fix(core,cli): harden install engine and argument parsing

- Reject unknown flags with exit 2 and never write on --dry-run, even in a TTY
- Treat files already matching the new content as up to date after an interrupted update
- Remove unmodified orphan files from older versions, keep and report modified ones and shared paths
- Degrade malformed manifests instead of blocking installs; readIfExists only maps ENOENT/ENOTDIR to null
- Block downgrades from older CLIs (semver), honor uninstall --scope, dedupe targets, fix next-step output and table width
- Deeper package verification, LF normalization for .mjs, MIT LICENSE
This commit is contained in:
Yun Chan 2026-10-09 18:18:49 +09:00
parent 97f2c241e4
commit eecd3f03ff
29 changed files with 867 additions and 124 deletions

View file

@ -25,8 +25,6 @@ const skill: SkillSource = {
version: "9.9.9",
skillMd: ['---', 'name: designpaca', 'description: "테스트용"', '---', '', BODY, ''].join("\n"),
files: new Map([["references/tokens.md", "# 토큰\n"]]),
body: BODY,
description: "테스트용",
};
const env = { home, cwd };
@ -156,7 +154,10 @@ test("windsurf: 네이티브 스킬 경로에 싣는다 — 본문 크기 제한
// 예전 규칙 파일 방식은 12,000자 상한 때문에 실제 스킬(본문 25KB)이 막혔다.
// 네이티브 스킬은 본문을 통째로 프롬프트에 넣지 않으므로 큰 본문도 설치돼야 한다.
const huge: SkillSource = { ...skill, body: "가".repeat(13_000) };
const huge: SkillSource = {
...skill,
skillMd: `${skill.skillMd}${"가".repeat(13_000)}`,
};
const hugePlan = await planInstall("windsurf", "project", huge, env);
assert.ok(!hugePlan.blocked, "본문이 크다고 막히면 안 된다");

View file

@ -83,3 +83,16 @@ test("문서 중간 블록을 빼면 블록 앞뒤 구분 빈 줄 하나만 걷
const doc = "A\n\n<!-- designpaca:start -->\nx\n<!-- designpaca:end -->\n\nB\n";
assert.equal(removeBlock(doc, M), "A\n\nB\n");
});
test("CRLF 문서에는 CRLF 블록을 주입하고 제거하면 원문으로 돌아온다", () => {
const doc = "# 내 지침\r\n\r\n건드리지 마라.\r\n";
const out = upsertBlock(doc, M, "첫 줄\n둘째 줄");
assert.ok(!/(^|[^\r])\n/.test(out), "LF 단독 줄바꿈이 섞이면 안 된다");
assert.equal(extractBlock(out, M), "첫 줄\r\n둘째 줄");
assert.equal(removeBlock(out, M), doc);
});
test("LF 문서에는 LF 블록을 주입한다", () => {
const out = upsertBlock("# 지침\n", M, "본문");
assert.ok(!out.includes("\r"));
});

View file

