designpaca/packages/core/src/manifest.ts
Yun Chan 9bcb45cbd3 feat(core,cli): harden install engine and extend skill lint and interview eval
- update only touches the recorded project root; project installs do not
  follow symlinks or junctions; repeated --force rotates .orig backups;
  uninstall never deletes outside the recorded root
- run npm/npx without a shell on Windows and pin optional tool versions
- skip the update check in CI and non-interactive output
- lint: cross-document section pointers, preflight row ids, gate rule
  numbers, per-document size budgets, gate copy equality
- eval: scenarios S19-S21, route and read-cost rejudging, interpretation
  card judging, temp-dir previews and table-form cards no longer fail
2026-10-06 16:55:38 +09:00

116 lines
4.1 KiB
TypeScript

import fs from "node:fs/promises";
import { manifestPath } from "./paths.ts";
import { readIfExists, samePath, sha256, writeAtomic } from "./fsx.ts";
import { extractBlock } from "./marker.ts";
import type { DriftReport, InstallRecord, Manifest, Scope, TargetId } from "./types.ts";
const EMPTY: Manifest = { schema: 1, installs: [] };
export async function readManifest(home?: string): Promise<Manifest> {
const raw = await readIfExists(manifestPath(home));
if (!raw) return structuredClone(EMPTY);
// 손상된 매니페스트로 설치 전체가 막히지 않도록 빈 것으로 되돌린다(원본은 writeManifest 가 보존한다)
return parseManifest(raw) ?? structuredClone(EMPTY);
}
function parseManifest(raw: string): Manifest | null {
try {
const parsed = JSON.parse(raw) as Manifest;
if (parsed.schema !== 1 || !Array.isArray(parsed.installs)) return null;
return parsed;
} catch {
return null;
}
}
export async function writeManifest(m: Manifest, home?: string): Promise<void> {
const file = manifestPath(home);
// 손상된 매니페스트를 빈 것으로 읽은 뒤 그대로 덮으면 다른 설치 기록이 영구 소실된다.
// 덮기 전에 원본을 manifest.json.corrupt-<시각> 으로 옮겨 복구 여지를 남긴다.
const prev = await readIfExists(file);
if (prev !== null && prev.trim().length > 0 && parseManifest(prev) === null) {
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
await fs.rename(file, `${file}.corrupt-${stamp}`).catch(() => undefined);
}
await writeAtomic(file, JSON.stringify(m, null, 2) + "\n");
}
function sameInstall(a: InstallRecord, target: TargetId, scope: Scope, root: string): boolean {
return a.target === target && a.scope === scope && samePath(a.root, root);
}
export function findInstall(
m: Manifest,
target: TargetId,
scope: Scope,
root: string,
): InstallRecord | undefined {
return m.installs.find((i) => sameInstall(i, target, scope, root));
}
export async function upsertInstall(record: InstallRecord, home?: string): Promise<void> {
const m = await readManifest(home);
const idx = m.installs.findIndex((i) => sameInstall(i, record.target, record.scope, record.root));
if (idx >= 0) m.installs[idx] = record;
else m.installs.push(record);
await writeManifest(m, home);
}
export async function dropInstall(
target: TargetId,
scope: Scope,
root: string,
home?: string,
): Promise<void> {
const m = await readManifest(home);
m.installs = m.installs.filter((i) => !sameInstall(i, target, scope, root));
await writeManifest(m, home);
}
/**
* 설치 당시 해시와 현재 내용을 비교한다.
* 마커 방식 파일은 문서 전체가 아니라 블록 안쪽만 비교한다 — 사용자가 문서의 다른 부분을
* 고치는 것은 정상이고, 그걸 드리프트로 잡으면 update 가 영영 못 돈다.
*/
export async function inspectDrift(record: InstallRecord): Promise<DriftReport> {
const files: DriftReport["files"] = [];
for (const f of record.files) {
const cur = await readIfExists(f.path);
if (cur === null) {
files.push({ path: f.path, status: "missing" });
continue;
}
const target = f.marker ? (extractBlock(cur, f.marker) ?? "") : cur;
files.push({ path: f.path, status: sha256(target) === f.sha256 ? "ok" : "modified" });
}
return {
record,
files,
modified: files.filter((f) => f.status === "modified").map((f) => f.path),
};
}
/** 매니페스트가 가리키는 경로가 실제로 살아있는지 확인한다 */
export async function pruneDeadInstalls(home?: string): Promise<number> {
const m = await readManifest(home);
const before = m.installs.length;
const alive: InstallRecord[] = [];
for (const rec of m.installs) {
const anyAlive = await Promise.all(
rec.files.map(async (f) => {
try {
await fs.access(f.path);
return true;
} catch {
return false;
}
}),
);
if (anyAlive.some(Boolean)) alive.push(rec);
}
if (alive.length !== before) {
m.installs = alive;
await writeManifest(m, home);
}
return before - alive.length;
}