Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): isolate approved snapshot mutations
Yuewei-LL1e8aebbfebd7
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 6b0cfa3a37..12a85b8775 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1473,6 +1473,12 @@ const config: ForgeConfig = {// the worker's cwd is the validated parent directory capability.target: 'preload',},+ {+ entry: 'src/main/cindy-brain/ghostSnapshotWorkerProcess.ts',+ config: 'vite.preload.config.ts',+ // Approval snapshot mutation is cwd-relative inside a stable-parent worker.+ target: 'preload',+ },{entry: 'src/preload/preload.ts',config: 'vite.preload.config.ts',diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 8cecbd46b0..21b8cfee4b 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -181,6 +181,8 @@ export interface GhostManagerOptions {/** Cindy 维护的发布者/审核公钥表;缺省为空,签名仍验完整性但不抬身份等级。 */trustRegistry?: GhostTrustRegistry;log?: GhostManagerLogger;+ /** Test-only stable snapshot mutation seam; production defaults to the worker. */+ mutateSnapshot?: ConstructorParameters<typeof GhostInstallReceiptStore>[1];}/** install / update 的失败分类 —— IPC 层据此映射错误码。 */@@ -518,7 +520,10 @@ export class GhostManager {}constructor(private readonly options: GhostManagerOptions) {- this.receiptStore = new GhostInstallReceiptStore(() => this.stateRootDir());+ this.receiptStore = new GhostInstallReceiptStore(+ () => this.stateRootDir(),+ this.options.mutateSnapshot,+ );const contentRoot = this.resolveContentRoot();const stateRoot = this.resolveStateRoot();this.assertDisjointRoots(contentRoot, stateRoot);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 43fd9f8ebb..36992a8e69 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -13,6 +13,7 @@ import {} from '../../../shared/ghost';import { CINDY_OFFICIAL_GHOST_TRUST, GhostManager, readLegacyGhostApprovalProjection } from '../GhostManager';import { hashApprovedSkillContent } from '../ghostInstallReceipt';+import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess';/** 每个用例独立的临时仓库根 + 源文件目录(规则 23:测试路径一律 os.tmpdir)。 */let workDir: string;@@ -46,6 +47,10 @@ beforeEach(async () => {trustedBundledIds.has(id) &&path.resolve(sourceDir) === path.resolve(workDir, 'bundled-seeds', id),recordBuiltinTombstone,+ mutateSnapshot: async (request) => {+ const { parentDir, ...workerRequest } = request;+ await runGhostSnapshotWorkerRequest(workerRequest, parentDir);+ },});});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex 4b16a0d2ec..6246964432 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -15,7 +15,9 @@ describe('GhostInstallReceiptStore cleanup', () => {workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-receipt-cleanup-'));stateRoot = path.join(workDir, 'state');await fs.promises.mkdir(stateRoot);- store = new GhostInstallReceiptStore(() => stateRoot);+ store = new GhostInstallReceiptStore(() => stateRoot, async ({ parentDir, targetName, operation }) => {+ if (operation === 'remove') await fs.promises.rm(path.join(parentDir, targetName), { recursive: true, force: true });+ });});afterEach(async () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.tsindex 4fc2ed2579..917c5fac51 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts@@ -12,6 +12,7 @@ describe('Node runtime packaging contract', () => {const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');expect(forge).toContain("entry: 'src/main/cindy-brain/nodeRuntimeWorkerProcess.ts'");expect(forge).toContain("entry: 'src/main/cindy-brain/forgeScaffoldWorkerProcess.ts'");+ expect(forge).toContain("entry: 'src/main/cindy-brain/ghostSnapshotWorkerProcess.ts'");expect(forge).toContain("target: 'preload'");expect(forge).toContain('[FuseV1Options.RunAsNode]: false');expect(forge).toContain('[FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false');diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 7f0c6e4d05..8af78bbdaa 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -23,6 +23,10 @@ import {} from './ghostContentTree.js';import { isPathInsideDir } from './dirDeposit.js';import { checkSkillMdConsistency } from './skillSlot.js';+import {+ mutateGhostSnapshotWithStableParent,+ type GhostSnapshotMutationRequest,+} from './ghostSnapshotCapability.js';// v2 pairs receipts with the unambiguous ghostContentTree framing. Keeping v1// readable would let an old ambiguous digest authorize a snapshot under the@@ -166,7 +170,12 @@ export type GhostPendingMutationListResult =/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */export class GhostInstallReceiptStore {- constructor(private readonly getRootDir: () => string) {}+ constructor(+ private readonly getRootDir: () => string,+ private readonly mutateSnapshot: (+ request: GhostSnapshotMutationRequest,+ ) => Promise<void> = mutateGhostSnapshotWithStableParent,+ ) {}rootDir(): string {return path.resolve(this.getRootDir());@@ -281,9 +290,17 @@ export class GhostInstallReceiptStore {// and transient IO failures remain observable so the caller keeps its journal.const snapshotPath = await this.assertManagedSnapshotParent(id, { createMissing: false });if (!snapshotPath) return;- await fs.promises.rm(snapshotPath, {- recursive: true,- force: true,+ const parentDir = path.join(this.rootDir(), 'skill-snapshots');+ const parentStats = await fs.promises.lstat(parentDir, { bigint: true });+ await this.mutateSnapshot({+ parentDir,+ expectedParent: {+ realPath: await fs.promises.realpath(parentDir),+ dev: parentStats.dev,+ ino: parentStats.ino,+ },+ operation: 'remove',+ targetName: id,});}@@ -300,7 +317,10 @@ export class GhostInstallReceiptStore {}const snapshotPath = this.assertManagedSnapshotParentSync(id, { createMissing: false });if (!snapshotPath) return;- fs.rmSync(snapshotPath, { recursive: true, force: true });+ // Startup recovery is synchronous, while the only safe recursive cleanup+ // capability is the cwd-bound utility worker. Removing the receipt is the+ // authorization boundary; retain the now-unreferenced snapshot for later+ // asynchronous cleanup rather than performing a pathname-based rmSync.}skillSnapshotRoot(id: string, revision: string): string {@@ -684,141 +704,24 @@ export class GhostInstallReceiptStore {): Promise<void> {const items = receipt.manifest.skill?.items ?? [];if (items.length === 0) return;- const target = this.skillSnapshotRoot(receipt.id, receipt.revision);- // 父段遏制必须先于**任何**对 target 的操作:lstat/rm/rename 都会穿透被换成- // junction 的父段,读写到状态根之外(见 assertManagedSnapshotParent 头注释)。- const parent = await this.assertManagedSnapshotParent(receipt.id, { createMissing: true });- if (!parent) throw new Error('skill snapshot parent unavailable');- let existing: fs.Stats | null;- try {- existing = await fs.promises.lstat(target);- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- existing = null;- }- if (existing) {- if (!existing.isDirectory()) {- throw new Error('approved skill snapshot target is not a directory');- }- // 快照已存在**不等于**它还是被批准的那份字节:状态根里的目录同样可被同权限- // 进程改写,而主 Agent 是顺着共享技能链接持续读它的。所以这里必须重算,- // 不能像上一版那样直接早退信任它。- if (await this.skillSnapshotMatchesReceipt(receipt, target)) return;- // 对不上的快照一律不可信:删掉,退回下面的重建路径 —— 重建本身仍要过安装- // 目录的字节校验,所以"损坏快照"能自愈,"安装字节已漂移"仍然拒。- await fs.promises.rm(target, { recursive: true, force: true });- }- if (!skillSourceDir) {- throw new Error('approved skill snapshot is missing');- }- const temp = path.join(- parent,- `.${receipt.revision}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,- );- try {- await fs.promises.mkdir(temp, { recursive: false });-- // 顺序是安全要点,不要改回"先校验源目录、再复制":源目录随时可被同权限进程- // 改写,校验和复制各读一次就有一个可换字节的窗口,复制出来的快照可能不是被- // 校验过的那一份。因此**先复制到 temp,再对 temp 里(即将成为快照的)那份字节- // 做全部权威校验**,校验通过才 rename 就位。- // 清单允许嵌套的 skill dir(如 skills/foo 与 skills/foo/bar —— 校验只拒重复,- // 不拒前缀嵌套)。祖先目录的整树复制已经带上了嵌套项的字节,再按嵌套项复制一次- // 会撞上 COPYFILE_EXCL 直接失败 —— 那会让一份合法清单在装入/更新/迁移/重新确认- // 四条路上全军覆没(§5 红线)。按深度排序、祖先先复制,已覆盖的嵌套项跳过复制;- // 指纹校验仍逐 item 进行(嵌套项的根就在祖先拷出的树里)。大小写折叠比较,- // 与清单查重同口径。- const copiedRoots: string[] = [];- const itemsByDepth = [...items].sort(- (a, b) => a.dir.split('/').length - b.dir.split('/').length,- );- for (const item of itemsByDepth) {- const dirFold = item.dir.toLowerCase();- if (copiedRoots.some((root) => dirFold === root || dirFold.startsWith(`${root}/`))) {- continue;- }- // 与算指纹同一个解析入口:逐段确认真目录,挡住"中间段被换成链接"这条从技能- // 目录之外取字节的路子。两侧必须共用,否则一侧穿透、一侧不穿透,复制的和- // 算指纹的就不是同一组字节。- const source = await resolveGhostContentPath(skillSourceDir, item.dir, {- expect: 'directory',- label: 'approved skill',- });- // 复制前的便宜预检:只为早失败、少做无用功(避免整份拷一个超大 SKILL.md)。- // **这不是安全边界** —— 它读的是可变源目录,结论随时可能过期,真正说话的是- // 下面对 temp 的校验。- const sourceSkillMdStat = await fs.promises- .lstat(path.join(source, 'SKILL.md'))- .catch(() => null);- if (- sourceSkillMdStat &&- (!sourceSkillMdStat.isFile() || sourceSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES)- ) {- throw new Error(- `approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,- );- }- await copyRegularDirectory(source, path.join(temp, ...item.dir.split('/')));- copiedRoots.push(dirFold);- }-- // 权威校验一律针对 temp:此刻这些字节已经脱离可变安装目录,复制期间被换过也- // 会在这里暴露。**尺寸上限必须排在算指纹之前** —— 源目录那道预检不是安全边界- // (预检后可被换成超大文件),若先算指纹就等于上限在权威路径上一次都没生效。- for (const item of items) {- const copiedSkillMdPath = path.join(temp, ...item.dir.split('/'), 'SKILL.md');- // 包一层领域错误:这一段现在排在算指纹之前,SKILL.md 缺失时若直接抛裸 ENOENT,- // 日志里就看不出是"技能内容被动过"这件事(只有被篡改时才可达,两种写法都- // fail closed,纯粹为可读性)。- const copiedSkillMdStat = await fs.promises.lstat(copiedSkillMdPath).catch((error) => {- throw new Error(- `approved skill ${item.dir}/SKILL.md is unreadable in the snapshot: ${- error instanceof Error ? error.message : String(error)- }`,- );- });- if (!copiedSkillMdStat.isFile() || copiedSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES) {- throw new Error(- `approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,- );- }- }- // 指纹判定走与"接受既有快照""发布后复核"同一个 helper:同一判据只有一份实现,- // 否则三处各写一遍、日后只改其中一处,就是这条链路前几轮反复出问题的形态。- if (!(await this.skillSnapshotMatchesReceipt(receipt, temp))) {- throw new Error(- `approved skill content for ${receipt.id} no longer matches the bytes approved at install time`,- );- }- for (const item of items) {- // 指纹相符已经蕴含 frontmatter 一致(批准时点那份过过这道校验),这里重跑一遍- // 是防止钉指纹那条路径本身有 bug,并给出更具体的错误。- const consistencyError = checkSkillMdConsistency(- await fs.promises.readFile(path.join(temp, ...item.dir.split('/'), 'SKILL.md'), 'utf8'),- item,- );- if (consistencyError) {- throw new Error(`approved skill ${item.dir} is inconsistent: ${consistencyError}`);- }- }-- await fs.promises.rename(temp, target);-- // rename 之前 temp 位于状态根内、同权限进程仍可改写它,所以就位之后再核一遍:- // 这一步把"校验通过 → rename"之间那段窗口收掉 —— 在那段里被换过的字节到这里- // 会暴露,并且不会留在盘上。- //- // 残留窗口(已知、未关):这次核对之后、主 Agent 顺着共享技能链接读取之前,快照- // 仍可被改写。要真正关掉需要给状态根写保护或在消费侧校验,都不在本函数范围内;- // 该缺口已正式登记在 docs/dev-rules/plugin-security-and-authoring.md 第 6 节- // (与"内容根字节可变"是两条并列的不同缺口)。- if (!(await this.skillSnapshotMatchesReceipt(receipt, target))) {- await fs.promises.rm(target, { recursive: true, force: true }).catch(() => undefined);- throw new Error('approved skill snapshot changed while being published');- }- } finally {- await fs.promises.rm(temp, { recursive: true, force: true }).catch(() => undefined);+ const snapshotsRoot = path.join(this.rootDir(), 'skill-snapshots');+ try { await fs.promises.mkdir(snapshotsRoot, { recursive: false }); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;}+ const rootStats = await fs.promises.lstat(snapshotsRoot, { bigint: true });+ if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error('skill snapshot root unavailable');+ await this.mutateSnapshot({+ parentDir: snapshotsRoot,+ expectedParent: {+ realPath: await fs.promises.realpath(snapshotsRoot),+ dev: rootStats.dev,+ ino: rootStats.ino,+ },+ operation: 'ensure',+ targetName: `${receipt.id}/${receipt.revision}`,+ receipt,+ ...(skillSourceDir ? { sourceDir: skillSourceDir } : {}),+ });}/**diff --git a/apps/desktop/src/main/cindy-brain/ghostSnapshotCapability.ts b/apps/desktop/src/main/cindy-brain/ghostSnapshotCapability.tsnew file mode 100644index 0000000000..683b37de76--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostSnapshotCapability.ts@@ -0,0 +1,52 @@+import { utilityProcess } from 'electron';+import path from 'node:path';++import type { GhostInstallReceipt } from './ghostInstallReceipt.js';+import type { GhostSnapshotParentIdentity } from './ghostSnapshotIdentity.js';+import type { GhostSnapshotWorkerRequest } from './ghostSnapshotWorkerProcess.js';++export interface GhostSnapshotMutationRequest {+ parentDir: string;+ expectedParent: GhostSnapshotParentIdentity;+ operation: 'ensure' | 'remove';+ targetName: string;+ sourceDir?: string;+ receipt?: GhostInstallReceipt;+}++export type GhostSnapshotTestMutation = (request: GhostSnapshotMutationRequest) => Promise<void>;++export function mutateGhostSnapshotWithStableParent(+ request: GhostSnapshotMutationRequest,+): Promise<void> {+ const child = utilityProcess.fork(path.join(__dirname, 'ghostSnapshotWorkerProcess.js'), [], {+ cwd: request.parentDir,+ stdio: ['ignore', 'ignore', 'pipe'],+ serviceName: 'cindy-ghost-snapshot',+ });+ return new Promise((resolve, reject) => {+ let settled = false;+ let ready = false;+ const finish = (error?: Error): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ child.kill();+ error ? reject(error) : resolve();+ };+ const timer = setTimeout(() => finish(new Error('ghost snapshot worker timed out')), 30_000);+ timer.unref?.();+ child.on('message', (message: unknown) => {+ if (!message || typeof message !== 'object') return;+ const value = message as { type?: unknown; ok?: unknown; message?: unknown };+ if (!ready && value.type === 'ready') {+ ready = true;+ const { parentDir: _parentDir, ...workerRequest } = request;+ child.postMessage({ type: 'mutate', request: workerRequest });+ } else if (value.ok === true) finish();+ else if (value.ok === false) finish(new Error(String(value.message ?? 'ghost snapshot worker failed')));+ });+ child.on('error', (error) => finish(new Error(String(error))));+ child.on('exit', (code) => { if (!settled) finish(new Error(`ghost snapshot worker exited (${code})`)); });+ });+}diff --git a/apps/desktop/src/main/cindy-brain/ghostSnapshotIdentity.ts b/apps/desktop/src/main/cindy-brain/ghostSnapshotIdentity.tsnew file mode 100644index 0000000000..5b4a42e031--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostSnapshotIdentity.ts@@ -0,0 +1,17 @@+import type fs from 'node:fs';++export interface GhostSnapshotParentIdentity {+ realPath: string;+ dev: bigint;+ ino: bigint;+}++export function sameGhostSnapshotParentIdentity(+ stats: fs.BigIntStats,+ expected: GhostSnapshotParentIdentity,+): boolean {+ return stats.isDirectory() && !stats.isSymbolicLink() &&+ stats.dev !== 0n && stats.ino !== 0n &&+ expected.dev !== 0n && expected.ino !== 0n &&+ stats.dev === expected.dev && stats.ino === expected.ino;+}diff --git a/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts b/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.tsnew file mode 100644index 0000000000..880a9a7ede--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts@@ -0,0 +1,170 @@+import fs from 'node:fs';+import path from 'node:path';++import { GHOST_SKILL_MD_MAX_BYTES } from '../../shared/ghost.js';+import {+ classifyGhostDirEntry,+ collectGhostContentFiles,+ hashGhostContentFiles,+ isRegularGhostDirEntry,+ resolveGhostContentPath,+} from './ghostContentTree.js';+import {+ sameGhostSnapshotParentIdentity,+ type GhostSnapshotParentIdentity,+} from './ghostSnapshotIdentity.js';+import { checkSkillMdConsistency } from './skillSlot.js';++export interface GhostSnapshotWorkerRequest {+ expectedParent: GhostSnapshotParentIdentity;+ operation: 'ensure' | 'remove';+ targetName: string;+ sourceDir?: string;+ receipt?: {+ manifest: import('../../shared/ghost.js').GhostManifest;+ skillContentSha256: Record<string, string>;+ };+}+interface Port {+ postMessage(message: unknown): void;+ on(event: 'message', listener: (event: { data: unknown }) => void): void;+}+const port = (process as unknown as { parentPort?: Port }).parentPort;+const send = (message: unknown): void => port?.postMessage(message);+const hasCode = (error: unknown, code: string): boolean =>+ Boolean(error && typeof error === 'object' && (error as NodeJS.ErrnoException).code === code);+function samePath(left: string, right: string): boolean {+ const normalize = (value: string) =>+ process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);+ return normalize(left) === normalize(right);+}+function targetParts(request: GhostSnapshotWorkerRequest): string[] {+ const parts = request.targetName.split('/');+ if (request.operation === 'ensure') {+ if (parts.length !== 2 || !/^[a-z0-9][a-z0-9-]{0,31}$/.test(parts[0]) ||+ !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(parts[1])) {+ throw new Error('invalid snapshot request');+ }+ } else if (parts.length !== 1 || !/^[a-z0-9][a-z0-9-]{0,31}$/.test(parts[0])) {+ throw new Error('invalid snapshot request');+ }+ return parts;+}+async function verifyParent(expected: GhostSnapshotParentIdentity, workingDir: string): Promise<void> {+ const stats = await fs.promises.lstat(workingDir, { bigint: true });+ if (!sameGhostSnapshotParentIdentity(stats, expected)) throw new Error('snapshot parent identity changed');+ if (!samePath(await fs.promises.realpath(workingDir), expected.realPath)) throw new Error('snapshot parent path changed');+}+async function copyDirectory(source: string, target: string): Promise<void> {+ if ((await classifyGhostDirEntry(source)) !== 'directory') throw new Error(`skill source is not a directory: ${source}`);+ await fs.promises.mkdir(target, { recursive: true });+ for (const entry of await fs.promises.readdir(source, { withFileTypes: true })) {+ const from = path.join(source, entry.name);+ const to = path.join(target, entry.name);+ const kind = await classifyGhostDirEntry(from);+ if (!isRegularGhostDirEntry(kind)) throw new Error(`skill snapshot rejects non-regular entry: ${from}`);+ if (kind === 'directory') await copyDirectory(from, to);+ else await fs.promises.copyFile(from, to, fs.constants.COPYFILE_EXCL);+ }+}+async function hashes(receipt: NonNullable<GhostSnapshotWorkerRequest['receipt']>, root: string): Promise<Record<string, string>> {+ const result: Record<string, string> = {};+ for (const item of receipt.manifest.skill?.items ?? []) {+ const itemRoot = await resolveGhostContentPath(root, item.dir, { expect: 'directory', label: 'approved skill' });+ const tree = await collectGhostContentFiles(itemRoot, { dotEntries: 'include', nonRegular: 'throw', label: `approved skill ${item.dir}` });+ result[item.dir] = await hashGhostContentFiles(itemRoot, tree.files, tree.rootIdentity);+ }+ return result;+}+async function matches(receipt: NonNullable<GhostSnapshotWorkerRequest['receipt']>, root: string): Promise<boolean> {+ const actual = await hashes(receipt, root).catch(() => null);+ return Boolean(actual && (receipt.manifest.skill?.items ?? []).every(+ (item) => actual[item.dir] === receipt.skillContentSha256[item.dir],+ ));+}+export async function runGhostSnapshotWorkerRequest(+ request: GhostSnapshotWorkerRequest,+ workingDir = process.cwd(),+): Promise<void> {+ if (!request || !request.expectedParent) {+ throw new Error('invalid snapshot request');+ }+ const parts = targetParts(request);+ const relativeWorkerPaths = path.resolve(workingDir) === path.resolve(process.cwd());+ const workPath = (name: string): string =>+ relativeWorkerPaths ? name : path.join(workingDir, name);+ const targetPath = workPath(path.join(...parts));+ await verifyParent(request.expectedParent, workingDir);+ if (request.operation === 'remove') {+ await verifyParent(request.expectedParent, workingDir);+ await fs.promises.rm(targetPath, { recursive: true, force: true });+ send({ ok: true }); return;+ }+ if (!request.receipt || !request.sourceDir) throw new Error('approved skill snapshot is missing');+ let exists = false;+ try {+ const stat = await fs.promises.lstat(targetPath);+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('snapshot target is not a real directory');+ exists = true;+ } catch (error) { if (!hasCode(error, 'ENOENT')) throw error; }+ if (exists && await matches(request.receipt, targetPath)) { send({ ok: true }); return; }+ try {+ const parentKind = await classifyGhostDirEntry(workPath(parts[0]));+ if (parentKind !== 'directory') throw new Error('snapshot parent identity changed');+ } catch (error) {+ if (!hasCode(error, 'ENOENT')) throw error;+ await fs.promises.mkdir(workPath(parts[0]), { recursive: false });+ }+ const temp = `.${parts[1]}-${process.pid}-${Date.now()}.tmp`;+ try {+ const tempPath = workPath(temp);+ await fs.promises.mkdir(tempPath);+ const copiedRoots: string[] = [];+ for (const item of [...(request.receipt.manifest.skill?.items ?? [])].sort(+ (left, right) => left.dir.split('/').length - right.dir.split('/').length,+ )) {+ const folded = item.dir.toLowerCase();+ if (copiedRoots.some((root) => folded === root || folded.startsWith(`${root}/`))) continue;+ const source = await resolveGhostContentPath(request.sourceDir, item.dir, { expect: 'directory', label: 'approved skill' });+ await copyDirectory(source, path.join(tempPath, ...item.dir.split('/')));+ copiedRoots.push(folded);+ }+ for (const item of request.receipt.manifest.skill?.items ?? []) {+ const skillMd = path.join(tempPath, ...item.dir.split('/'), 'SKILL.md');+ const stat = await fs.promises.lstat(skillMd);+ if (!stat.isFile()) throw new Error(`approved skill ${item.dir}/SKILL.md is not a regular file`);+ if (stat.size > GHOST_SKILL_MD_MAX_BYTES) {+ throw new Error(`approved skill ${item.dir}/SKILL.md exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`);+ }+ const error = checkSkillMdConsistency(await fs.promises.readFile(skillMd, 'utf8'), item);+ if (error) throw new Error(`approved skill ${item.dir} is inconsistent: ${error}`);+ }+ if (!await matches(request.receipt, tempPath)) throw new Error('approved skill content no longer matches receipt');+ await verifyParent(request.expectedParent, workingDir);+ if (exists) await fs.promises.rm(targetPath, { recursive: true, force: true });+ await verifyParent(request.expectedParent, workingDir);+ await fs.promises.rename(tempPath, targetPath);+ await verifyParent(request.expectedParent, workingDir);+ if (!await matches(request.receipt, targetPath)) {+ if (await verifyParent(request.expectedParent, workingDir).then(() => true, () => false)) {+ await fs.promises.rm(targetPath, { recursive: true, force: true }).catch(() => undefined);+ }+ throw new Error('approved skill snapshot changed while being published');+ }+ send({ ok: true });+ } finally {+ if (await verifyParent(request.expectedParent, workingDir).then(() => true, () => false)) {+ await fs.promises.rm(workPath(temp), { recursive: true, force: true }).catch(() => undefined);+ }+ }+}+if (port) {+ let handled = false;+ send({ type: 'ready' });+ port.on('message', (event) => {+ const message = event.data as { type?: unknown; request?: GhostSnapshotWorkerRequest };+ if (handled || message?.type !== 'mutate' || !message.request) return;+ handled = true;+ runGhostSnapshotWorkerRequest(message.request).catch((error) => send({ ok: false, message: error instanceof Error ? error.message : String(error) }));+ });+}diff --git a/apps/desktop/src/test/vitest/electron-stub.ts b/apps/desktop/src/test/vitest/electron-stub.tsindex e755ecfc46..93b2dbc88a 100644--- a/apps/desktop/src/test/vitest/electron-stub.ts+++ b/apps/desktop/src/test/vitest/electron-stub.ts@@ -1,6 +1,7 @@import { EventEmitter } from 'node:events';import * as os from 'node:os';import * as path from 'node:path';+import { runGhostSnapshotWorkerRequest } from '../../main/cindy-brain/ghostSnapshotWorkerProcess';const noop = () => undefined;const asyncNoop = async () => undefined;@@ -257,12 +258,25 @@ export class Notification extends EventEmitter {}export const utilityProcess = {- fork: () =>- createEmitter({+ fork: (_entry?: string, _args?: string[], options?: { cwd?: string }) => {+ const emitter = createEmitter({pid: 0,- postMessage: noop,+ postMessage: (message: unknown) => {+ const value = message as { type?: string; request?: unknown };+ if (value.type !== 'mutate' || !value.request || !options?.cwd) return;+ void runGhostSnapshotWorkerRequest(value.request as never, options.cwd).then(+ () => emitter.emit('message', { ok: true }),+ (error) => emitter.emit('message', {+ ok: false,+ message: error instanceof Error ? error.message : String(error),+ }),+ );+ },kill: () => true,- }),+ });+ queueMicrotask(() => emitter.emit('message', { type: 'ready' }));+ return emitter;+ },};export const contextBridge = {