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

@ -24,7 +24,7 @@ Key packaging fact: when the CLI builds, `@designpaca/core` is bundled into the
## Commands
```bash
pnpm install # pnpm 10.x, Node >= 20.11
pnpm install # pnpm 10.x; dev/CI need Node >= 22.6 (see Node versions below)
pnpm build # skill bundle + CLI build (packages only)
pnpm typecheck # tsc --noEmit in packages
pnpm test # node:test across all packages
@ -69,17 +69,29 @@ node tools/visual.mjs --update-baseline # refresh visual baselines, then commi
10. **Never soften the step-0 interview gate.** v0.11.0 (`45ba92e`) rewrote "almost always ask" into "ask only when it would change the result", with an empty commit body and no changelog line. Combined with harness autonomy pressure (Claude Code auto mode, Codex "bias to action"), the skill stopped asking users. `build/ci/lint-skill.mjs` now fails if the `## 인터뷰 게이트` section, the "명시적으로 의존한다" sentence, or the `harness.md`/`brief-interview.md` links disappear, or if a "~때만 묻는다" condition returns. Any change to when the skill asks must be stated in its changeset and re-checked with `build/eval/interview/` on Claude Code and Codex.
11. **Keep tool names harness-neutral in the skill body.** Every target adapter copies `SKILL.md` verbatim, so a Claude-only tool name (e.g. `AskUserQuestion`) reaches Codex, Cursor, Gemini, and others unchanged. Put per-harness tool names, limits, and fallbacks in `references/harness.md`, not in the body.
### Node versions
- Installed CLI runtime: `engines.node >= 20.11` (`packages/cli/package.json`). Do not use anything newer in shipped `dist` code.
- Development and CI: Node >= 22.6, because tests run `node --test --experimental-strip-types`. `build/ci/verify-node.sh` enforces this on the runner (`MIN_MAJOR=22`, `MIN_MINOR=6`).
### Scratch and eval
- `outputs/` is gitignored scratch space; never rely on anything there being committed.
- `build/eval/interview/` runs agent sessions in a temp directory outside the repo (`os.tmpdir()/dp-eval-*`) and refuses to start if an ancestor holds `AGENTS.md`/`CLAUDE.md`/`.git`, so repo instructions cannot contaminate a run. Per-run records are kept inside the repo.
## Architecture & data flow
### Install pipeline (core)
- `targets/*.ts` — one adapter per destination tool (claude-code, codex, cursor, zcode, agents, antigravity, gemini-cli, windsurf, copilot, agents-md). Each implements `detect()` (any trace on system → preselected in TUI) and `plan()` which returns a pure `InstallPlan` (list of file actions, **no disk writes**).
- Two adapter shapes: `skillDirActions()` copies the whole skill directory (Claude Code, Codex — SKILL.md used verbatim), `referenceActions()`/injection split the body from references (Cursor, AGENTS.md). For the latter, `rewriteRefPaths()` rewrites `references/...` links to the actual install location — without this the body points at nonexistent paths.
- One shape: every adapter builds its file list with `skillDirActions()` (whole skill directory; `SKILL.md` verbatim). The `agents-md` adapter additionally injects a pointer block into `AGENTS.md` and runs `rewriteRefPaths()` over the `SKILL.md` copy it unpacks to a separate directory — without that, `references/...` links point at nonexistent paths. There is no body/reference split any more.
- `installer.ts` — `planInstall()` → `applyPlan()`. Safety semantics (do not break these):
- User-modified files (drift detected via stored sha256) are **skipped** unless `--force`; force still backs up to `.orig`.
- Skipped files stay in the manifest with their **original install-time hash** — using the current hash would make drift vanish and a later update silently overwrite user edits.
- Marker-injected files (`AGENTS.md` etc.) hash only the content inside `<!-- designpaca:start/end -->` blocks; the rest of the user's document is untouchable.
- `manifest.ts` — install records in `~/.designpaca/manifest.json`. Uninstall only removes recorded files; corrupted manifest degrades to empty rather than blocking installs.
- Orphans (files a previous install recorded but the new plan no longer contains): unmodified ones are deleted (`ApplyResult.removedStale`); modified ones, marker-injected docs and out-of-bounds paths are kept and stay in the manifest with their original hash (`keptStale`). On uninstall, a path another record also owns is kept (`RemoveResult.sharedKept`, e.g. `agents` + `antigravity` in project scope). The CLI reports all three.
- `readIfExists()` returns `null` only for `ENOENT`/`ENOTDIR` and throws on anything else (permissions, locks) — treating an unreadable user document as absent would overwrite it without a backup. `readOrNull()` swallows every error and is only for disposable files such as the update-check cache.
- `manifest.ts` — install records in `~/.designpaca/manifest.json`. Uninstall only removes recorded files; a manifest that fails to parse or has the wrong shape (schema, record fields) degrades to empty rather than blocking installs, and `writeManifest` keeps the original as `.corrupt-*` before overwriting. Degradation applies only to those two cases; I/O errors still throw.
- AGENTS.md adapter deliberately injects **a pointer only**, not the skill body — AGENTS.md loads unconditionally in every session and Codex truncates around 32 KiB. If you change this adapter, keep that reasoning in mind.
### CLI (packages/cli)

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Yun Chan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -9,7 +9,7 @@ CI는 self-hosted **`linux-builder`** 러너(host 모드)에서 돈다. host 모
| 필요 | 확인 | 없을 때 |
|---|---|---|
| Node 20 이상 | `node -v` | `fnm install 22 && fnm default 22` 후 러너 재시작 |
| Node 22.6 이상 | `node -v` | `fnm install 22 && fnm default 22` 후 러너 재시작 |
| pnpm 10 | `pnpm -v` | `corepack enable && corepack prepare pnpm@10.5.2 --activate` |
| git, curl, tar, python3 | `command -v` | 배포판 패키지로 설치 |
@ -35,7 +35,7 @@ git.chanpaca.net/<owner>/designpaca
| 이름 | 용도 | 발급처 |
|---|---|---|
| `NPM_TOKEN` | npmjs 배포 | npmjs.com → Access Tokens → **Automation** 타입 |
| `NPM_TOKEN` | npmjs 배포 (**태그 릴리스 필수** — 없으면 `publish-npm.sh` 가 exit 1) | npmjs.com → Access Tokens → **Automation** 타입 |
| `FORGEJO_NPM_TOKEN` | 사설 레지스트리 미러 | Forgejo → 설정 → 애플리케이션 → 액세스 토큰 (`write:package` 권한) |
| `RELEASE_TOKEN` | 릴리스 생성·자산 업로드 | Forgejo 액세스 토큰 (`write:repository`) |
| `CF_API_TOKEN` | Cloudflare Pages 배포 | Cloudflare → API Tokens → **Edit Cloudflare Workers** 템플릿 |
@ -47,8 +47,8 @@ git.chanpaca.net/<owner>/designpaca
|---|---|---|
| `FORGEJO_NPM_OWNER` | `yunchan` | 사설 npm 패키지 소유자 |
> **시크릿이 없어도 파이프라인은 죽지 않는다.** `publish-npm.sh`는 `FORGEJO_NPM_TOKEN`이 없으면 미러를 건너뛰고,
> 릴리스 스텝은 `CF_API_TOKEN`이 없으면 페이지 배포를 건너뛴다. 하나씩 붙여가며 굴릴 수 있다.
> **`NPM_TOKEN` 은 필수다.** 없으면 `publish-npm.sh` 가 exit 1 로 멈춘다. 나머지는 선택이다 — `publish-npm.sh`는 `FORGEJO_NPM_TOKEN`이 없으면 미러를 건너뛰고,
> 릴리스 스텝은 `CF_API_TOKEN`이 없으면 페이지 배포를 건너뛴다.
## 3. 릴리스 절차
@ -151,7 +151,7 @@ SSH 키는 이미 Forgejo 에 등록돼 있어(`encep-win`) 토큰도 비밀번
| # | 증상 | 원인 |
|---|---|---|
| 1 | `exit 126` / 허가 거부 | Windows 에서 만든 `.sh` 가 mode 100644 로 커밋됐다. `git update-index --chmod=+x` + 워크플로에서 `bash script` 로 호출 |
| 2 | `Node 20 이상이 필요하다 (현재 v18)` | 러너에 Node 18 뿐. fnm 으로 22 설치. **그리고 `verify-node.sh` 가 Node 가 *없을 때만* 대체 경로를 훑고 있었다** — 낡았을 때도 찾도록 고침 |
| 2 | `Node 20 이상이 필요하다 (현재 v18)` (당시 메시지. 현재 기준은 22.6 이상) | 러너에 Node 18 뿐. fnm 으로 22 설치. **그리고 `verify-node.sh` 가 Node 가 *없을 때만* 대체 경로를 훑고 있었다** — 낡았을 때도 찾도록 고침 |
| 3 | `ERR_MODULE_NOT_FOUND: picocolors` | tarball 을 풀어 `node dist/index.js` 를 직접 불렀다. 그건 npx 경로가 아니다. 임시 프로젝트에 `npm i` 후 실행하도록 교체 |
| 4 | 초록불인데 `# pass 0` | 빌드보다 테스트가 먼저라 CLI 테스트 6개가 전부 SKIP. 순서를 바꾸고 **SKIP 이 있으면 실패시키는 단계**를 넣었다 |