@ -3,9 +3,17 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { after, test } from "node:test";
import { assertNoLinksBelow, backup, removeFileAndPrune, sha256, writeAtomic } from "../src/fsx.ts";
import {
assertNoLinksBelow,
backup,
readIfExists,
readOrNull,
removeFileAndPrune,
sha256,
writeAtomic,
} from "../src/fsx.ts";
import { applyPlan, envForRecord, planForRecord, planInstall, removeInstall } from "../src/installer.ts";
import { readManifest, writeManifest } from "../src/manifest.ts";
import { inspectDrift, readManifest, writeManifest } from "../src/manifest.ts";
import type { InstallRecord, SkillSource } from "../src/types.ts";
// 보안 감사(2026-10-01) 재현 시나리오를 회귀 테스트로 고정한다. 모든 쓰기는 임시 디렉터리 안에서만 한다.
@ -18,8 +26,6 @@ const skill: SkillSource = {
version: "9.9.9",
skillMd: ["---", "name: designpaca", 'description: "테스트용"', "---", "", "# 본문", ""].join("\n"),
files: new Map([["references/tokens.md", "# 토큰\n"]]),
body: "# 본문",
description: "테스트용",
};
async function fresh(name: string): Promise<{ home: string; cwd: string; outside: string }> {
@ -205,3 +211,151 @@ test("손상된 매니페스트는 덮기 전에 .corrupt-* 로 보존한다", a
const kept = (await fs.readdir(path.dirname(file))).filter((n) => n.startsWith("manifest.json.corrupt-"));
assert.equal(kept.length, 1);
});
// ---- 감사(2026-10) 회귀: 중단된 update·고아 파일·읽기 실패·손상 매니페스트·공유 root ----
function withFiles(version: string, files: [string, string][]): SkillSource {
return { ...skill, version, files: new Map(files) };
}
test("중단된 update: 디스크가 이미 새 내용이면 드리프트로 보지 않는다", async () => {
const { home, cwd } = await fresh("interrupted");
const env = { home, cwd };
const v1 = withFiles("1.0.0", [["references/a.md", "v1\n"]]);
const v2 = withFiles("2.0.0", [["references/a.md", "v2\n"]]);
const plan1 = await planInstall("claude-code", "project", v1, env);
await applyPlan(plan1, "1.0.0", { env });
// update 중간 크래시 모사: 파일만 v2 로 쓰이고 매니페스트는 v1 그대로
const a = path.join(plan1.root, "references", "a.md");
await fs.writeFile(a, "v2\n", "utf8");
const plan2 = await planInstall("claude-code", "project", v2, env);
const res = await applyPlan(plan2, "2.0.0", { env });
assert.deepEqual(res.skipped, []);
assert.equal(res.backedUp.length, 0);
const rec = (await readManifest(home)).installs[0]!;
assert.equal((await inspectDrift(rec)).modified.length, 0);
});
test("사용자 편집이 새 버전과 다르면 여전히 건너뛴다", async () => {
const { home, cwd } = await fresh("still-dirty");
const env = { home, cwd };
const v1 = withFiles("1.0.0", [["references/a.md", "v1\n"]]);
const v2 = withFiles("2.0.0", [["references/a.md", "v2\n"]]);
const plan1 = await planInstall("claude-code", "project", v1, env);
await applyPlan(plan1, "1.0.0", { env });
const a = path.join(plan1.root, "references", "a.md");
await fs.writeFile(a, "내가 고침\n", "utf8");
const res = await applyPlan(await planInstall("claude-code", "project", v2, env), "2.0.0", { env });
assert.deepEqual(res.skipped, [a]);
assert.equal(await fs.readFile(a, "utf8"), "내가 고침\n");
// 기록은 설치 당시 해시를 유지한다
const kept = (await readManifest(home)).installs[0]!.files.find((f) => f.path === a)!;
assert.equal(kept.sha256, sha256("v1\n"));
});
test("새 버전에서 빠진 파일은 지우고, 사용자가 고친 것은 보존한다", async () => {
const { home, cwd } = await fresh("orphans");
const env = { home, cwd };
const v1 = withFiles("1.0.0", [
["references/keep.md", "k\n"],
["references/old.md", "o\n"],
["references/edited.md", "e\n"],
]);
const v2 = withFiles("2.0.0", [["references/keep.md", "k\n"]]);
const plan1 = await planInstall("claude-code", "project", v1, env);
await applyPlan(plan1, "1.0.0", { env });
const old = path.join(plan1.root, "references", "old.md");
const edited = path.join(plan1.root, "references", "edited.md");
await fs.writeFile(edited, "내 수정\n", "utf8");
const res = await applyPlan(await planInstall("claude-code", "project", v2, env), "2.0.0", { env });
assert.deepEqual(res.removedStale, [old]);
assert.deepEqual(res.keptStale, [edited]);
await assert.rejects(fs.access(old));
assert.equal(await fs.readFile(edited, "utf8"), "내 수정\n");
const files = (await readManifest(home)).installs[0]!.files;
assert.ok(
files.some((f) => f.path === edited && f.sha256 === sha256("e\n")),
"보존한 파일은 원래 해시로 기록에 남는다",
);
assert.ok(!files.some((f) => f.path === old));
});
test("readIfExists: 없는 파일만 null, 그 밖의 읽기 실패는 던진다", async () => {
const { cwd } = await fresh("readerr");
assert.equal(await readIfExists(path.join(cwd, "없음.md")), null);
assert.equal(await readIfExists(path.join(cwd, "없음.md", "아래")), null);
// 디렉터리를 파일처럼 읽으면 EISDIR — 예전에는 null("없음")로 삼켰다
await assert.rejects(readIfExists(cwd));
assert.equal(await readOrNull(cwd), null);
});
test("읽을 수 없는 AGENTS.md 는 덮지 않고 설치를 멈춘다 (POSIX 일반 사용자)", async () => {
// AGENTS.md 규칙 1 때문에 test.skip 을 쓰지 않는다 — 환경이 안 맞으면 본문을 건너뛴다
if (process.platform === "win32" || process.getuid?.() === 0) return;
const { home, cwd } = await fresh("unreadable");
const doc = path.join(cwd, "AGENTS.md");
await fs.writeFile(doc, "# 내 지침\n", "utf8");
await fs.chmod(doc, 0o000);
try {
const plan = await planInstall("agents-md", "project", skill, { home, cwd });
await assert.rejects(applyPlan(plan, skill.version, { env: { home, cwd } }));
} finally {
await fs.chmod(doc, 0o644);
}
assert.equal(await fs.readFile(doc, "utf8"), "# 내 지침\n");
});
test("형태가 깨진 매니페스트 레코드는 빈 매니페스트로 강등하고 원본을 보존한다", async () => {
const { home, cwd } = await fresh("shape");
const file = path.join(home, ".designpaca", "manifest.json");
await fs.mkdir(path.dirname(file), { recursive: true });
const broken = [
{ schema: 1, installs: [null] },
{ schema: 1, installs: [{ target: "codex", scope: "user", root: "/x" }] },
];
for (const bad of broken) {
await fs.writeFile(file, JSON.stringify(bad), "utf8");
assert.equal((await readManifest(home)).installs.length, 0);
const plan = await planInstall("claude-code", "project", skill, { home, cwd });
await applyPlan(plan, skill.version, { env: { home, cwd } });
const kept = (await fs.readdir(path.dirname(file))).filter((n) => n.startsWith("manifest.json.corrupt-"));
assert.ok(kept.length >= 1, "원본이 .corrupt-* 로 남아야 한다");
await removeInstall((await readManifest(home)).installs[0]!, { env: { home }, force: true });
}
// 유효한 레코드는 그대로 읽힌다
const ok: InstallRecord = {
target: "claude-code",
scope: "user",
root: path.join(home, "r"),
version: "1",
installedAt: "x",
files: [{ path: path.join(home, "r", "a"), sha256: "h" }],
};
await writeManifest({ schema: 1, installs: [ok] }, home);
assert.equal((await readManifest(home)).installs.length, 1);
});
test("project 범위에서 agents 와 antigravity 가 root 를 공유해도 한쪽 제거가 다른 쪽을 깨지 않는다", async () => {
const { home, cwd } = await fresh("shared-root");
const env = { home, cwd };
const pa = await planInstall("agents", "project", skill, env);
const pg = await planInstall("antigravity", "project", skill, env);
assert.equal(pa.root, pg.root);
const ra = await applyPlan(pa, skill.version, { env });
const rg = await applyPlan(pg, skill.version, { env });
const first = await removeInstall(ra.record, { env });
assert.equal(first.removed.length, 0);
assert.equal(first.sharedKept.length, ra.record.files.length);
await fs.access(path.join(pa.root, "SKILL.md"));
const left = (await readManifest(home)).installs;
assert.equal(left.length, 1);
assert.equal((await inspectDrift(left[0]!)).files.every((f) => f.status === "ok"), true);
const last = await removeInstall(rg.record, { env });
assert.equal(last.sharedKept.length, 0);
await assert.rejects(fs.access(path.join(pa.root, "SKILL.md")));
});