import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { after, test } from "node:test"; const CLI = fileURLToPath(new URL("../dist/index.js", import.meta.url)); const built = await fs .access(CLI) .then(() => true) .catch(() => false); const home = await fs.mkdtemp(path.join(os.tmpdir(), "designpaca-cli-")); after(async () => { await fs.rm(home, { recursive: true, force: true }); }); /** 빌드 산출물을 사용자가 실행하는 방식 그대로 돌린다 */ function run(args: string[], cwd?: string): string { return execFileSync(process.execPath, [CLI, ...args, "--no-update-check"], { encoding: "utf8", ...(cwd ? { cwd } : {}), env: { ...process.env, HOME: home, USERPROFILE: home, FORCE_COLOR: "0", DESIGNPACA_STATE_DIR: path.join(home, ".designpaca"), }, }); } /** 종료 코드·stderr 까지 본다. stdin 을 닫아 TTY 가 아닌 환경을 흉내 낸다 */ function runRaw(args: string[], cwd?: string) { const r = spawnSync(process.execPath, [CLI, ...args, "--no-update-check"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], ...(cwd ? { cwd } : {}), env: { ...process.env, HOME: home, USERPROFILE: home, FORCE_COLOR: "0", DESIGNPACA_STATE_DIR: path.join(home, ".designpaca"), }, }); return { status: r.status, stdout: r.stdout, stderr: r.stderr }; } test("빌드 산출물이 있어야 한다", { skip: built ? false : "pnpm build 먼저 실행해라" }, () => { assert.ok(built); }); test("--version 은 스킬 버전과 같다", { skip: !built }, async () => { const stamp = ( await fs.readFile(fileURLToPath(new URL("../dist/skill/.designpaca_version", import.meta.url)), "utf8") ).trim(); assert.equal(run(["--version"]).trim(), stamp); // 스탬프를 --version 과만 비교하면 순환이다 — package.json 과의 일치까지 본다(AGENTS.md 4번 불변식) const pkg = JSON.parse(await fs.readFile(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")); assert.equal(stamp, pkg.version, "dist 가 오래됐다: 버전을 올린 뒤 pnpm build 를 다시 실행해라"); }); test("도움말에 모든 명령이 나온다", { skip: !built }, () => { const out = run(["--help"]); for (const cmd of ["install", "update", "uninstall", "doctor", "list"]) { assert.ok(out.includes(cmd), `도움말에 ${cmd} 가 없다`); } }); test("dry-run 은 아무 파일도 쓰지 않는다", { skip: !built }, async () => { const before = await fs.readdir(home); const out = run(["install", "-t", "claude-code", "-s", "user", "-y", "--dry-run"]); assert.ok(out.includes("설치 계획")); assert.deepEqual(await fs.readdir(home), before); }); test("알 수 없는 대상은 종료 코드 2 로 거부한다", { skip: !built }, () => { assert.throws( () => run(["install", "-t", "emacs", "-y"]), (err: { status?: number }) => err.status === 2, ); }); test("update --dry-run 은 파일도 매니페스트도 건드리지 않는다", { skip: !built }, async () => { run(["install", "-t", "claude-code", "-s", "user", "-y"]); const manifestFile = path.join(home, ".designpaca", "manifest.json"); const skillMd = path.join(home, ".claude", "skills", "designpaca", "SKILL.md"); // 업데이트 대상이 있는 상태를 만든다 const manifest = JSON.parse(await fs.readFile(manifestFile, "utf8")); manifest.installs[0].version = "0.0.1"; await fs.writeFile(manifestFile, JSON.stringify(manifest, null, 2) + "\n", "utf8"); const manifestBefore = await fs.readFile(manifestFile, "utf8"); const skillBefore = await fs.readFile(skillMd, "utf8"); const statBefore = await fs.stat(skillMd); const out = run(["update", "--dry-run"]); assert.ok(out.includes("업데이트 계획")); assert.ok(out.includes("설치 계획")); assert.equal(await fs.readFile(manifestFile, "utf8"), manifestBefore); assert.equal(await fs.readFile(skillMd, "utf8"), skillBefore); const statAfter = await fs.stat(skillMd); assert.equal(statAfter.mtimeMs, statBefore.mtimeMs); // 대조군: 실제 update 는 반영돼야 한다 run(["update"]); const manifestAfter = JSON.parse(await fs.readFile(manifestFile, "utf8")); assert.equal(manifestAfter.installs[0].version, run(["--version"]).trim()); run(["uninstall", "-y"]); }); test("uninstall --dry-run 은 아무것도 지우지 않는다", { skip: !built }, async () => { run(["install", "-t", "claude-code", "-s", "user", "-y"]); const skillMd = path.join(home, ".claude", "skills", "designpaca", "SKILL.md"); const manifestFile = path.join(home, ".designpaca", "manifest.json"); const out = run(["uninstall", "--dry-run"]); assert.ok(out.includes("제거 계획")); await fs.access(skillMd); const manifest = JSON.parse(await fs.readFile(manifestFile, "utf8")); assert.equal(manifest.installs.length, 1); run(["uninstall", "-y"]); await assert.rejects(() => fs.access(skillMd)); }); test("설치 → doctor → 제거 왕복", { skip: !built }, async () => { run(["install", "-t", "claude-code", "-s", "user", "-y"]); const skillMd = path.join(home, ".claude", "skills", "designpaca", "SKILL.md"); assert.ok((await fs.readFile(skillMd, "utf8")).includes("name: designpaca")); assert.ok(run(["doctor"]).includes("claude-code")); run(["uninstall", "-y"]); await assert.rejects(() => fs.access(skillMd)); }); test("update 는 project 설치를 기록된 root 에서 갱신하고 cwd 에는 아무것도 쓰지 않는다", { skip: !built }, async () => { // 보안 감사 P0 재현: repoA 에 project 설치 → 버전을 낮춤 → 무관한 repoB 에서 update. // 예전에는 repoB 의 AGENTS.md 에 블록이 주입되고 사용자가 만든 스킬이 백업 없이 덮였다. const repoA = path.join(home, "repoA"); const repoB = path.join(home, "repoB"); await fs.mkdir(repoA, { recursive: true }); await fs.mkdir(path.join(repoB, ".claude", "skills", "designpaca"), { recursive: true }); await fs.writeFile(path.join(repoB, "AGENTS.md"), "# repoB\n", "utf8"); const userSkill = path.join(repoB, ".claude", "skills", "designpaca", "SKILL.md"); await fs.writeFile(userSkill, "user own skill\n", "utf8"); const listB = async () => (await fs.readdir(repoB, { recursive: true })).map(String).sort(); const beforeB = await listB(); run(["install", "-t", "agents-md,claude-code", "-s", "project", "-y"], repoA); const manifestFile = path.join(home, ".designpaca", "manifest.json"); const manifest = JSON.parse(await fs.readFile(manifestFile, "utf8")); assert.equal(manifest.installs.length, 2); for (const rec of manifest.installs) rec.version = "0.0.1"; await fs.writeFile(manifestFile, JSON.stringify(manifest, null, 2) + "\n", "utf8"); run(["update"], repoB); // repoB 는 그대로다 assert.deepEqual(await listB(), beforeB); assert.equal(await fs.readFile(path.join(repoB, "AGENTS.md"), "utf8"), "# repoB\n"); assert.equal(await fs.readFile(userSkill, "utf8"), "user own skill\n"); // repoA 기록만 새 버전으로 갱신됐고, 새 기록이 생기지 않았다 const after = JSON.parse(await fs.readFile(manifestFile, "utf8")); const version = run(["--version"]).trim(); assert.equal(after.installs.length, 2); for (const rec of after.installs) { assert.equal(rec.version, version); assert.ok(path.resolve(rec.root).startsWith(path.resolve(repoA)), `기록 root 가 repoA 밖: ${rec.root}`); } assert.ok((await fs.readFile(path.join(repoA, "AGENTS.md"), "utf8")).includes("designpaca:start")); run(["uninstall", "-y"], repoB); await assert.rejects(() => fs.access(path.join(repoA, ".claude", "skills", "designpaca", "SKILL.md"))); assert.equal(await fs.readFile(userSkill, "utf8"), "user own skill\n"); }); test("알 수 없는 옵션은 종료 코드 2 로 거부하고 아무것도 실행하지 않는다", { skip: !built }, () => { for (const flag of ["--dryrun", "--dry_run", "--forse", "--yes=true", "-x"]) { const r = runRaw(["uninstall", flag]); assert.equal(r.status, 2, `${flag} 가 거부되지 않았다`); assert.ok(r.stderr.includes("알 수 없는 옵션"), r.stderr); } const r = runRaw(["install", "foo", "-y"]); assert.equal(r.status, 2); assert.ok(r.stderr.includes("알 수 없는 인자")); // --help 는 다른 입력 오류보다 먼저 처리된다 assert.equal(runRaw(["--help", "--dryrun"]).status, 0); }); test("값 옵션에 값이 없거나 비면 종료 코드 2 다", { skip: !built }, () => { for (const args of [ ["install", "-t"], ["install", "-t", "-y"], ["install", "--target="], ["install", "-t", ",,"], ["install", "-s"], ["install", "--scope="], ]) { const r = runRaw(args); assert.equal(r.status, 2, `${args.join(" ")} 가 거부되지 않았다`); assert.ok(r.stderr.includes("값이 필요합니다"), r.stderr); } }); test("종료 코드: 잘못된 범위와 알 수 없는 명령은 2, 기록 없는 update 는 1", { skip: !built }, () => { assert.equal(runRaw(["install", "-s", "galaxy", "-y"]).status, 2); assert.equal(runRaw(["frobnicate"]).status, 2); assert.equal(runRaw(["update"]).status, 1); assert.equal(runRaw(["doctor"]).status, 0); assert.equal(runRaw(["ls"]).status, 0); assert.equal(runRaw(["list"]).status, 0); }); test("stdin 이 TTY 가 아니면 인자 없이 실행해도 프롬프트 없이 사용법을 낸다", { skip: !built }, () => { const r = runRaw([]); assert.equal(r.status, 0); assert.ok(r.stdout.includes("사용법")); const d = runRaw(["install", "--dry-run"]); assert.equal(d.status, 0); assert.ok(d.stdout.includes("설치 계획")); }); test("중복 대상은 한 번만 설치한다", { skip: !built }, () => { const r = runRaw(["install", "-t", "claude-code,claude-code", "-t", "claude-code", "-y"]); assert.equal(r.status, 0); assert.equal(r.stdout.split("claude-code — 설치됨").length - 1, 1, r.stdout); runRaw(["uninstall", "-y"]); }); test("uninstall -s 는 지정한 범위만 지우고, 범위를 안 주면 모두 지운다", { skip: !built }, async () => { const proj = path.join(home, "scope-proj"); await fs.mkdir(proj, { recursive: true }); const userSkill = path.join(home, ".claude", "skills", "designpaca", "SKILL.md"); const projSkill = path.join(proj, ".claude", "skills", "designpaca", "SKILL.md"); runRaw(["install", "-t", "claude-code", "-s", "user", "-y"], proj); runRaw(["install", "-t", "claude-code", "-s", "project", "-y"], proj); await fs.access(userSkill); await fs.access(projSkill); assert.equal(runRaw(["uninstall", "-t", "claude-code", "-s", "project", "-y"], proj).status, 0); await assert.rejects(() => fs.access(projSkill)); await fs.access(userSkill); // user 설치는 남아야 한다 runRaw(["install", "-t", "claude-code", "-s", "project", "-y"], proj); assert.equal(runRaw(["uninstall", "-y"], proj).status, 0); await assert.rejects(() => fs.access(userSkill)); await assert.rejects(() => fs.access(projSkill)); }); test("설치본이 CLI 보다 새로우면 update 는 건너뛰고 doctor 는 문제로 세지 않는다", { skip: !built }, async () => { runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]); const manifestFile = path.join(home, ".designpaca", "manifest.json"); const skillMd = path.join(home, ".claude", "skills", "designpaca", "SKILL.md"); const manifest = JSON.parse(await fs.readFile(manifestFile, "utf8")); manifest.installs[0].version = "99.0.0"; await fs.writeFile(manifestFile, JSON.stringify(manifest, null, 2) + "\n", "utf8"); const manifestBefore = await fs.readFile(manifestFile, "utf8"); const statBefore = await fs.stat(skillMd); const up = runRaw(["update"]); assert.equal(up.status, 0, up.stdout); assert.ok(up.stdout.includes("건너뛴다"), up.stdout); assert.equal(await fs.readFile(manifestFile, "utf8"), manifestBefore, "다운그레이드가 기록을 바꿨다"); assert.equal((await fs.stat(skillMd)).mtimeMs, statBefore.mtimeMs); const doc = runRaw(["doctor"]); assert.equal(doc.status, 0, doc.stdout); assert.ok(doc.stdout.includes("더 오래됨"), doc.stdout); assert.ok(!doc.stdout.includes("업데이트 가능")); // --force 일 때만 다시 쓴다 assert.equal(runRaw(["update", "--force"]).status, 0); const after = JSON.parse(await fs.readFile(manifestFile, "utf8")); assert.equal(after.installs[0].version, run(["--version"]).trim()); runRaw(["uninstall", "-y"]); }); test("사용자가 수정한 파일은 install 이 건너뛰고 --force 는 .orig 로 백업한다", { skip: !built }, async () => { runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]); const skillMd = path.join(home, ".claude", "skills", "designpaca", "SKILL.md"); await fs.appendFile(skillMd, "\n내 메모\n", "utf8"); const edited = await fs.readFile(skillMd, "utf8"); runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]); assert.equal(await fs.readFile(skillMd, "utf8"), edited, "수정 파일을 덮어썼다"); assert.equal(runRaw(["install", "-t", "claude-code", "-s", "user", "-y", "--force"]).status, 0); assert.notEqual(await fs.readFile(skillMd, "utf8"), edited); assert.equal(await fs.readFile(skillMd + ".orig", "utf8"), edited); await fs.rm(skillMd + ".orig", { force: true }); runRaw(["uninstall", "-y"]); }); /** 매니페스트에 "이전 버전이 깔았던 파일"을 심는다 — 새 버전 계획에 없는 파일이 stale 이 된다 */ async function plantStale(rel: string, content: string): Promise { const manifestFile = path.join(home, ".designpaca", "manifest.json"); const m = JSON.parse(await fs.readFile(manifestFile, "utf8")); const rec = m.installs[0]; const file = path.join(rec.root, ...rel.split("/")); await fs.mkdir(path.dirname(file), { recursive: true }); await fs.writeFile(file, content, "utf8"); const { createHash } = await import("node:crypto"); rec.files.push({ path: file, sha256: createHash("sha256").update(content).digest("hex") }); await fs.writeFile(manifestFile, JSON.stringify(m, null, 2), "utf8"); return file; } test("새 버전에서 빠진 파일은 지우고 안내하며, 수정돼 있으면 남기고 안내한다", { skip: !built }, async () => { runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]); const gone = await plantStale("references/old-removed.md", "예전 문서\n"); const r1 = runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]); assert.match(r1.stdout, /새 버전에서 빠진 파일 1개를 제거/); await assert.rejects(fs.access(gone), "빠진 파일이 남아 있다"); const kept = await plantStale("references/old-edited.md", "예전 문서\n"); await fs.appendFile(kept, "내 메모\n", "utf8"); const r2 = runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]); assert.match(r2.stdout, /새 버전에서 빠졌지만 수정돼 있어 남겨 두었습니다/); await fs.access(kept); runRaw(["uninstall", "-y", "--force"]); }); test("다른 대상과 경로를 공유하는 파일은 uninstall 이 남기고 안내한다", { skip: !built }, async () => { const proj = await fs.mkdtemp(path.join(os.tmpdir(), "designpaca-shared-")); try { runRaw(["install", "-t", "agents,antigravity", "-s", "project", "-y"], proj); const r = runRaw(["uninstall", "-t", "agents", "-s", "project", "-y"], proj); assert.match(r.stdout, /다른 대상과 공유 중이라 남긴 파일 \d+개/); runRaw(["uninstall", "-y"], proj); } finally { await fs.rm(proj, { recursive: true, force: true }); } });