21
packages/cli/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Yun Chan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -25,7 +25,8 @@
},
"files": [
"dist",
"README.md"
"README.md",
"LICENSE"
],
"engines": {
"node": ">=20.11"

View file

@ -13,7 +13,8 @@ const dest = path.resolve(here, "../dist/skill");
// Windows 에서 작업하면 파일이 CRLF 로 저장되고, 그대로 tarball 에 들어가면
// SKILL.md 의 YAML 프론트매터를 파서에 따라 못 읽는다.
// 배포물은 어느 OS 에서 만들었는지와 무관하게 같아야 한다.
const TEXT = new Set([".md", ".txt", ".json", ".yml", ".yaml"]);
// .mjs 도 포함한다 — tools/*.mjs 가 설치물이라 같은 바이트 동일성 원칙이 적용된다.
const TEXT = new Set([".md", ".txt", ".json", ".yml", ".yaml", ".mjs", ".js", ".cjs"]);
const excluded = [];

View file

@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
import { isAllowedSkillFile } from "./skill-allowlist.mjs";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const must = ["dist/index.js", "dist/skill/SKILL.md", "dist/skill/.designpaca_version"];
const must = ["dist/index.js", "dist/skill/SKILL.md", "dist/skill/.designpaca_version", "LICENSE"];
const missing = [];
for (const rel of must) {
@ -40,4 +40,45 @@ if (unexpected.length) {
console.error("scripts/skill-allowlist.mjs 를 확인하고 pnpm build 를 다시 실행해라.");
process.exit(1);
}
// SKILL.md 가 비었거나 프론트매터가 깨졌거나 본문이 링크한 문서가 빠졌으면 배포하지 않는다
const skillMd = await fs.readFile(path.join(skillDir, "SKILL.md"), "utf8");
if (!skillMd.startsWith("---\nname: designpaca\n")) {
console.error('dist/skill/SKILL.md 의 프론트매터가 "name: designpaca" 로 시작하지 않는다 (비었거나 CRLF·손상)');
process.exit(1);
}
const brokenLinks = [];
for (const m of skillMd.matchAll(/\]\((references\/[^)#\s]+)/g)) {
try {
await fs.access(path.join(skillDir, m[1]));
} catch {
brokenLinks.push(m[1]);
}
}
if (brokenLinks.length) {
const list = [...new Set(brokenLinks)].map((m) => ` - ${m}`).join("\n");
console.error(`SKILL.md 가 링크한 문서가 배포물에 없다:\n${list}`);
process.exit(1);
}
// 텍스트는 LF 여야 한다 — 정규화 대상 확장자가 빠졌을 때 여기서 잡는다
const crlf = [];
for (const e of await fs.readdir(skillDir, { recursive: true, withFileTypes: true })) {
if (!e.isFile() || !/\.(md|txt|json|ya?ml|mjs|c?js)$/.test(e.name)) continue;
const full = path.join(e.parentPath ?? e.path, e.name);
if ((await fs.readFile(full, "utf8")).includes("\r\n")) {
crlf.push(path.relative(skillDir, full).split(path.sep).join("/"));
}
}
if (crlf.length) {
console.error(`CRLF 가 남은 파일:\n${crlf.map((m) => ` - ${m}`).join("\n")}`);
process.exit(1);
}
// 실행 진입점은 첫 줄이 shebang 이어야 한다(tsup banner)
const indexHead = (await fs.readFile(path.join(root, "dist/index.js"), "utf8")).split("\n", 1)[0];
if (indexHead !== "#!/usr/bin/env node") {
console.error("dist/index.js 첫 줄이 shebang 이 아니다 (tsup banner 확인)");
process.exit(1);
}
console.log(`배포 점검 통과 (v${pkg.version})`);

View file

@ -1,4 +1,5 @@
import { inspectDrift, pruneDeadInstalls, readManifest, tildify } from "@designpaca/core";
import { isNewer } from "../semver.ts";
import { getVersion } from "../skill.ts";
import { bad, dim, heading, info, ok, table, warn } from "../ui.ts";
@ -25,6 +26,8 @@ export async function runDoctor(): Promise<number> {
let problems = 0;
for (const rec of manifest.installs) {
const drift = await inspectDrift(rec);
const outdated = isNewer(version, rec.version);
const cliOlder = isNewer(rec.version, version);
const missing = drift.files.filter((f) => f.status === "missing");
const modified = drift.files.filter((f) => f.status === "modified");
@ -32,12 +35,19 @@ export async function runDoctor(): Promise<number> {
console.log(
table([
["위치", tildify(rec.root)],
["버전", rec.version === version ? rec.version : `${rec.version} → ${version} 업데이트 가능`],
[
"버전",
outdated
? `${rec.version} → ${version} 업데이트 가능`
: cliOlder
? `${rec.version} (이 CLI v${version} 가 더 오래됨 — npx designpaca@latest 로 실행)`
: rec.version,
],
["파일", `${rec.files.length}개`],
]),
);
if (rec.version !== version) problems++;
if (outdated) problems++;
if (missing.length > 0) {
problems++;
console.log(bad(`파일 ${missing.length}개가 보이지 않습니다 — \`designpaca update --force\` 로 복구하실 수 있습니다`));
@ -47,7 +57,7 @@ export async function runDoctor(): Promise<number> {
console.log(warn(`직접 수정한 파일 ${modified.length}개 — 업데이트가 이 파일들을 건너뛴다`));
for (const m of modified.slice(0, 5)) console.log(dim(` ${tildify(m.path)}`));
}
if (missing.length === 0 && modified.length === 0 && rec.version === version) {
if (missing.length === 0 && modified.length === 0 && !outdated) {
console.log(ok("정상"));
}
}

View file

@ -32,6 +32,10 @@ export interface InstallOutcome {
skipped: string[];
/** 덮기 전에 남긴 백업(.orig) */
backedUp?: string[];
/** 새 버전에서 빠져 지운 이전 설치 파일 */
removedStale?: string[];
/** 새 버전에서 빠졌지만 수정돼 있어 남긴 파일 */
keptStale?: string[];
blocked?: string;
}
@ -68,6 +72,8 @@ export async function runInstall(opts: InstallOptions): Promise<InstallOutcome[]
written: res.written.length,
skipped: res.skipped,
backedUp: res.backedUp,
removedStale: res.removedStale,
keptStale: res.keptStale,
});
}
return outcomes;
@ -90,6 +96,14 @@ export function printOutcomes(outcomes: InstallOutcome[], dryRun = false): void
console.log(warn(` 기존 파일을 덮기 전에 백업해 두었습니다:`));
for (const b of fold(o.backedUp)) console.log(dim(` ${tildify(b)}`));
}
if (o.removedStale && o.removedStale.length > 0) {
console.log(info(` 새 버전에서 빠진 파일 ${o.removedStale.length}개를 제거했습니다:`));
for (const r of fold(o.removedStale)) console.log(dim(` ${tildify(r)}`));
}
if (o.keptStale && o.keptStale.length > 0) {
console.log(warn(` 새 버전에서 빠졌지만 수정돼 있어 남겨 두었습니다 (uninstall --force 로 지울 수 있습니다):`));
for (const k of fold(o.keptStale)) console.log(dim(` ${tildify(k)}`));
}
}
}

View file

@ -1,14 +1,18 @@
import { readManifest, removeInstall, tildify, type TargetId } from "@designpaca/core";
import { dim, heading, ok, warn } from "../ui.ts";
import { readManifest, removeInstall, tildify, type Scope, type TargetId } from "@designpaca/core";
import { dim, heading, info, ok, warn } from "../ui.ts";
export async function runUninstall(opts: {
targets?: TargetId[];
/** 직접 지정했을 때만 넘긴다 — 기본값으로 걸러 내면 project 설치를 놓친다 */
scope?: Scope;
force?: boolean;
dryRun?: boolean;
}): Promise<number> {
const manifest = await readManifest();
const targets = manifest.installs.filter(
(i) => !opts.targets || opts.targets.length === 0 || opts.targets.includes(i.target),
(i) =>
(!opts.targets || opts.targets.length === 0 || opts.targets.includes(i.target)) &&
(opts.scope === undefined || i.scope === opts.scope),
);
if (targets.length === 0) {
@ -29,6 +33,10 @@ export async function runUninstall(opts: {
);
for (const p of res.keptModified.slice(0, 5)) console.log(dim(` ${tildify(p)}`));
}
if (res.sharedKept.length > 0) {
console.log(info(` 다른 대상과 공유 중이라 남긴 파일 ${res.sharedKept.length}개 (그 대상을 제거할 때 함께 지워진다)`));
for (const p of res.sharedKept.slice(0, 5)) console.log(dim(` ${tildify(p)}`));
}
if (res.refused.length > 0) {
code = 1;
console.log(

View file

@ -1,5 +1,6 @@
import { envForRecord, inspectDrift, readManifest, tildify } from "@designpaca/core";
import { getVersion } from "../skill.ts";
import { isNewer } from "../semver.ts";
import { runInstall, printOutcomes } from "./install.ts";
import { bad, dim, heading, info, ok, warn } from "../ui.ts";
@ -17,10 +18,23 @@ export async function runUpdate(opts: { force?: boolean; dryRun?: boolean } = {}
}
console.log(heading(opts.dryRun ? `업데이트 계획 → v${version}` : `업데이트 → v${version}`));
const stale = manifest.installs.filter((i) => i.version !== version);
const stale = manifest.installs.filter((i) => isNewer(version, i.version));
// 이 CLI 보다 새 버전으로 깔린 설치 — npx 캐시·전역 설치의 구 CLI 가 새 스킬을 덮지 못하게 한다
const newer = manifest.installs.filter((i) => isNewer(i.version, version));
for (const rec of newer) {
console.log(
warn(
`${rec.target} (${rec.scope}): 설치본(v${rec.version})이 이 CLI(v${version})보다 새롭다` +
(opts.force ? " — --force 라서 다시 쓴다" : " — 건너뛴다. `npx designpaca@latest update` 로 갱신해 주세요"),
),
);
}
const targets = opts.force
? manifest.installs
: manifest.installs.filter((i) => !isNewer(i.version, version));
if (stale.length === 0) {
console.log(ok("설치된 스킬이 모두 최신 버전입니다"));
if (newer.length === 0) console.log(ok("설치된 스킬이 모두 최신 버전입니다"));
// 버전이 같아도 파일이 사라졌거나 수정됐을 수 있다. 조용히 넘기면 사용자가 모른다.
let broken = 0;
@ -43,7 +57,7 @@ export async function runUpdate(opts: { force?: boolean; dryRun?: boolean } = {}
}
let failed = 0;
for (const rec of manifest.installs) {
for (const rec of targets) {
console.log(info(`${rec.target} (${rec.scope}) ${dim(tildify(rec.root))} — ${rec.version} → ${version}`));
// 기록이 있던 바로 그 자리를 다시 계획한다. cwd 를 쓰면 project 설치가 지금 디렉터리에 깔린다.
let env;

View file

@ -16,11 +16,23 @@ interface Args {
command: string;
targets: TargetId[];
scope: Scope;
/** -s/--scope 를 직접 줬는가. 기본값 "user" 를 필터로 쓰면 project 설치를 놓친다 */
scopeExplicit: boolean;
yes: boolean;
force: boolean;
dryRun: boolean;
help: boolean;
version: boolean;
/** 해석하지 못한 입력. --help·--version 이 아니면 main 이 exit 2 로 끝낸다 */
errors: string[];
}
/** "a,b" 형태의 대상 목록을 정리한다 — 공백·빈 항목 제거 */
function splitList(v: string): TargetId[] {
return v
.split(",")
.map((s) => s.trim())
.filter(Boolean) as TargetId[];
}
function parse(argv: string[]): Args {
@ -28,11 +40,35 @@ function parse(argv: string[]): Args {
command: "",
targets: [],
scope: "user",
scopeExplicit: false,
yes: false,
force: false,
dryRun: false,
help: false,
version: false,
errors: [],
};
/** 값을 받는 옵션: 다음 토큰이 없거나 다른 옵션이면 값이 빠진 것이다 */
const takeValue = (flag: string, i: number): string | null => {
const v = argv[i + 1];
if (v === undefined || v === "" || v.startsWith("-")) {
out.errors.push(`${flag} 에는 값이 필요합니다`);
return null;
}
return v;
};
const addTargets = (flag: string, v: string) => {
const list = splitList(v);
if (list.length === 0) out.errors.push(`${flag} 에는 값이 필요합니다`);
out.targets.push(...list);
};
const setScope = (flag: string, v: string) => {
if (v === "") out.errors.push(`${flag} 에는 값이 필요합니다`);
else {
out.scope = v as Scope;
out.scopeExplicit = true;
}
};
for (let i = 0; i < argv.length; i++) {
@ -44,19 +80,31 @@ function parse(argv: string[]): Args {
else if (a === "--dry-run") out.dryRun = true;
else if (a === "--no-update-check") process.env["DESIGNPACA_NO_UPDATE_CHECK"] = "1";
else if (a === "--target" || a === "-t") {
const v = argv[++i];
if (v) out.targets.push(...(v.split(",") as TargetId[]));
const v = takeValue(a, i);
if (v !== null) {
addTargets(a, v);
i++;
}
} else if (a.startsWith("--target=")) {
out.targets.push(...(a.slice(9).split(",") as TargetId[]));
addTargets("--target", a.slice(9));
} else if (a === "--scope" || a === "-s") {
const v = argv[++i];
if (v) out.scope = v as Scope;
const v = takeValue(a, i);
if (v !== null) {
setScope(a, v);
i++;
}
} else if (a.startsWith("--scope=")) {
out.scope = a.slice(8) as Scope;
} else if (!a.startsWith("-") && !out.command) {
setScope("--scope", a.slice(8));
} else if (a.startsWith("-")) {
// 오타(--dryrun, --forse)가 조용히 버려져 실제 쓰기·삭제로 이어지는 일을 막는다
out.errors.push(`알 수 없는 옵션: ${a}`);
} else if (!out.command) {
out.command = a;
} else {
out.errors.push(`알 수 없는 인자: ${a}`);
}
}
out.targets = [...new Set(out.targets)];
return out;
}
@ -75,7 +123,7 @@ ${bold("사용법")}
${bold("옵션")}
-t, --target <id[,id]> 설치 대상: ${VALID_TARGETS.join(", ")}
-s, --scope <범위> user | project ${dim("(기본: user)")}
-s, --scope <범위> user | project ${dim("(기본: user)")} ${dim("uninstall 은 지정한 범위만 제거")}
-y, --yes 확인 없이 진행합니다
-f, --force 직접 수정한 파일도 덮어씁니다 ${dim("(.orig 로 백업)")}
--dry-run 쓰지 않고 계획만 보여줍니다 (install · update · uninstall)
@ -105,6 +153,12 @@ async function main(): Promise<number> {
return 0;
}
if (args.errors.length > 0) {
for (const e of args.errors) console.error(bad(e));
console.error(dim(" `designpaca --help` 로 사용법을 확인해 주세요"));
return 2;
}
const bad_ = args.targets.filter((t) => !VALID_TARGETS.includes(t));
if (bad_.length > 0) {
console.error(bad(`알 수 없는 대상: ${bad_.join(", ")}`));
@ -117,9 +171,15 @@ async function main(): Promise<number> {
}
// 대화형으로 쓸 수 있는 환경이면 인자 없이 실행했을 때 온보딩으로 보낸다
const interactive = process.stdout.isTTY && !args.yes;
// 출력만 TTY 이고 입력이 막힌 환경(에이전트 터미널, `< /dev/null`)에서는 프롬프트가 입력을 못 받는다
const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !args.yes;
const onboardOpts = {
dryRun: args.dryRun,
force: args.force,
...(args.scopeExplicit ? { scope: args.scope } : {}),
};
if (!args.command || args.command === "onboard") {
if (interactive) return onboard();
if (interactive) return onboard(onboardOpts);
console.log(usage(version));
return 0;
}
@ -128,7 +188,7 @@ async function main(): Promise<number> {
switch (args.command) {
case "install": {
const targets = args.targets.length > 0 ? args.targets : (["claude-code"] as TargetId[]);
if (interactive && args.targets.length === 0) return onboard();
if (interactive && args.targets.length === 0) return onboard(onboardOpts);
const outcomes = await runInstall({
targets,
scope: args.scope,
@ -136,7 +196,9 @@ async function main(): Promise<number> {
dryRun: args.dryRun,
});
printOutcomes(outcomes, args.dryRun);
if (!args.dryRun) printNextSteps(targets);
// 막힌 대상에는 "다음 단계"를 안내하지 않는다 — 실패 메시지와 모순된다
const installed = outcomes.filter((o) => !o.blocked).map((o) => o.target);
if (!args.dryRun && installed.length > 0) printNextSteps(installed);
code = outcomes.some((o) => o.blocked) ? 1 : 0;
break;
}
@ -145,7 +207,12 @@ async function main(): Promise<number> {
break;
case "uninstall":
case "remove":
code = await runUninstall({ targets: args.targets, force: args.force, dryRun: args.dryRun });
code = await runUninstall({
targets: args.targets,
...(args.scopeExplicit ? { scope: args.scope } : {}),
force: args.force,
dryRun: args.dryRun,
});
break;
case "doctor":
code = await runDoctor();

View file

@ -0,0 +1,38 @@
/**
* 의존성 없이 쓰는 최소 semver 비교.
* 숫자 세 칸을 먼저 비교하고, 같으면 프리릴리스가 붙은 쪽을 더 낮게 본다(1.0.0-rc.1 < 1.0.0).
*/
function parts(v: string): { nums: number[]; pre: string[] } {
const [core = "", pre = ""] = v.split("+")[0]!.split(/-(.*)/s);
const nums = core.split(".").map((n) => Number.parseInt(n, 10) || 0);
return { nums, pre: pre ? pre.split(".") : [] };
}
/** a 가 b 보다 크면 양수, 작으면 음수, 같으면 0 */
export function compareVersions(a: string, b: string): number {
const [x, y] = [parts(a), parts(b)];
for (let i = 0; i < 3; i++) {
const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
if (d !== 0) return d;
}
if (x.pre.length === 0 && y.pre.length === 0) return 0;
if (x.pre.length === 0) return 1;
if (y.pre.length === 0) return -1;
for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
const [p, q] = [x.pre[i], y.pre[i]];
if (p === undefined) return -1;
if (q === undefined) return 1;
if (p === q) continue;
const [pn, qn] = [/^\d+$/.test(p), /^\d+$/.test(q)];
if (pn && qn) return Number(p) - Number(q);
if (pn) return -1;
if (qn) return 1;
return p < q ? -1 : 1;
}
return 0;
}
/** latest 가 current 보다 새 버전인가 */
export function isNewer(latest: string, current: string): boolean {
return compareVersions(latest, current) > 0;
}

View file

@ -12,7 +12,7 @@ import {
} from "@designpaca/core";
import { getSkill } from "../skill.ts";
import { runInstall, printNextSteps, printOutcomes } from "../commands/install.ts";
import { accent, bold, dim } from "../ui.ts";
import { accent, bad, bold, dim, warn } from "../ui.ts";
/** 선택한 범위를 어댑터가 지원하지 않으면 지원 가능한 범위로 낮춘다 */
function effectiveScope(target: TargetId, wanted: Scope): Scope {
@ -20,7 +20,15 @@ function effectiveScope(target: TargetId, wanted: Scope): Scope {
return a.scopes.includes(wanted) ? wanted : (a.scopes[0] as Scope);
}
export async function onboard(): Promise<number> {
export interface OnboardOptions {
/** 쓰지 않고 계획만 보여 준다 — 터미널에서도 실제 설치로 빠지지 않는다 */
dryRun?: boolean;
force?: boolean;
/** 명령줄에서 직접 지정한 범위. 있으면 범위 질문을 건너뛴다 */
scope?: Scope;
}
export async function onboard(opts: OnboardOptions = {}): Promise<number> {
const skill = await getSkill();
console.clear();
@ -53,7 +61,9 @@ export async function onboard(): Promise<number> {
});
if (p.isCancel(targets)) return cancel();
const wanted = await p.select<Scope>({
const picked = opts.scope
? opts.scope
: await p.select<Scope>({
message: "어느 범위에 설치할까요?",
options: [
{
@ -69,7 +79,8 @@ export async function onboard(): Promise<number> {
],
initialValue: "user",
});
if (p.isCancel(wanted)) return cancel();
if (p.isCancel(picked)) return cancel();
const wanted: Scope = picked;
// 범위가 낮춰진 타깃이 있으면 미리 알린다 — 설치 후에 "왜 여기 깔렸지"가 되지 않게
const downgraded = targets.filter((t) => effectiveScope(t, wanted) !== wanted);
@ -112,6 +123,19 @@ export async function onboard(): Promise<number> {
"이렇게 설치됩니다",
);
if (opts.dryRun) {
// 계획만 보여 주고 끝낸다 — 확인 질문도, 도구 제안도 하지 않는다
const planned = [];
for (const t of targets) {
planned.push(
...(await runInstall({ targets: [t], scope: effectiveScope(t, wanted), force: opts.force, dryRun: true })),
);
}
printOutcomes(planned, true);
p.outro(dim("--dry-run: 아무것도 쓰지 않았습니다"));
return planned.some((o) => o.blocked) ? 1 : 0;
}
const go = await p.confirm({ message: "이대로 진행할까요?", initialValue: true });
if (p.isCancel(go) || !go) return cancel();
@ -122,7 +146,7 @@ export async function onboard(): Promise<number> {
for (const t of targets) {
const scope = effectiveScope(t, wanted);
s.message(`${getAdapter(t).label} 에 설치하고 있습니다`);
outcomes.push(...(await runInstall({ targets: [t], scope })));
outcomes.push(...(await runInstall({ targets: [t], scope, force: opts.force })));
}
s.stop("설치가 끝났습니다");
} catch (err) {
@ -133,10 +157,21 @@ export async function onboard(): Promise<number> {
printOutcomes(outcomes);
// 막힌 대상에는 "다음 단계"도 "준비됐습니다"도 말하지 않는다
const installed = outcomes.filter((o) => !o.blocked).map((o) => o.target);
if (installed.length === 0) {
p.outro(bad("설치하지 못했습니다 — 위 메시지를 확인해 주세요"));
return 1;
}
await offerTools();
printNextSteps(targets);
printNextSteps(installed);
if (installed.length < outcomes.length) {
p.outro(warn("일부 대상은 설치하지 못했습니다 — 위 메시지를 확인해 주세요"));
return 1;
}
p.outro(`${accent("designpaca")} 준비됐습니다 — 만들고 싶은 것을 말씀해 주세요`);
return 0;
}

View file

@ -16,7 +16,7 @@ export const info = (s: string) => `${pc.cyan("·")} ${s}`;
*/
export function displayWidth(s: string): number {
// ANSI 이스케이프는 폭을 차지하지 않는다
const plain = s.replace(/\[[0-9;]*m/g, "");
const plain = s.replace(/\x1b\[[0-9;]*m/g, "");
let w = 0;
for (const ch of plain) {
const cp = ch.codePointAt(0) ?? 0;
@ -40,7 +40,7 @@ export function padDisplay(s: string, width: number): string {
}
export function heading(s: string): string {
return `\n${bold(s)}\n${dim("─".repeat(Math.min(s.length + 8, 56)))}`;
return `\n${bold(s)}\n${dim("─".repeat(Math.min(displayWidth(s) + 8, 56)))}`;
}
/** 긴 경로 목록을 접어서 보여준다 — 설치 계획이 화면을 삼키지 않게 */
@ -50,6 +50,6 @@ export function fold(items: string[], max = 6): string[] {
}
export function table(rows: [string, string][]): string {
const w = Math.max(...rows.map(([k]) => k.length));
return rows.map(([k, v]) => ` ${k.padEnd(w)} ${dim(v)}`).join("\n");
const w = Math.max(...rows.map(([k]) => displayWidth(k)));
return rows.map(([k, v]) => ` ${padDisplay(k, w)} ${dim(v)}`).join("\n");
}

View file

@ -1,4 +1,5 @@
import { readIfExists, updateCachePath, writeAtomic } from "@designpaca/core";
import { isNewer } from "./semver.ts";
import { readOrNull, updateCachePath, writeAtomic } from "@designpaca/core";
const DAY = 24 * 60 * 60 * 1000;
/** 명령을 마친 뒤 종료를 붙잡는 최대 시간. 느린 네트워크에서 체감 지연을 줄이려고 짧게 둔다 */
@ -12,17 +13,6 @@ interface Cache {
latest: string;
}
function isNewer(latest: string, current: string): boolean {
const norm = (v: string) => v.split("-")[0]!.split(".").map((n) => Number.parseInt(n, 10) || 0);
const [a, b] = [norm(latest), norm(current)];
for (let i = 0; i < 3; i++) {
const l = a[i] ?? 0;
const c = b[i] ?? 0;
if (l !== c) return l > c;
}
return false;
}
/**
* 하루 한 번만 레지스트리를 본다. 네트워크가 없거나 느리면 조용히 포기한다 —
* 업데이트 확인 때문에 CLI 가 멈추는 일은 없어야 한다.
@ -34,7 +24,8 @@ export async function checkForUpdate(current: string): Promise<string | null> {
if (!process.stdout.isTTY) return null;
const cachePath = updateCachePath();
const raw = await readIfExists(cachePath);
// 캐시는 보조 정보다 — 권한·잠금 등 어떤 읽기 오류든 '캐시 없음'으로 보고 넘어간다
const raw = await readOrNull(cachePath);
if (raw) {
try {
const c = JSON.parse(raw) as Cache;

View file

@ -1,5 +1,5 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { execFileSync, spawnSync } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@ -33,6 +33,23 @@ function run(args: string[], cwd?: string): string {
});
}
/** 종료 코드·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);
});
@ -42,6 +59,10 @@ test("--version 은 스킬 버전과 같다", { skip: !built }, async () => {
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 }, () => {
@ -163,3 +184,162 @@ test("update 는 project 설치를 기록된 root 에서 갱신하고 cwd 에는
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<string> {
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 });
}
});

View file

@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { compareVersions, isNewer } from "../src/semver.ts";
import { displayWidth, fold, heading, padDisplay, table } from "../src/ui.ts";
test("isNewer 는 숫자 세 칸을 semver 로 비교한다", () => {
assert.equal(isNewer("0.14.0", "0.12.0"), true);
assert.equal(isNewer("0.12.0", "0.14.0"), false);
assert.equal(isNewer("0.14.0", "0.14.0"), false);
assert.equal(isNewer("0.10.0", "0.9.0"), true, "문자열 비교가 아니라 숫자 비교다");
assert.equal(isNewer("1.0.0", "0.99.99"), true);
});
test("프리릴리스는 같은 숫자의 정식 버전보다 낮다", () => {
assert.equal(isNewer("1.0.0", "1.0.0-rc.1"), true);
assert.equal(isNewer("1.0.0-rc.1", "1.0.0"), false);
assert.ok(compareVersions("1.0.0-rc.2", "1.0.0-rc.1") > 0);
assert.ok(compareVersions("1.0.0-rc.10", "1.0.0-rc.9") > 0);
assert.equal(compareVersions("1.0.0+build5", "1.0.0"), 0);
});
test("displayWidth 는 한글을 2칸으로 센다", () => {
assert.equal(displayWidth("abc"), 3);
assert.equal(displayWidth("위치"), 4);
assert.equal(displayWidth("CLI 버전"), 8);
assert.equal(displayWidth("\x1b[31mab\x1b[0m"), 2, "ANSI 이스케이프는 폭이 아니다");
});
test("padDisplay 와 table 은 한글이 섞여도 값 열이 같은 칸에서 시작한다", () => {
assert.equal(displayWidth(padDisplay("위치", 8)), 8);
const lines = table([
["위치", "a"],
["CLI 버전", "b"],
["Node", "c"],
]).split("\n");
const starts = lines.map((l) => displayWidth(l.slice(0, l.search(/[abc]$/))));
assert.equal(new Set(starts).size, 1, `값 열 시작 칸이 제각각이다: ${starts}`);
});
test("heading 밑줄은 표시 폭을 기준으로 한다", () => {
const rule = (heading("설치 기록").split("\n")[2] ?? "").replace(/\x1b\[[0-9;]*m/g, "");
assert.equal([...rule].length, displayWidth("설치 기록") + 8);
});
test("fold 는 max 를 넘는 항목을 접는다", () => {
assert.deepEqual(fold(["a", "b"], 3), ["a", "b"]);
assert.equal(fold(["a", "b", "c", "d"], 2).length, 3);
});

View file

@ -16,7 +16,23 @@ export async function exists(p: string): Promise<boolean> {
}
}
/**
* 파일이 없을 때만 null 을 돌려준다(ENOENT·ENOTDIR). 권한 없음·잠김·fd 고갈 같은 읽기 실패는
* 던진다 — "없음"으로 취급하면 읽지 못한 사용자 문서를 백업 없이 새 내용으로 교체하게 된다.
* 읽기 실패가 동작을 막으면 안 되는 호출부(캐시 등)는 readOrNull 을 쓴다.
*/
export async function readIfExists(p: string): Promise<string | null> {
try {
return await fs.readFile(p, "utf8");
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code === "ENOENT" || code === "ENOTDIR") return null;
throw err;
}
}
/** 어떤 이유로든 읽지 못하면 null — 없어도 되는 캐시 같은 파일용. 사용자 문서에는 쓰지 않는다 */
export async function readOrNull(p: string): Promise<string | null> {
try {
return await fs.readFile(p, "utf8");
} catch {

View file

@ -13,7 +13,7 @@ import {
UnsafePathError,
writeAtomic,
} from "./fsx.ts";
import { removeBlock, upsertBlock } from "./marker.ts";
import { extractBlock, removeBlock, upsertBlock } from "./marker.ts";
import { dropInstall, findInstall, inspectDrift, readManifest, upsertInstall } from "./manifest.ts";
import { ADAPTERS, getAdapter } from "./targets/index.ts";
import type {
@ -46,8 +46,6 @@ const EMPTY_SKILL: SkillSource = {
version: "0.0.0",
skillMd: "",
files: new Map(),
body: "",
description: "",
};
/** 시스템에 흔적이 있는 타깃을 골라준다 — TUI 의 기본 체크 상태로 쓴다 */
@ -143,6 +141,10 @@ export interface ApplyResult {
backedUp: string[];
/** 사용자가 고쳐서 건너뛴 파일 */
skipped: string[];
/** 새 버전에서 빠져 지운 이전 설치 파일(사용자 수정이 없던 것만) */
removedStale: string[];
/** 새 버전에서 빠졌지만 사용자가 고쳐 둔 탓에 남긴 파일. 기록에도 남는다 */
keptStale: string[];
}
/**
@ -202,10 +204,23 @@ export async function applyPlan(
// 1차: 무엇을 쓸지 전부 정한다. 마커가 꼬인 문서 등은 여기서 실패해 반쯤 쓰인 설치를 남기지 않는다.
type Step =
| { action: FileAction; skip: true }
| { action: FileAction; skip: false; next: string; backupFirst: boolean };
/** 디스크 내용이 이미 계획과 같다 — 쓰지도 백업하지도 않고 새 해시만 기록한다 */
| { action: FileAction; skip: false; same: true }
| { action: FileAction; skip: false; same: false; next: string; backupFirst: boolean };
const steps: Step[] = [];
for (const action of plan.actions) {
const isDirty = modified.has(keyOf(action.path));
// 읽기 실패(권한 등)는 여기서 던져 아무것도 쓰기 전에 멈춘다
const cur = await readIfExists(action.path);
if (isDirty && cur !== null) {
// 중단된 update 의 잔재이거나 우연히 새 버전과 같게 고친 파일 — 잃을 것이 없으니 드리프트가 아니다
const have = action.kind === "write" ? cur : extractBlock(cur, action.marker);
const want = action.kind === "write" ? action.content : action.content.trim();
if (have !== null && sha256(have) === sha256(want)) {
steps.push({ action, skip: false, same: true });
continue;
}
}
if (isDirty && !opts.force) {
steps.push({ action, skip: true });
continue;
@ -213,16 +228,15 @@ export async function applyPlan(
if (action.kind === "write") {
let backupFirst = isDirty;
if (!isDirty && !recorded.has(keyOf(action.path))) {
const cur = await readIfExists(action.path);
backupFirst = cur !== null && sha256(cur) !== sha256(action.content);
}
steps.push({ action, skip: false, next: action.content, backupFirst });
steps.push({ action, skip: false, same: false, next: action.content, backupFirst });
} else {
const cur = (await readIfExists(action.path)) ?? "";
steps.push({
action,
skip: false,
next: upsertBlock(cur, action.marker, action.content),
same: false,
next: upsertBlock(cur ?? "", action.marker, action.content),
backupFirst: isDirty,
});
}
@ -250,18 +264,45 @@ export async function applyPlan(
skipped.push(action.path);
continue;
}
if (!step.same) {
if (step.backupFirst) {
const b = await backup(action.path);
if (b) backedUp.push(b);
}
await writeAtomic(action.path, step.next);
}
if (action.kind === "write") {
files.push({ path: action.path, sha256: sha256(action.content) });
} else {
// 마커 방식은 블록 안쪽만 해시한다 — 문서의 다른 부분은 사용자 자유다
files.push({ path: action.path, sha256: sha256(action.content.trim()), marker: action.marker });
}
written.push(action.path);
if (!step.same) written.push(action.path);
}
// 새 계획에 없는 이전 설치 파일(스킬 문서가 삭제·개명된 경우)을 정리한다.
// 사용자가 고친 것은 지우지 않고 기록에 원래 해시로 남긴다 — uninstall 이 계속 추적하고 경고한다.
const removedStale: string[] = [];
const keptStale: string[] = [];
if (prev) {
const planned = new Set(plan.actions.map((a) => keyOf(a.path)));
const stale = prev.files.filter((f) => !planned.has(keyOf(f.path)));
if (stale.length > 0) {
const guard = await removalGuard(prev);
for (const f of stale) {
// 마커 주입 문서·경계 밖 경로는 건드리지 않고 기록만 유지한다
if (f.marker || (await guard(f))) {
files.push(f);
keptStale.push(f.path);
} else if (modified.has(keyOf(f.path))) {
files.push(f);
keptStale.push(f.path);
} else {
await removeFileAndPrune(f.path, plan.root);
removedStale.push(f.path);
}
}
}
}
const record: InstallRecord = {
@ -274,12 +315,14 @@ export async function applyPlan(
};
await upsertInstall(record, home);
return { record, written, backedUp, skipped };
return { record, written, backedUp, skipped, removedStale, keptStale };
}
export interface RemoveResult {
removed: string[];
keptModified: string[];
/** 같은 경로를 다른 타깃 기록도 소유해 지우지 않은 파일(agents·antigravity 의 project 범위). 기록만 드롭한다 */
sharedKept: string[];
/** 경계 검사에 걸려 손대지 않은 파일(기록 root 밖·링크·꼬인 마커). 기록에 남긴다 */
refused: string[];
}
@ -335,12 +378,24 @@ export async function removeInstall(
const removed: string[] = [];
const keptModified: string[] = [];
const refused: string[] = [];
const sharedKept: string[] = [];
// 다른 기록이 같은 파일을 소유하면(참조 카운트) 지우지 않는다 — 한쪽 제거가 다른 쪽 설치를 깨면 안 된다
const others = new Set<string>();
for (const rec of (await readManifest(opts.env?.home)).installs) {
if (rec.target === record.target && rec.scope === record.scope && samePath(rec.root, record.root)) continue;
for (const f of rec.files) if (!f.marker) others.add(keyOf(f.path));
}
for (const f of record.files) {
if (await guard(f)) {
refused.push(f.path);
continue;
}
if (!f.marker && others.has(keyOf(f.path))) {
sharedKept.push(f.path);
continue;
}
if (dirty.has(f.path) && !opts.force) {
keptModified.push(f.path);
continue;
@ -377,5 +432,5 @@ export async function removeInstall(
}
}
return { removed, keptModified, refused };
return { removed, keptModified, refused, sharedKept };
}

View file

@ -13,10 +13,31 @@ export async function readManifest(home?: string): Promise<Manifest> {
return parseManifest(raw) ?? structuredClone(EMPTY);
}
const isStr = (v: unknown): v is string => typeof v === "string";
/** 레코드 형태 검증 — 형태가 깨진 원소 하나가 findInstall·inspectDrift 에서 TypeError 로 설치 전체를 막지 않게 한다 */
function isInstallRecord(v: unknown): v is InstallRecord {
if (typeof v !== "object" || v === null) return false;
const r = v as Record<string, unknown>;
if (!isStr(r["target"]) || !isStr(r["scope"]) || !isStr(r["root"])) return false;
if (!Array.isArray(r["files"])) return false;
return r["files"].every((f) => {
if (typeof f !== "object" || f === null) return false;
const x = f as Record<string, unknown>;
return isStr(x["path"]) && isStr(x["sha256"]) && (x["marker"] === undefined || isStr(x["marker"]));
});
}
/**
* 파싱 실패와 형태 불일치는 모두 null — readManifest 가 빈 매니페스트로 강등하고,
* writeManifest 가 덮기 전에 원본을 .corrupt-* 로 보존한다. 원소를 골라 버리면 보존 경로가 꺼진다.
*/
function parseManifest(raw: string): Manifest | null {
try {
const parsed = JSON.parse(raw) as Manifest;
const parsed = JSON.parse(raw) as Manifest | null;
if (typeof parsed !== "object" || parsed === null) return null;
if (parsed.schema !== 1 || !Array.isArray(parsed.installs)) return null;
if (!parsed.installs.every(isInstallRecord)) return null;
return parsed;
} catch {
return null;

View file

@ -75,7 +75,11 @@ export function hasBlock(doc: string, marker: string): boolean {
/** 블록이 있으면 내용만 교체, 없으면 문서 끝에 덧붙인다. 마커가 꼬여 있으면 MarkerError */
export function upsertBlock(doc: string, marker: string, content: string): string {
const block = `${startTag(marker)}\n${content.trim()}\n${endTag(marker)}`;
// 문서가 전부 CRLF 면 블록도 CRLF 로 조립한다. LF 문서나 줄바꿈이 섞인 문서는 LF 로 둔다
const crlf = doc.includes("\r\n") && !/(^|[^\r])\n/.test(doc);
const nl = crlf ? "\r\n" : "\n";
const body = content.trim().replace(/\r?\n/g, nl);
const block = `${startTag(marker)}${nl}${body}${nl}${endTag(marker)}`;
const loc = locate(doc, marker);
if (loc.kind === "ambiguous") throw new MarkerError(loc.reason);
if (loc.kind === "one") {
@ -86,7 +90,7 @@ export function upsertBlock(doc: string, marker: string, content: string): strin
return doc.slice(0, from) + block + eol + tail;
}
const base = doc.trimEnd();
return base.length > 0 ? `${base}\n\n${block}\n` : `${block}\n`;
return base.length > 0 ? `${base}${nl}${nl}${block}${nl}` : `${block}${nl}`;
}
/**

View file

@ -43,7 +43,6 @@ async function walk(dir: string, base = dir): Promise<string[]> {
*/
export async function loadSkillSource(root: string, version: string): Promise<SkillSource> {
const skillMd = await fs.readFile(path.join(root, "SKILL.md"), "utf8");
const { fm, body } = splitFrontmatter(skillMd);
const files = new Map<string, string>();
for (const rel of await walk(root)) {
@ -54,11 +53,5 @@ export async function loadSkillSource(root: string, version: string): Promise<Sk
files.set(rel, await fs.readFile(path.join(root, rel), "utf8"));
}
return {
version,
skillMd,
files,
body: body.trim(),
description: fm["description"] ?? "웹 디자인 파이프라인 스킬",
};
return { version, skillMd, files };
}

View file

@ -17,6 +17,8 @@ import { anyExists, scopeRoot, skillDirActions } from "./common.ts";
* 전역 ~/.gemini/config/skills/<이름>/
*
* 전역 경로는 Antigravity Global Discovery 가 탐색하는 표준 위치(~/.gemini/config/skills)다.
* 공식 문서상 Antigravity CLI 는 전역 경로가 별도(~/.gemini/antigravity-cli/skills)라 이 타깃의 전역 설치를
* 읽지 못할 수 있다. 과거에 CLI 경로로 바꿨다가 되돌린 이력이 있어 경로 결정은 보류했다(감사 F049).
*
* 프론트매터 요구사항: `description` 필수, `name` 필수.
* 우리 SKILL.md 는 둘 다 갖고 있다.

View file

@ -22,25 +22,11 @@ export function skillDirActions(root: string, skill: SkillSource): FileAction[]
return actions;
}
/** references 를 별도 디렉터리로 내보내는 타깃(Cursor·AGENTS.md)용 */
export function referenceActions(root: string, skill: SkillSource): FileAction[] {
const actions: FileAction[] = [];
for (const [rel, content] of skill.files) {
actions.push({ kind: "write", path: path.join(root, ...rel.split("/")), content });
}
actions.push({
kind: "write",
path: path.join(root, ".designpaca_version"),
content: `${skill.version}\n`,
});
return actions;
}
/**
* 본문의 `references/...` 상대 경로를 실제 설치 위치로 바꾼다.
*
* Claude Code·Codex 는 스킬 디렉터리를 통째로 복사하므로 상대 경로가 그대로 맞다.
* Cursor·Windsurf·AGENTS.md 는 본문만 다른 자리로 옮기고 references 는 별도 디렉터리에 풀기
* AGENTS.md 어댑터는 본문만 다른 자리로 옮기고 references 는 별도 디렉터리에 풀기
* 때문에, 재작성하지 않으면 본문이 가리키는 경로가 전부 존재하지 않는 곳을 가리킨다.
*/
export function rewriteRefPaths(body: string, prefix: string): string {

View file

@ -104,8 +104,4 @@ export interface SkillSource {
skillMd: string;
/** references/ 이하 상대경로 → 내용 */
files: Map<string, string>;
/** 프론트매터를 제외한 본문 — 프론트매터를 쓰지 않는 포맷용 */
body: string;
/** 프론트매터에서 뽑은 description */
description: string;
}

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")));
});