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

@ -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.backupFirst) {
const b = await backup(action.path);
if (b) backedUp.push(b);
if (!step.same) {
if (step.backupFirst) {
const b = await backup(action.path);
if (b) backedUp.push(b);
}
await writeAtomic(action.path, step.next);
}
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;
}