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

@ -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,23 +61,26 @@ export async function onboard(): Promise<number> {
});
if (p.isCancel(targets)) return cancel();
const wanted = await p.select<Scope>({
message: "어느 범위에 설치할까요?",
options: [
{
value: "user",
label: "전역 (권장)",
hint: "홈 디렉터리에 두어 모든 프로젝트에서 쓸 수 있습니다",
},
{
value: "project",
label: "이 프로젝트만",
hint: `${tildify(process.cwd())} · 팀과 함께 쓰려면 이쪽이 좋습니다`,
},
],
initialValue: "user",
});
if (p.isCancel(wanted)) return cancel();
const picked = opts.scope
? opts.scope
: await p.select<Scope>({
message: "어느 범위에 설치할까요?",
options: [
{
value: "user",
label: "전역 (권장)",
hint: "홈 디렉터리에 두어 모든 프로젝트에서 쓸 수 있습니다",
},
{
value: "project",
label: "이 프로젝트만",
hint: `${tildify(process.cwd())} · 팀과 함께 쓰려면 이쪽이 좋습니다`,
},
],
initialValue: "user",
});
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;