Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 收敛插件批准 journal 闸并修复账号边界撤链等 6 项复审缺陷
Yuewei-LLb3570b18847b
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex 9097e9c388..41302f633e 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1363,6 +1363,13 @@ const config: ForgeConfig = {// 承载。独立 CJS entry 与 main bundle 同目录,dev / packaged 同路径。target: 'preload',},+ {+ entry: 'src/main/cindy-brain/forgeScaffoldWorkerProcess.ts',+ config: 'vite.preload.config.ts',+ // Stable-parent scaffold publish/cleanup runs in a utility process;+ // the worker's cwd is the validated parent directory capability.+ target: 'preload',+ },{entry: 'src/preload/preload.ts',config: 'vite.preload.config.ts',diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex 77822c90b5..856c70d6cd 100644--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@ -1,13 +1,16 @@import fs from 'node:fs/promises';+import fsSync from 'node:fs';import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { dataOwnerStorageKey } from '../appSessionState.js';import {+ acknowledgeRecoveredLegacyGhosts,claimLegacyOwnerNamespace,getLegacyGhostRecoveryStatus,hasLegacyOwnerNamespaceClaim,+ listLegacyOwnerProjectionRoots,listLegacyGhostTombstoneRoots,recoverLegacyGhostPlugins,__testing,@@ -119,6 +122,16 @@ describe('claimLegacyOwnerNamespace', () => {// 文件留在原地、marker 未创建:被动实例保持只读,不打断共享同一 userData 的旧版本实例。await expect(fs.readFile(path.join(root, 'slack-hook.json'), 'utf-8')).resolves.toBe('legacy-hook');await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();+ await expect(+ fs.access(+ path.join(+ root,+ 'owners',+ dataOwnerStorageKey('cloud-a'),+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ ),+ ),+ ).rejects.toThrow();expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(false);});@@ -446,9 +459,336 @@ describe('claimLegacyOwnerNamespace', () => {expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(true);expect(hasLegacyOwnerNamespaceClaim('cloud-b', root)).toBe(false);});+ it('keeps the claim marker valid if the completion rename fails', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const markerPath = path.join(root, __testing.CLAIM_MARKER);+ await fs.writeFile(path.join(root, 'ghost-workdir-prefs.json'), 'legacy-prefs');+ let failCompletionRename = true;++ await expect(+ claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root, {}, {+ rename: async (source: string, target: string) => {+ if (target === markerPath && failCompletionRename) {+ failCompletionRename = false;+ throw Object.assign(new Error('simulated completion failure'), { code: 'EIO' });+ }+ return fs.rename(source, target);+ },+ }),+ ),+ ).rejects.toThrow('simulated completion failure');+ await expect(fs.readFile(markerPath, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ version: 1,+ ownerKey: dataOwnerStorageKey(ownerId),+ complete: false,+ });+ });++ it('does not move a symlinked legacy credential into the owner namespace', async () => {+ const root = await tempRoot();+ const external = await tempRoot();+ const source = path.join(root, 'model-access-credentials.json');+ await fs.writeFile(path.join(external, 'credentials.json'), '{"secret":"external"}');+ await fs.symlink(+ path.join(external, 'credentials.json'),+ source,+ process.platform === 'win32' ? 'file' : undefined,+ );++ const result = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ );+ const target = path.join(+ root,+ 'owners',+ dataOwnerStorageKey('cloud-a'),+ 'model-access-credentials.json',+ );++ expect(result).toMatchObject({ status: 'migrated', moved: 0, conflicts: 1 });+ expect((await fs.lstat(source)).isSymbolicLink()).toBe(true);+ await expect(fs.access(target)).rejects.toThrow();+ });++ it('does not write legacy data through a linked owner target root', async () => {+ const root = await tempRoot();+ const external = await tempRoot();+ const ownerKey = dataOwnerStorageKey('cloud-a');+ await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');+ await fs.mkdir(path.join(root, 'owners'), { recursive: true });+ await fs.symlink(+ external,+ path.join(root, 'owners', ownerKey),+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ const result = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ );++ expect(result).toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });+ await expect(fs.readFile(path.join(root, 'slack-hook.json'), 'utf8')).resolves.toBe('legacy-hook');+ await expect(fs.access(path.join(external, 'slack-hook.json'))).rejects.toThrow();+ });+});++it('fails closed when owner projection roots cannot be enumerated', () => {+ const readdir = vi.spyOn(fsSync, 'readdirSync').mockImplementationOnce(() => {+ throw Object.assign(new Error('denied'), { code: 'EACCES' });+ });+ try {+ expect(() => listLegacyOwnerProjectionRoots('C:\\cindy-user-data')).toThrow('denied');+ } finally {+ readdir.mockRestore();+ }});describe('legacy Ghost plugin recovery', () => {+ it('persists a durable backfill queue before moving a legacy plugin', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const source = path.join(root, 'brain', 'legacy-plugin');+ const target = path.join(root, 'owners', ownerKey, 'cindy-brain', 'legacy-plugin');+ const markerPath = path.join(+ root,+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ );+ await writeGhostDirAtPath(source, 'legacy-plugin');+ let interrupted = false;+ let markerPendingAtRename: string[] | null = null;++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root, {}, {+ rename: async (from: string, to: string) => {+ if (from === source && to === target) {+ markerPendingAtRename = (+ JSON.parse(await fs.readFile(markerPath, 'utf-8')) as {+ pendingIds: string[];+ }+ ).pendingIds;+ }+ await fs.rename(from, to);+ if (from === source && to === target && !interrupted) {+ interrupted = true;+ throw Object.assign(new Error('simulated process interruption'), { code: 'EIO' });+ }+ },+ }),+ );++ expect(result).toMatchObject({+ status: 'partial',+ moved: 0,+ });+ expect(markerPendingAtRename).toEqual(['legacy-plugin']);+ await expect(fs.access(source)).rejects.toThrow();+ await expect(fs.readFile(path.join(target, 'ghost.json'), 'utf-8')).resolves.toContain(+ '"id":"legacy-plugin"',+ );+ const marker = JSON.parse(+ await fs.readFile(+ markerPath,+ 'utf-8',+ ),+ ) as { ownerKey: string; pendingIds: string[] };+ expect(marker).toEqual({+ version: 1,+ ownerKey,+ pendingIds: ['legacy-plugin'],+ });+ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: true,+ });++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({+ status: 'partial',+ moved: 0,+ recoveredIds: ['legacy-plugin'],+ });+ });++ it('does not backfill a target that appeared while the legacy source still exists', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const source = path.join(root, 'brain', 'legacy-plugin');+ const target = path.join(root, 'owners', ownerKey, 'cindy-brain', 'legacy-plugin');+ await writeGhostDirAtPath(source, 'legacy-plugin');++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root, {}, {+ rename: async (from: string, to: string) => {+ if (from === source && to === target) {+ await writeGhostDirAtPath(target, 'legacy-plugin');+ throw Object.assign(new Error('target appeared before rename'), { code: 'EEXIST' });+ }+ await fs.rename(from, to);+ },+ }),+ );++ expect(result).toMatchObject({ status: 'partial', moved: 0 });+ expect(result.recoveredIds).toBeUndefined();+ await expect(fs.access(source)).resolves.toBeUndefined();+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0 });+ });++ it('does not let a stale pending id expand the frozen recovery whitelist', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(+ root,+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ );+ await fs.mkdir(path.dirname(markerPath), { recursive: true });+ await fs.writeFile(+ markerPath,+ JSON.stringify({ version: 1, ownerKey, pendingIds: ['stale-plugin'] }),+ );+ await writeGhostDirAtPath(path.join(root, 'brain', 'new-plugin'), 'new-plugin');++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0 });+ await expect(+ fs.access(path.join(root, 'brain', 'new-plugin')),+ ).resolves.toBeUndefined();+ await expect(+ fs.readFile(markerPath, 'utf8').then(JSON.parse),+ ).resolves.toEqual({+ version: 1,+ ownerKey,+ pendingIds: ['stale-plugin'],+ });+ });++ it('continues a mixed recovery marker when one id is already in the target', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(+ root,+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ );+ await fs.mkdir(path.dirname(markerPath), { recursive: true });+ await fs.writeFile(+ markerPath,+ JSON.stringify({ version: 1, ownerKey, pendingIds: ['already-moved', 'still-legacy'] }),+ );+ await writeGhostDirAtPath(+ path.join(root, 'owners', ownerKey, 'cindy-brain', 'already-moved'),+ 'already-moved',+ );+ await writeGhostDirAtPath(path.join(root, 'brain', 'still-legacy'), 'still-legacy');++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({+ status: 'migrated',+ moved: 1,+ recoveredIds: ['already-moved', 'still-legacy'],+ });+ await expect(+ fs.access(path.join(root, 'owners', ownerKey, 'cindy-brain', 'still-legacy')),+ ).resolves.toBeUndefined();+ });++ it('does not pick one of duplicate legacy sources for the same id', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDirAtPath(path.join(root, 'brain', 'duplicate-plugin'), 'duplicate-plugin');+ await writeGhostDirAtPath(+ path.join(root, 'owners', ownerKey, 'brain', 'duplicate-plugin'),+ 'duplicate-plugin',+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0, conflicts: 2 });+ await expect(fs.access(path.join(root, 'brain', 'duplicate-plugin'))).resolves.toBeUndefined();+ await expect(+ fs.access(path.join(root, 'owners', ownerKey, 'brain', 'duplicate-plugin')),+ ).resolves.toBeUndefined();+ await expect(+ fs.access(path.join(root, 'owners', ownerKey, 'cindy-brain', 'duplicate-plugin')),+ ).rejects.toThrow();+ });++ it('acknowledges only completed durable backfill ids', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(+ root,+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ );+ await fs.mkdir(path.dirname(markerPath), { recursive: true });+ await fs.writeFile(+ markerPath,+ JSON.stringify({+ version: 1,+ ownerKey,+ pendingIds: ['completed-plugin', 'retry-plugin'],+ }),+ );++ await acknowledgeRecoveredLegacyGhosts(+ ownerId,+ ['completed-plugin'],+ realFsDeps(root),+ );++ await expect(fs.readFile(markerPath, 'utf-8').then(JSON.parse)).resolves.toEqual({+ version: 1,+ ownerKey,+ pendingIds: ['retry-plugin'],+ });+ });+it('does not follow a linked legacy repository root', async () => {const root = await tempRoot();const externalRoot = await tempRoot();@@ -467,7 +807,7 @@ describe('legacy Ghost plugin recovery', () => {{ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },realFsDeps(root),),- ).resolves.toEqual({ status: 'skipped', moved: 0, conflicts: 0 });+ ).resolves.toEqual({ status: 'partial', moved: 0, conflicts: 1 });await expect(fs.readFile(path.join(externalRoot, 'external-plugin', 'ghost.json'), 'utf-8'),).resolves.toContain('"id":"external-plugin"');@@ -501,7 +841,7 @@ describe('legacy Ghost plugin recovery', () => {{ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },realFsDeps(root),),- ).resolves.toEqual({ status: 'skipped', moved: 0, conflicts: 0 });+ ).resolves.toEqual({ status: 'partial', moved: 0, conflicts: 1 });await expect(fs.readFile(path.join(linkedPlugin, 'ghost.json'), 'utf-8'),).resolves.toContain('"id":"linked-plugin"');@@ -926,7 +1266,8 @@ describe('legacy Ghost plugin recovery', () => {{},{rename: (source: string, target: string) =>- path.basename(source) === '.builtin-provisioning.json'+ path.basename(source) === '.builtin-provisioning.json' ||+ path.basename(target) === __testing.LEGACY_GHOST_RECOVERY_MARKER? fs.rename(source, target): Promise.reject(Object.assign(new Error('rename denied'), { code: 'EACCES' })),},@@ -969,7 +1310,7 @@ describe('legacy Ghost plugin recovery', () => {);const targetRoot = path.join(root, 'owners', dataOwnerStorageKey(ownerId));- expect(result).toMatchObject({ status: 'migrated', moved: 1, conflicts: 0 });+ expect(result).toMatchObject({ status: 'partial', moved: 1, conflicts: 1 });await expect(fs.readFile(path.join(targetRoot, 'cindy-brain', 'valid-plugin', 'ghost.json'), 'utf-8'),).resolves.toContain('"id":"valid-plugin"');@@ -993,8 +1334,10 @@ describe('legacy Ghost plugin recovery', () => {root,{},{- rename: () =>- Promise.reject(Object.assign(new Error('rename denied'), { code: 'EACCES' })),+ rename: (source: string, target: string) =>+ path.basename(target) === __testing.LEGACY_GHOST_RECOVERY_MARKER+ ? fs.rename(source, target)+ : Promise.reject(Object.assign(new Error('rename denied'), { code: 'EACCES' })),},);@@ -1057,13 +1400,137 @@ describe('legacy Ghost plugin recovery', () => {realFsDeps(root),);- expect(result).toEqual({ status: 'skipped', moved: 0, conflicts: 0 });+ expect(result).toEqual({ status: 'partial', moved: 0, conflicts: 1 });await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();await expect(fs.readFile(path.join(root, 'dialogues', 'session.json'), 'utf-8')).resolves.toBe('legacy-dialogue',);});+ it('defers the whole recovery when a legacy root cannot be enumerated', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDir(root, 'cindy-brain', 'ready-plugin');+ await writeGhostDir(root, 'brain', 'unreadable-plugin');+ const blockedRoot = path.join(root, 'brain');+ const originalReaddir = fsSync.readdirSync.bind(fsSync);+ const readdirSpy = vi.spyOn(fsSync, 'readdirSync').mockImplementation((dir, options) => {+ if (path.resolve(String(dir)) === path.resolve(blockedRoot)) {+ throw Object.assign(new Error('scan denied'), { code: 'EACCES' });+ }+ return originalReaddir(dir as never, options as never) as never;+ });+ try {+ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'deferred',+ legacyPluginCount: 2,+ canRetry: true,+ deferredReason: 'legacy-discovery-incomplete',+ });+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toEqual({+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'legacy-discovery-incomplete',+ });+ } finally {+ readdirSpy.mockRestore();+ }+ await expect(+ fs.readFile(path.join(root, 'cindy-brain', 'ready-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"ready-plugin"');+ await expect(+ fs.access(path.join(root, 'owners', dataOwnerStorageKey(ownerId), 'cindy-brain')),+ ).rejects.toThrow();+ });++ it('defers recovery when a legacy manifest is temporarily unreadable', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDir(root, 'cindy-brain', 'unreadable-manifest');+ const manifestPath = path.join(root, 'cindy-brain', 'unreadable-manifest', 'ghost.json');+ const originalReadFile = fsSync.readFileSync.bind(fsSync);+ const readFileSpy = vi.spyOn(fsSync, 'readFileSync').mockImplementation((file, options) => {+ if (path.resolve(String(file)) === path.resolve(manifestPath)) {+ throw Object.assign(new Error('manifest locked'), { code: 'EACCES' });+ }+ return originalReadFile(file as never, options as never) as never;+ });+ try {+ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toMatchObject({+ state: 'deferred',+ legacyPluginCount: 1,+ canRetry: true,+ deferredReason: 'legacy-discovery-incomplete',+ });+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({+ status: 'deferred',+ moved: 0,+ deferredReason: 'legacy-discovery-incomplete',+ });+ } finally {+ readFileSpy.mockRestore();+ }+ await expect(fs.access(manifestPath)).resolves.toBeUndefined();+ await expect(+ fs.access(path.join(root, 'owners', dataOwnerStorageKey(ownerId), 'cindy-brain')),+ ).rejects.toThrow();+ });++ it('defers and keeps the queue when the recovery marker is temporarily unreadable', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(+ root,+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ );+ await fs.mkdir(path.dirname(markerPath), { recursive: true });+ await fs.writeFile(+ markerPath,+ JSON.stringify({ version: 1, ownerKey, pendingIds: ['queued-plugin'] }),+ );+ await writeGhostDir(root, 'brain', 'queued-plugin');+ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root, {}, {+ readFile: (file: string) =>+ path.resolve(file) === path.resolve(markerPath)+ ? Promise.reject(Object.assign(new Error('marker locked'), { code: 'EACCES' }))+ : fs.readFile(file, 'utf8'),+ }),+ );+ expect(result).toEqual({+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'legacy-discovery-incomplete',+ });+ await expect(fs.access(path.join(root, 'brain', 'queued-plugin'))).resolves.toBeUndefined();+ });+it('consolidates plugins left in the current owner scoped brain directory', async () => {const root = await tempRoot();const ownerId = 'cloud-a';@@ -1290,6 +1757,49 @@ describe('legacy Ghost plugin recovery', () => {expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(false);});+ it('keeps a pending but invalid moved target visible for recovery', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(root, 'owners', ownerKey, __testing.LEGACY_GHOST_RECOVERY_MARKER);+ const targetDir = path.join(root, 'owners', ownerKey, 'cindy-brain', 'broken-plugin');+ await fs.mkdir(targetDir, { recursive: true });+ await fs.writeFile(path.join(targetDir, 'ghost.json'), '{ broken');+ await fs.mkdir(path.dirname(markerPath), { recursive: true });+ await fs.writeFile(+ markerPath,+ JSON.stringify({ version: 1, ownerKey, pendingIds: ['broken-plugin'] }),+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toMatchObject({ state: 'partial', legacyPluginCount: 1, canRetry: false });+ });++ it('keeps pending recovery visible when the target root itself becomes invalid', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const ownerRoot = path.join(root, 'owners', ownerKey);+ const markerPath = path.join(ownerRoot, __testing.LEGACY_GHOST_RECOVERY_MARKER);+ await fs.mkdir(ownerRoot, { recursive: true });+ await fs.writeFile(path.join(ownerRoot, 'cindy-brain'), 'replaced target root');+ await fs.writeFile(+ markerPath,+ JSON.stringify({ version: 1, ownerKey, pendingIds: ['moved-plugin'] }),+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({ state: 'partial', legacyPluginCount: 1, canRetry: false });+ });+it('reports claimed-by-other-owner and never moves plugins across accounts', async () => {const root = await tempRoot();await writeGhostDir(root, 'cindy-brain', 'valid-plugin');diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex fa45cd5681..4d2492d9b9 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -928,7 +928,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {// the auth-change activation pass after the new boundary is committed.await interruptGhostCallsForAccountBoundary();await waitForGhostMutations();- suspendAllGhosts();+ await suspendAllGhosts();// Personal IM channels have the same DB boundary. Relogin restarts them from// the next owner DB-ready callback; app:ready-for-bot remains a compatibility// retry after the new DbClient is ready.diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex c3abfcaec3..74e6a0c390 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -7,6 +7,7 @@ import JSZip from 'jszip';import {GHOST_MANIFEST_FILE,+ GHOST_MANIFEST_MAX_BYTES,GHOST_LOCALE_MAX_BYTES,GHOST_SKILL_MD_MAX_BYTES,ghostLocalePathFor,@@ -48,7 +49,41 @@ import {export const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;export const MAX_NODE_CINDY_FILE_BYTES = 128 * 1024 * 1024;/** 身份卡本身只应是小 JSON;先限流读取,避免在识别包类型前被单文件撑爆内存。 */-const MAX_GHOST_MANIFEST_BYTES = 256 * 1024;+const MAX_GHOST_MANIFEST_BYTES = GHOST_MANIFEST_MAX_BYTES;++async function readRegularFileStableWithLimit(+ filePath: string,+ maxBytes: number,+): Promise<Buffer> {+ const noFollow = fs.constants.O_NOFOLLOW ?? 0;+ const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | noFollow);+ try {+ const opened = await handle.stat();+ if (!opened.isFile() || opened.isSymbolicLink()) {+ throw new Error('source is not a regular file');+ }+ if (opened.size > maxBytes) {+ throw new Error(`source exceeds ${maxBytes} bytes`);+ }+ const bytes = Buffer.allocUnsafe(opened.size);+ let offset = 0;+ while (offset < bytes.byteLength) {+ const { bytesRead } = await handle.read(bytes, offset, bytes.byteLength - offset, null);+ if (bytesRead === 0) throw new Error('source file shrank while being read');+ offset += bytesRead;+ }+ const after = await handle.stat();+ const sameIdentity = after.isFile() &&+ after.size === opened.size &&+ after.mtimeMs === opened.mtimeMs &&+ ((opened.dev === 0 && opened.ino === 0) ||+ (after.dev === opened.dev && after.ino === opened.ino));+ if (!sameIdentity) throw new Error('source file changed while being read');+ return bytes;+ } finally {+ await handle.close().catch(() => undefined);+ }+}/*** icon 文件大小上限。icon 以 data URL 形态随 ghosts:list(sendSync)下发,* 上限同时保护装载与首帧同步 IPC 的载荷体积。@@ -446,26 +481,40 @@ export class GhostManager {if (marker.kind === 'install') {// 未提交装入(无已批准 receipt)= 不完整安装,删 finalDir;有已批准 receipt = 完整// 安装,保留(绝不删有有效批准的插件)。只删真目录,junction/链接跳过(避免穿透)。- const committed =+ const finalKind = this.recoveryEntryKind(finalDir);+ const receiptCommitted =approval.state === 'approved' &&- approval.receipt.packageSha256 === marker.packageSha256;+ (marker.receiptRevision !== undefined+ ? approval.receipt.revision === marker.receiptRevision+ : approval.receipt.packageSha256 === marker.packageSha256);+ const committed = receiptCommitted && finalKind === 'directory';+ if (receiptCommitted && finalKind !== 'directory') {+ throw new Error('committed install receipt has no published directory');+ }if (committed && marker.clearBuiltinTombstone) {if (!this.options.clearBuiltinTombstone) {throw new Error('builtin install recovery has no tombstone clearer');}this.options.clearBuiltinTombstone(id);}- if (!committed && this.recoveryEntryKind(finalDir) === 'directory') {+ if (!committed && finalKind === 'directory') {fs.rmSync(finalDir, { recursive: true, force: true });}} else {handledBackupNames.add(marker.backupDirName);const backupPath = path.join(root, marker.backupDirName);+ const backupKind = this.recoveryEntryKind(backupPath);+ const finalKind = this.recoveryEntryKind(finalDir);const committed =approval.state === 'approved' &&- approval.receipt.packageSha256 === marker.packageSha256;+ finalKind === 'directory' &&+ (marker.receiptRevision !== undefined+ ? approval.receipt.revision === marker.receiptRevision+ : approval.receipt.packageSha256 === marker.packageSha256 &&+ (marker.oldPackageSha256 !== undefined+ ? marker.oldPackageSha256 !== marker.packageSha256+ : marker.phase === 'published'));if (committed) {- const backupKind = this.recoveryEntryKind(backupPath);if (backupKind === 'directory') {fs.rmSync(backupPath, { recursive: true, force: true }); // 陈旧旧字节} else if (backupKind !== 'missing') {@@ -473,8 +522,14 @@ export class GhostManager {}} else {// 回滚:finalDir 可能是未提交新字节,删;backup 若在则搬回(旧字节+旧 receipt)。- const backupKind = this.recoveryEntryKind(backupPath);- const finalKind = this.recoveryEntryKind(finalDir);+ if (+ marker.receiptRevision !== undefined &&+ approval.state === 'approved' &&+ approval.receipt.revision === marker.receiptRevision &&+ finalKind !== 'directory'+ ) {+ throw new Error('committed update receipt has no published directory');+ }// A prepared (or legacy phase-less) marker with no backup means the// process crashed before final -> backup. Preserve the old final and// receipt instead of deleting valid installed bytes.@@ -714,6 +769,19 @@ export class GhostManager {}}+ /** Migration-only marker read: preserve transient fs errors for retry. */+ private readLegacyDisabledMarkerForMigration(dir: string): boolean {+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ try {+ const kind = classifyGhostDirEntrySync(marker);+ if (kind === 'file') return true;+ throw new Error('legacy disabled marker is not a regular file');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw error;+ }+ }+private writeDisabledMarkerSync(dir: string): void {if (classifyGhostDirEntrySync(dir) !== 'directory') {throw new Error('ghost disabled marker parent is not a real directory');@@ -987,8 +1055,7 @@ export class GhostManager {// 有未清的事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净(通常恢复已在// 构造期把它清掉,这里兜住"恢复删 finalDir 失败"的残留)。绝不迁移这种目录 ——// 它的字节来源不是"用户确认过的旧安装",而是一次未完成事务的中间态。- const pendingMutation = this.receiptStore.readPendingMutationSync(id);- if (pendingMutation.state !== 'missing') {+ if (this.hasPendingMutationJournal(id)) {result.skipped.push(id);blockedByPendingJournal.push(id);continue;@@ -1100,14 +1167,31 @@ export class GhostManager {* 没有有效 receipt 时 backfill,随包 id 照旧交给 provisioning。结果并进 ledger,* 事后可分辨来源。*/+ /**+ * 有未清事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净。任何会**写 receipt**+ * 的入口(主迁移、legacy backfill、用户重新确认)都必须让路:绝不对一次未完成事务的+ * 中间态字节铸出批准 —— 否则 journal 之后的恢复会回滚字节却留下这份 receipt/技能快照,+ * 形成永不自愈的错位授权(约束 B-2/B-5/I-1)。journal 由启动恢复负责收敛,收敛后这些+ * 入口自然放行;若恢复被卡死,退出通道由批量恢复入口负责(见约束文档 §8 已知项),+ * 而不是靠这里对中间态铸批准。+ */+ private hasPendingMutationJournal(id: string): boolean {+ return this.receiptStore.readPendingMutationSync(id).state !== 'missing';+ }+async backfillRecoveredLegacyGhosts(ids: readonly string[],- ): Promise<{ migrated: string[]; failed: string[] }> {+ options: { includePending?: boolean } = {},+ ): Promise<{ migrated: string[]; failed: string[]; pending?: string[] }> {return this.runExclusiveMutation(async () => {const out = { migrated: [] as string[], failed: [] as string[] };const retryIds: string[] = [];const root = this.contentRootDir();+ const hasLedger = this.receiptStore.hasMigrationLedger();const prev = this.receiptStore.readMigrationLedger();+ if (hasLedger && !prev) {+ throw new Error('legacy migration ledger exists but is unreadable; recovery queue preserved');+ }const pendingForRetry = new Set(prev?.pendingIds ?? []);const workIds = [...new Set(ids)].filter((id): id is string =>@@ -1117,6 +1201,7 @@ export class GhostManager {// first receipt write or subsequent processing crashes, receiptStore.write()// cannot auto-close the migration door and the remaining ids are still durable.const queuedIds = [...new Set([...pendingForRetry, ...workIds])].sort();+ const hadQueuedWork = queuedIds.length > 0;if (queuedIds.length > 0) {await this.receiptStore.writeMigrationLedger({version: 1,@@ -1143,6 +1228,16 @@ export class GhostManager {});continue;}+ if (this.hasPendingMutationJournal(id)) {+ // 与主迁移循环 candidates 阶段同一道闸:恢复未收敛前绝不对中间态字节铸批准,+ // 留在重试队列,等启动恢复收敛 journal 后下一轮再处理。+ retryIds.push(id);+ pendingForRetry.add(id);+ this.options.log?.warn('recovered legacy ghost has an unsettled mutation journal; will retry', {+ id,+ });+ continue;+ }try {if (await this.backfillLegacyApproval(path.join(root, id), id)) {out.migrated.push(id);@@ -1170,6 +1265,7 @@ export class GhostManager {}}if (+ hadQueuedWork ||out.migrated.length > 0 ||out.failed.length > 0 ||retryIds.length > 0 ||@@ -1188,7 +1284,8 @@ export class GhostManager {});}if (out.migrated.length > 0) this.options.onChanged?.(this.list());- return out;+ const pending = [...new Set(retryIds)].sort();+ return options.includePending && pending.length > 0 ? { ...out, pending } : out;});}@@ -1237,7 +1334,7 @@ export class GhostManager {if (!validated.ok) throw new Error(`invalid manifest: ${validated.reason}`);if (validated.manifest.id !== id) throw new Error('manifest id != install dir name');- const enabled = !this.isDisabledMarkerPresentSync(dir);+ const enabled = !this.readLegacyDisabledMarkerForMigration(dir);const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {level: 'unverified',publisherSigned: false,@@ -1306,6 +1403,17 @@ export class GhostManager {if (this.readApproval(id).state === 'approved') {return { rejection: { code: 'state-changed', reason: '插件批准状态已恢复,无需重新确认' } };}+ // 有未清事务标记时绝不铸批准:否则启动恢复回滚字节后会留下这份 receipt/技能快照,+ // 形成永不自愈的错位授权(B-2/B-5/I-1)。确认第二步会经此再查一次(持互斥锁,+ // 与 install/update 不交错),所以只在这里设闸即可覆盖 inspect 与 confirm 两步。+ if (this.hasPendingMutationJournal(id)) {+ return {+ rejection: {+ code: 'state-changed',+ reason: '插件有未完成的安装/更新事务正在恢复,请重启应用完成恢复后再重新确认',+ },+ };+ }const dir = path.join(this.contentRootDir(), id);try {if (classifyGhostDirEntrySync(dir) !== 'directory') {@@ -1491,9 +1599,18 @@ export class GhostManager {};}this.untrustedApprovals.delete(this.isolationKey(id));- // 与 setEnabled 同款:启停镜像同步维护,回滚到旧客户端不错位。+ // 与 setEnabled 同款:启停镜像同步维护,回滚到旧客户端不错位。写入前先 no-follow+ // 复核 marker 是受管普通文件(B-3):安装目录可变,marker 被换成符号链接时裸+ // writeFile 会穿透截断链接目标,与 setEnabled/writeDisabledMarkerSync 判据保持一致。try {const marker = path.join(dir, DISABLED_MARKER_FILE);+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }if (opts.enable) await fs.promises.rm(marker, { force: true });else await fs.promises.writeFile(marker, '');} catch {@@ -1611,6 +1728,28 @@ export class GhostManager {return result;}+ /**+ * Mutation callers may immediately use the returned object to spawn a+ * resident runtime. Always return the same authorization projection that+ * list()/runtime lookup can currently observe instead of a hand-built+ * "approved" object that could bypass an active quarantine.+ */+ private projectCommittedMutationResult(fallback: InstalledGhost): {+ ghost: InstalledGhost;+ list: InstalledGhost[];+ } {+ const list = this.list();+ const ghost =+ list.find((item) => item.manifest.id === fallback.manifest.id) ??+ ({+ ...fallback,+ enabled: false,+ approval: { state: 'invalid' },+ approvedSkillRoot: undefined,+ } satisfies InstalledGhost);+ return { ghost, list };+ }+/** receipt 内的 base manifest + 已批准 locale 资源;不再读取可变安装目录。 */private localizeApprovedManifest(receipt: GhostInstallReceipt): GhostManifest {const requestedLocale = this.options.getLocale?.();@@ -1878,23 +2017,19 @@ export class GhostManager {// 1) 读源文件(带体积上限)let buf: Buffer;try {- const stat = await fs.promises.stat(lizFilePath);- if (!stat.isFile()) {- return { rejection: { code: 'source-not-found', reason: '路径不是文件' } };+ buf = await readRegularFileStableWithLimit(lizFilePath, MAX_NODE_CINDY_FILE_BYTES);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ return { rejection: { code: 'source-not-found', reason: '文件不存在' } };}- if (stat.size > MAX_NODE_CINDY_FILE_BYTES) {+ if (err instanceof Error && err.message.includes('exceeds')) {return {rejection: {code: 'file-invalid',- reason: `文件过大:${stat.size} 字节(上限 ${MAX_NODE_CINDY_FILE_BYTES})`,+ reason: `文件超过 ${MAX_NODE_CINDY_FILE_BYTES} 字节上限`,},};}- buf = await fs.promises.readFile(lizFilePath);- } catch (err) {- if ((err as NodeJS.ErrnoException).code === 'ENOENT') {- return { rejection: { code: 'source-not-found', reason: '文件不存在' } };- }return {rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },};@@ -2249,6 +2384,7 @@ export class GhostManager {root,`.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`,);+ const receiptRevision = crypto.randomUUID();// receipt 在内容落到 finalDir 之后才创建:技能字节指纹必须从这次批准的内容// 目录现算,不能凭空构造。let receipt: GhostInstallReceipt | undefined;@@ -2269,8 +2405,10 @@ export class GhostManager {await this.receiptStore.writePendingMutation(manifest.id, {kind: 'install',packageSha256,+ receiptRevision,...(clearBuiltinTombstoneOnCommit ? { clearBuiltinTombstone: true } : {}),});+ this.untrustedApprovals.add(this.isolationKey(manifest.id));await fs.promises.rename(stagingDir, finalDir);try {receipt = createGhostInstallReceipt({@@ -2286,6 +2424,7 @@ export class GhostManager {prefix,),packageSha256,+ revision: receiptRevision,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),});await this.receiptStore.write(receipt, { skillSourceDir: finalDir });@@ -2308,13 +2447,23 @@ export class GhostManager {// receipt 已就位 = 事务提交,清标记。清失败只多留一份标记,下轮恢复见// receipt.packageSha256 与标记相符即判已提交、幂等清理。if (!tombstoneClearPending) {- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);+ try {+ await this.receiptStore.clearPendingMutation(manifest.id);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ } catch {+ // Keep quarantine while the durable journal remains.+ }+ } else {+ // The receipt and installed bytes are committed. The remaining+ // journal only records a deferred builtin tombstone side effect and+ // must not keep an otherwise valid builtin disabled in-process.+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));}- this.untrustedApprovals.delete(this.isolationKey(manifest.id));} catch (error) {try {await fs.promises.rm(finalDir, { recursive: true, force: true });await this.receiptStore.clearPendingMutation(manifest.id);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));} catch (rollbackError) {// Keep the install journal whenever rollback cannot prove the published// directory is gone. Migration treats that journal as a hard block, and@@ -2354,8 +2503,9 @@ export class GhostManager {...(iconDataUrl !== undefined ? { iconDataUrl } : {}),};this.options.log?.info('ghost installed', { id: manifest.id, version: manifest.version });- this.options.onChanged?.(this.list());- return { ghost };+ const projected = this.projectCommittedMutationResult(ghost);+ this.options.onChanged?.(projected.list);+ return { ghost: projected.ghost };}/**@@ -2474,11 +2624,13 @@ export class GhostManager {// 留下"新字节 + 旧 receipt";恢复器旧逻辑(final 在位就删 backup)会把它固化成"按旧// 批准跑新代码"。标记带本次 packageSha256 + backup 目录名,让恢复能判定 receipt 是否// 已提交:未提交则回滚到 backup。+ const receiptRevision = crypto.randomUUID();try {await this.receiptStore.writePendingMutation(manifest.id, {kind: 'update',packageSha256,backupDirName: path.basename(backupDir),+ receiptRevision,phase: 'prepared',...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256? { oldPackageSha256: approvalResult.receipt.packageSha256 }@@ -2490,12 +2642,27 @@ export class GhostManager {rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },};}+ // The durable update journal is the start of the live transaction, not just+ // a restart-recovery hint. Quarantine the id before the first directory+ // exchange so concurrent list/spawn/host calls cannot project the old+ // receipt onto the new finalDir while the new receipt and skill snapshot+ // are still being committed.+ this.untrustedApprovals.add(this.isolationKey(manifest.id));+ const clearUpdateQuarantineAfterRollback = async (): Promise<void> => {+ try {+ await this.receiptStore.clearPendingMutation(manifest.id);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ } catch {+ // Keep the in-process quarantine if the journal cannot be cleared;+ // restart recovery must see the marker before authorization resumes.+ }+ };// 换目录:旧版先挪去备份位,新版 rename 失败即滚回,保证任何时刻都有一份完整版本在位。try {await fs.promises.rename(finalDir, backupDir);} catch (err) {await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);+ await clearUpdateQuarantineAfterRollback();return {rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },};@@ -2508,6 +2675,7 @@ export class GhostManager {kind: 'update',packageSha256,backupDirName: path.basename(backupDir),+ receiptRevision,phase: 'backed-up',...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256? { oldPackageSha256: approvalResult.receipt.packageSha256 }@@ -2543,7 +2711,7 @@ export class GhostManager {// 只有回滚成功时才能清标记。回滚失败必须保留 journal,让下次启动继续收敛;// 清掉它会让 orphan-backup 启发式把新字节与旧 receipt 固化在一起。if (rolledBack) {- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);+ await clearUpdateQuarantineAfterRollback();}return {rejection: {@@ -2568,10 +2736,10 @@ export class GhostManager {prefix,),packageSha256,+ revision: receiptRevision,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),});await this.receiptStore.write(receipt, { skillSourceDir: finalDir });- this.untrustedApprovals.delete(this.isolationKey(manifest.id));} catch (err) {let rolledBack = true;await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);@@ -2588,7 +2756,7 @@ export class GhostManager {);});if (rolledBack) {- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);+ await clearUpdateQuarantineAfterRollback();}return {rejection: {@@ -2599,7 +2767,12 @@ export class GhostManager {};}// receipt 已就位 = 事务提交,清标记后再回收 backup;顺序保证"标记在 ⟺ 可能未提交"。- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);+ try {+ await this.receiptStore.clearPendingMutation(manifest.id);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ } catch {+ // Keep quarantine while the durable journal remains; recovery retries it.+ }await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => {});const ghost: InstalledGhost = {@@ -2611,8 +2784,9 @@ export class GhostManager {...(iconDataUrl !== undefined ? { iconDataUrl } : {}),};this.options.log?.info('ghost updated', { id: manifest.id, version: manifest.version });- this.options.onChanged?.(this.list());- return { ghost };+ const projected = this.projectCommittedMutationResult(ghost);+ this.options.onChanged?.(projected.list);+ return { ghost: projected.ghost };}/**@@ -2667,6 +2841,7 @@ export class GhostManager {}if (finalKind === 'missing') {await this.receiptStore.writePendingMutation(id, { kind: 'install', packageSha256 });+ this.untrustedApprovals.add(this.isolationKey(id));await fs.promises.rename(stagingDir, finalDir);return;}@@ -2677,6 +2852,7 @@ export class GhostManager {backupDirName: path.basename(backupDir),phase: 'prepared',});+ this.untrustedApprovals.add(this.isolationKey(id));await fs.promises.rename(finalDir, backupDir);await this.receiptStore.writePendingMutation(id, {kind: 'update',@@ -2705,11 +2881,17 @@ export class GhostManager {try {await fs.promises.rename(backupDir, finalDir);await this.receiptStore.clearPendingMutation(id);+ this.untrustedApprovals.delete(this.isolationKey(id));} catch {// Keep the journal for startup recovery when rollback cannot complete now.}} else if (backupKind === null && publishedKind === null) {- await this.receiptStore.clearPendingMutation(id).catch(() => undefined);+ try {+ await this.receiptStore.clearPendingMutation(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ } catch {+ // Keep the in-process quarantine while the journal remains.+ }}throw error;}@@ -2815,6 +2997,23 @@ export class GhostManager {current.receipt.packageSha256 === packageSha256 &¤t.receipt.iconDataUrl === iconDataUrl) {+ // Receipt equality is not enough for a no-op: the skill snapshot is a+ // separately materialized authorization projection and may have been+ // deleted or modified by an external cleanup/sync process. Re-enter the+ // normal receipt writer when the derived snapshot is unhealthy so the+ // immutable bundled seed can rebuild it without user action.+ const snapshotHealthy =+ (manifest.skill?.items.length ?? 0) === 0 ||+ (await this.receiptStore.skillSnapshotMatchesReceipt(+ current.receipt,+ this.receiptStore.skillSnapshotRoot(manifest.id, current.receipt.revision),+ ));+ if (!snapshotHealthy) {+ await this.receiptStore.write(current.receipt, { skillSourceDir: sourceDir });+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ return true;+ }if (current.receipt.enabled !== enabled) {await this.receiptStore.write({...current.receipt,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex aac6510f2d..c61f646275 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -391,6 +391,31 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });});+ it('legacy .disabled marker IO errors stay pending instead of becoming disabled', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const markerPath = path.join(rootDir, 'hello', '.disabled');+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {+ if (path.resolve(String(target)) === path.resolve(markerPath)) {+ spy.mockRestore();+ throw Object.assign(new Error('EIO: marker temporarily unreadable'), { code: 'EIO' });+ }+ return realLstatSync(target, options as never);+ });++ const first = await manager.migrateLegacyApprovalsOnce();+ expect(first).toMatchObject({ migrated: [], failed: [], retryPending: ['hello'] });+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({+ state: 'in-progress',+ pendingIds: ['hello'],+ });+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'legacy-unapproved' } });++ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ });+it('已有 receipt 瞬时不可读时不从可变安装目录重铸,保留原批准并持久重试', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');@@ -1105,6 +1130,28 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {expect(byId.planted).toBe('legacy-unapproved');});+ it('closes the recovery ledger when a queued id is already approved', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['hello'],+ }),+ );++ await expect(manager.backfillRecoveredLegacyGhosts(['hello'])).resolves.toEqual({+ migrated: [],+ failed: [],+ });+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({+ state: 'completed',+ });+ });+it('恢复旁路遇到 unreadable receipt 同样只排队重试,不重铸批准', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');@@ -1186,6 +1233,37 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {expect(queueSeenBeforeReceipt).toBe(true);});+ it('does not overwrite an existing recovery queue when the migration ledger is unreadable', async () => {+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });+ const originalLedger = {+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['existing'],+ };+ await fs.promises.writeFile(migrationLedgerPath(), JSON.stringify(originalLedger));+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realReadFileSync = fs.readFileSync;+ const readSpy = vi.spyOn(fs, 'readFileSync').mockImplementation((target, options) => {+ if (path.resolve(String(target)) === path.resolve(migrationLedgerPath())) {+ throw Object.assign(new Error('EIO: ledger temporarily unreadable'), { code: 'EIO' });+ }+ return realReadFileSync(target, options as never);+ });++ try {+ await expect(manager.backfillRecoveredLegacyGhosts(['recovered'])).rejects.toThrow(+ /ledger exists but is unreadable/,+ );+ } finally {+ readSpy.mockRestore();+ }+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toEqual(+ originalLedger,+ );+ });+it('P1-6:重新确认拒绝与已装插件撞名的指令', async () => {await manager.install(await makeCindy('holder.cindy', chipManifestWithCommand('holder', 'draw')),@@ -1779,9 +1857,10 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>it('已提交的更新(标记 packageSha256 == receipt)保留新字节,只回收陈旧 backup', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- const committedPkg = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ const committedReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {packageSha256: string;- }).packageSha256;+ revision: string;+ };const backupName = '.cindy-updating-hello-abcdef34';await fs.promises.mkdir(path.join(rootDir, backupName));await fs.promises.writeFile(path.join(rootDir, backupName, 'stale.txt'), 'old');@@ -1792,8 +1871,10 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>version: 1,id: 'hello',kind: 'update',- packageSha256: committedPkg, // 与 receipt 相符 = 已提交+ packageSha256: committedReceipt.packageSha256,+ receiptRevision: committedReceipt.revision,backupDirName: backupName,+ phase: 'published',}),);@@ -1804,6 +1885,87 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>expect(manager.list()[0].approval.state).toBe('approved');});+ it('same-hash backed-up update restores the only backup instead of deleting it', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');+ const receipt = JSON.parse(receiptBefore) as { packageSha256: string };+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-acde0011';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: receipt.packageSha256,+ oldPackageSha256: receipt.packageSha256,+ receiptRevision: '11111111-1111-4111-8111-111111111111',+ backupDirName: backupName,+ phase: 'backed-up',+ }),+ );++ freshManager();+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);+ });++ it('same-hash backed-up update rolls back a final whose receipt revision is still old', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ };+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-acde0022';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir);+ await fs.promises.writeFile(path.join(finalDir, 'new.txt'), 'uncommitted');+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: receipt.packageSha256,+ oldPackageSha256: receipt.packageSha256,+ receiptRevision: '22222222-2222-4222-8222-222222222222',+ backupDirName: backupName,+ phase: 'backed-up',+ }),+ );++ freshManager();+ expect(fs.existsSync(path.join(finalDir, 'new.txt'))).toBe(false);+ expect(fs.existsSync(path.join(finalDir, 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('legacy install marker with an old same-hash receipt and no final stays isolated', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ };+ await fs.promises.rm(path.join(rootDir, 'hello'), { recursive: true, force: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'install',+ packageSha256: receipt.packageSha256,+ }),+ );++ freshManager();+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(manager.list()).toEqual([]);+ });+it('卸载先撤批准再删目录:删目录失败时不留"孤立 approved receipt + 目录在"(防借尸还魂)', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));expect(manager.list()[0].approval.state).toBe('approved');@@ -2063,6 +2225,34 @@ describe('GhostManager · install', () => {expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);});+ it('returns the quarantined projection when install journal cleanup fails', async () => {+ const store = (+ manager as unknown as {+ receiptStore: { clearPendingMutation(id: string): Promise<void> };+ }+ ).receiptStore;+ const clearSpy = vi+ .spyOn(store, 'clearPendingMutation')+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));+ let result: Awaited<ReturnType<GhostManager['install']>>;+ try {+ result = await manager.install(await makeCindy('valid.cindy', goodManifest()));+ } finally {+ clearSpy.mockRestore();+ }+ expect('ghost' in result).toBe(true);+ if (!('ghost' in result)) throw new Error('expected committed install projection');+ expect(result.ghost).toMatchObject({ approval: { state: 'invalid' }, enabled: false });+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()[0]).toMatchObject({ approval: { state: 'approved' } });+ });+it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {const cindy = await makeCindy('hello.cindy', goodManifest());const result = await manager.install(cindy, { initiallyEnabled: false });@@ -2505,6 +2695,89 @@ describe('GhostManager · Host approval receipt', () => {expect(manager.list()[0].manifest.version).toBe('2.0.0');});+ it('quarantines an update while the new directory is published but receipt is not committed', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ const originalRename = fs.promises.rename;+ let releasePublish!: () => void;+ let publishStarted!: () => void;+ const publishStartedPromise = new Promise<void>((resolve) => {+ publishStarted = resolve;+ });+ const publishGate = new Promise<void>((resolve) => {+ releasePublish = resolve;+ });+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(from).includes('.cindy-installing-hello-')) {+ const result = await originalRename(from, to);+ publishStarted();+ await publishGate;+ return result;+ }+ return originalRename(from, to);+ });+ try {+ const updatePromise = manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ await publishStartedPromise;+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });+ releasePublish();+ expect('ghost' in (await updatePromise)).toBe(true);+ } finally {+ releasePublish();+ renameSpy.mockRestore();+ }+ });++ it('keeps a committed update quarantined until its durable journal is cleared', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const v2 = await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' });+ const store = (+ manager as unknown as {+ receiptStore: { clearPendingMutation(id: string): Promise<void> };+ }+ ).receiptStore;+ const clearSpy = vi+ .spyOn(store, 'clearPendingMutation')+ .mockRejectedValueOnce(new Error('journal cleanup blocked'));+ try {+ const result = await manager.update(v2, {+ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0].approval),+ });+ expect('ghost' in result).toBe(true);+ if (!('ghost' in result)) throw new Error('expected committed update projection');+ expect(result.ghost).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(manager.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'invalid' },+ enabled: false,+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(true);+ } finally {+ clearSpy.mockRestore();+ }++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()[0]).toMatchObject({+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ });+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });+it('removes the receipt and approved skill snapshots on uninstall', async () => {const manifest = {...goodManifest('skilled'),@@ -2872,6 +3145,27 @@ describe('GhostManager · Host approval receipt', () => {).toContain('Approved instructions');});+ it('bundled unchanged approval repairs a deleted skill snapshot without toggling enabled state', async () => {+ const manifest = skillManifest();+ await manager.install(await makeCindy('skill.cindy', manifest, skillFiles()));+ const listed = manager.list()[0];+ const source = await writeBundledSource(listed.manifest, skillFiles());+ const snapshotRoot = listed.approvedSkillRoot!;+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(+ await manager.approveTrustedBundledInstall(listed.manifest, listed.enabled, source),+ ).toBe(true);+ expect(manager.list()[0].enabled).toBe(listed.enabled);+ const repairedSnapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(+ await fs.promises.readFile(+ path.join(repairedSnapshotRoot, 'skills', 'demo', 'SKILL.md'),+ 'utf8',+ ),+ ).toContain('Approved instructions');+ });+it('invalidates a receipt whose skill content digests no longer match the manifest', async () => {await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));const receipt = JSON.parse(diff --git a/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.tsindex c50f912b7c..ccdea8aa07 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/dirDeposit.test.ts@@ -162,13 +162,49 @@ describe('DirDepositVault', () => {});describe('DirDepositVault userGranted 旁路(workdir 外确认卡通过后)', () => {+ it('rejects a canonical path that changed after confirmation', async () => {+ const first = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-approved-first-'));+ const second = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-approved-second-'));+ const linkPath = path.join(workdir, 'approved-link');+ try {+ await fs.promises.writeFile(path.join(first, 'a.txt'), 'first');+ await fs.promises.writeFile(path.join(second, 'b.txt'), 'second');+ try {+ await fs.promises.symlink(first, linkPath, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return;+ }+ await fs.promises.rm(linkPath, { recursive: true, force: true });+ await fs.promises.symlink(second, linkPath, process.platform === 'win32' ? 'junction' : 'dir');++ const vault = new DirDepositVault();+ const result = vault.deposit({+ ghostId: 'g1',+ dirAbs: linkPath,+ workdirAbs: workdir,+ userGranted: true,+ approvedRealPath: first,+ });+ expect(result.ok).toBe(false);+ } finally {+ await fs.promises.rm(first, { recursive: true, force: true });+ await fs.promises.rm(second, { recursive: true, force: true });+ await fs.promises.rm(linkPath, { recursive: true, force: true });+ }+ });it('workdir 外目录:未获确认拒,userGranted=true 放行且票据可正常取货', async () => {const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-outside-'));try {await fs.promises.writeFile(path.join(outside, 'a.txt'), 'hello');const vault = new DirDepositVault();expect(vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir }).ok).toBe(false);- const r = vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir, userGranted: true });+ const r = vault.deposit({+ ghostId: 'g1',+ dirAbs: outside,+ workdirAbs: workdir,+ userGranted: true,+ approvedRealPath: outside,+ });expect(r.ok).toBe(true);if (r.ok) {const taken = vault.take('g1', r.receipt.token);@@ -192,6 +228,36 @@ describe('DirDepositVault userGranted 旁路(workdir 外确认卡通过后)', ()}});+ it('出票后目录被替换为链接时,消费点拒绝跟链读取', async () => {+ const approvedParent = await fs.promises.mkdtemp(path.join(workdir, 'approved-parent-'));+ const sourceDir = path.join(approvedParent, 'source');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-ticket-outside-'));+ try {+ await fs.promises.mkdir(sourceDir, { recursive: true });+ await fs.promises.writeFile(path.join(sourceDir, 'safe.txt'), 'safe');+ await fs.promises.writeFile(path.join(outside, 'safe.txt'), 'outside');+ const vault = new DirDepositVault();+ const result = vault.deposit({ ghostId: 'g1', dirAbs: sourceDir, workdirAbs: workdir });+ if (!result.ok) throw new Error('deposit failed');++ await fs.promises.rename(sourceDir, path.join(approvedParent, 'source-old'));+ try {+ await fs.promises.symlink(+ outside,+ sourceDir,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }+ const taken = vault.take('g1', result.receipt.token);+ await expect(taken!.files[0].read()).rejects.toThrow(/changed after confirmation|identity changed/);+ } finally {+ await fs.promises.rm(approvedParent, { recursive: true, force: true });+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });+it('userGranted 不豁免存在性/类型校验:不存在的路径照拒', () => {const vault = new DirDepositVault();const r = vault.deposit({diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 5d7e5cbcc5..8259e61764 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -9,13 +9,74 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import JSZip from 'jszip';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir, type ForgeScaffoldTemplate } from '../forge';+import {+ FORGE_GUIDE,+ packGhostDir as packGhostDirRaw,+ scaffoldGhostDir as scaffoldGhostDirRaw,+ type ForgeScaffoldWriteRequest,+ type ForgeScaffoldTemplate,+} from '../forge';import { GhostManager } from '../GhostManager';let workDir: string;+async function testScaffoldWriter(request: ForgeScaffoldWriteRequest) {+ const parentStats = await fs.promises.lstat(request.parentDir);+ if (!parentStats.isDirectory() || parentStats.isSymbolicLink()) {+ return { ok: false as const, errorCode: 'INTERNAL' as const, message: 'unsafe parent' };+ }+ if (+ !(request.expectedParent.dev === 0 && request.expectedParent.ino === 0) &&+ (parentStats.dev !== request.expectedParent.dev || parentStats.ino !== request.expectedParent.ino)+ ) {+ return { ok: false as const, errorCode: 'INTERNAL' as const, message: 'parent changed' };+ }+ const target = path.join(request.parentDir, request.targetName);+ try {+ await fs.promises.lstat(target);+ return { ok: false as const, errorCode: 'TARGET_EXISTS' as const, message: 'exists' };+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ const staging = await fs.promises.mkdtemp(path.join(request.parentDir, `.${request.targetName}-scaffold-`));+ try {+ for (const file of request.files) {+ const abs = path.join(staging, file.path);+ await fs.promises.mkdir(path.dirname(abs), { recursive: true });+ await fs.promises.writeFile(abs, Buffer.from(file.base64, 'base64'), { flag: 'wx' });+ }+ try {+ await fs.promises.rename(staging, target);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EEXIST' || (error as NodeJS.ErrnoException).code === 'ENOTEMPTY') {+ return { ok: false as const, errorCode: 'TARGET_EXISTS' as const, message: 'exists' };+ }+ throw error;+ }+ return { ok: true as const };+ } catch (error) {+ await fs.promises.rm(staging, { recursive: true, force: true }).catch(() => {});+ throw error;+ }+}++function scaffoldGhostDir(+ input: Parameters<typeof scaffoldGhostDirRaw>[0],+ options: Omit<NonNullable<Parameters<typeof scaffoldGhostDirRaw>[1]>, 'writeScaffold'> = {},+) {+ return scaffoldGhostDirRaw(input, { ...options, writeScaffold: testScaffoldWriter });+}++function packGhostDir(+ dir: string,+ options: Omit<NonNullable<Parameters<typeof packGhostDirRaw>[1]>, 'sessionWorkdir'> = {},+) {+ return packGhostDirRaw(dir, { sessionWorkdir: workDir, ...options });+}+beforeEach(async () => {workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-test-'));});@@ -47,6 +108,130 @@ async function makeSrcDir(files: Record<string, string>): Promise<string> {}describe('packGhostDir', () => {+ it('writes an in-workdir alias output to the canonical source directory', async () => {+ const sourceTarget = path.join(workDir, 'source-target');+ const sourceAlias = path.join(workDir, 'source-alias');+ await fs.promises.mkdir(sourceTarget, { recursive: true });+ await fs.promises.writeFile(+ path.join(sourceTarget, 'ghost.json'),+ JSON.stringify({ ...GOOD_MANIFEST, id: 'inside' }),+ );+ await fs.promises.writeFile(path.join(sourceTarget, 'main.js'), 'export default {}');+ await fs.promises.symlink(+ sourceTarget,+ sourceAlias,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ const packed = await packGhostDir(sourceAlias);+ expect(packed).toMatchObject({ ok: true, cindyPath: path.join(sourceTarget, 'inside-1.0.0.cindy') });+ await expect(fs.promises.access(path.join(sourceTarget, 'inside-1.0.0.cindy'))).resolves.toBeUndefined();+ });++ it('rejects a file replaced by a link after classification', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': 'export default {};',+ });+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-file-race-'));+ const outsideFile = path.join(outsideRoot, 'secret.js');+ await fs.promises.writeFile(outsideFile, 'outside-secret');+ const originalLstat = fs.promises.lstat.bind(fs.promises);+ let swapped = false;+ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file) => {+ const result = await originalLstat(file);+ if (!swapped && path.basename(String(file)) === 'main.js') {+ swapped = true;+ await fs.promises.rm(String(file), { force: true });+ await fs.promises.symlink(+ outsideFile,+ String(file),+ process.platform === 'win32' ? 'file' : undefined,+ );+ }+ return result;+ });+ try {+ const packed = await packGhostDir(dir);+ expect(packed).toMatchObject({ ok: false, errorCode: 'ENTRY_MISSING' });+ await expect(fs.promises.access(path.join(dir, 'demo-1.0.0.cindy'))).rejects.toThrow();+ } finally {+ lstatSpy.mockRestore();+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });+ }+ });++ it('rejects a child directory replaced by a junction before recursion', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': 'export default {};',+ 'assets/readme.txt': 'inside',+ });+ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-dir-race-'));+ const outsideDir = path.join(outsideRoot, 'assets');+ await fs.promises.mkdir(outsideDir, { recursive: true });+ await fs.promises.writeFile(path.join(outsideDir, 'secret.txt'), 'outside-secret');+ const assetsDir = path.join(dir, 'assets');+ const originalLstat = fs.promises.lstat.bind(fs.promises);+ let swapped = false;+ const lstatSpy = vi.spyOn(fs.promises, 'lstat').mockImplementation(async (file) => {+ const result = await originalLstat(file);+ if (!swapped && path.resolve(String(file)) === path.resolve(assetsDir)) {+ swapped = true;+ await fs.promises.rm(assetsDir, { recursive: true, force: true });+ await fs.promises.symlink(+ outsideDir,+ assetsDir,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ }+ return result;+ });+ try {+ const packed = await packGhostDir(dir);+ expect(packed).toMatchObject({ ok: false, errorCode: 'SOURCE_OUTSIDE_WORKDIR' });+ await expect(fs.promises.access(path.join(dir, 'demo-1.0.0.cindy'))).rejects.toThrow();+ } finally {+ lstatSpy.mockRestore();+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });+ }+ });++ it('requires the source to stay inside the current session workdir', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': 'export default {}',+ });+ await expect(packGhostDirRaw(dir)).resolves.toMatchObject({+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ });+ await expect(+ packGhostDirRaw(dir, { sessionWorkdir: path.join(workDir, 'missing-workdir') }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ });++ const outsideRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-forge-outside-'));+ try {+ const outsideDir = path.join(outsideRoot, 'src');+ await fs.promises.cp(dir, outsideDir, { recursive: true });+ await expect(packGhostDirRaw(outsideDir, { sessionWorkdir: workDir })).resolves.toMatchObject({+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ });++ const alias = path.join(workDir, 'outside-alias');+ await fs.promises.symlink(outsideDir, alias, 'junction');+ await expect(packGhostDirRaw(alias, { sessionWorkdir: workDir })).resolves.toMatchObject({+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ });+ } finally {+ await fs.promises.rm(outsideRoot, { recursive: true, force: true });+ }+ });+it('rejects Host-managed roots, descendants, case aliases, and junction aliases', async () => {const managedRoot = path.join(workDir, 'managed');const installedDir = path.join(managedRoot, 'demo');@@ -206,6 +391,37 @@ describe('packGhostDir', () => {await fs.promises.rm(r.cindyPath, { force: true });});+ it('把已校验的 manifest 快照直接用于产物,避免校验 A、打包 B', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': 'export default {};',+ });+ const originalReaddir = fs.promises.readdir.bind(fs.promises);+ let mutated = false;+ const readdirSpy = vi.spyOn(fs.promises, 'readdir').mockImplementation(async (directory, options) => {+ const entries = await originalReaddir(directory, options as never);+ if (!mutated && path.resolve(String(directory)) === path.resolve(dir)) {+ mutated = true;+ await fs.promises.writeFile(+ path.join(dir, 'ghost.json'),+ JSON.stringify({ ...GOOD_MANIFEST, id: 'bravo', version: '9.0.0' }),+ );+ }+ return entries as never;+ });+ try {+ const packed = await packGhostDir(dir);+ expect(packed).toMatchObject({ ok: true, manifest: GOOD_MANIFEST });+ if (!packed.ok) return;+ const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));+ const manifest = await zip.file('ghost.json')?.async('string');+ expect(manifest).toContain('"id":"demo"');+ expect(manifest).not.toContain('"id":"bravo"');+ } finally {+ readdirSpy.mockRestore();+ }+ });+it('打包跳过开发残留:.git / node_modules / 隐藏文件 / 旧 .cindy 不进包', async () => {const dir = await makeSrcDir({'ghost.json': JSON.stringify(GOOD_MANIFEST),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.tsindex 08ccdd2b41..7973f639bb 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts@@ -11,6 +11,7 @@ describe('Node runtime packaging contract', () => {it('使用独立 utilityProcess bundle,且不重新打开 RunAsNode / Node 参数开关', () => {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("target: 'preload'");expect(forge).toContain('[FuseV1Options.RunAsNode]: false');expect(forge).toContain('[FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false');@@ -19,6 +20,22 @@ describe('Node runtime packaging contract', () => {expect(forge).toContain('[FuseV1Options.OnlyLoadAppFromAsar]: true');});+ it('scaffold worker is parentPort-only and does not reopen RunAsNode', () => {+ const worker = fs.readFileSync(+ path.join(desktopRoot, 'src/main/cindy-brain/forgeScaffoldWorkerProcess.ts'),+ 'utf8',+ );+ expect(worker).toContain('parentPort');+ expect(worker).toContain('verifyParent');+ expect(worker).toContain('fs.promises.rename(staging, request.targetName)');+ expect(worker).not.toContain('ELECTRON_RUN_AS_NODE');+ const capability = fs.readFileSync(+ path.join(desktopRoot, 'src/main/cindy-brain/forgeScaffoldCapability.ts'),+ 'utf8',+ );+ expect(capability).toContain('child.kill()');+ });+it('工作入口通过 parentPort 接收虚拟 stdin,不启动外部 node 命令', () => {const worker = fs.readFileSync(path.join(desktopRoot, 'src/main/cindy-brain/nodeRuntimeWorkerProcess.ts'),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.tsindex a75b382eda..8255cdd30b 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/saveDeposit.test.ts@@ -5,10 +5,14 @@import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SaveDepositVault, sanitizeSaveFileName } from '../dirDeposit.js';-import { GHOST_SAVE_DEPOSIT_MAX_USES, GHOST_SAVE_DEPOSIT_TTL_MS } from '../../../shared/ghost.js';+import {+ GHOST_SAVE_DEPOSIT_MAX_TOTAL_BYTES,+ GHOST_SAVE_DEPOSIT_MAX_USES,+ GHOST_SAVE_DEPOSIT_TTL_MS,+} from '../../../shared/ghost.js';let workdir: string;let saveDir: string;@@ -97,6 +101,100 @@ describe('SaveDepositVault', () => {}expect(await vault.write('g1', ok2.receipt.token, 'over.bin', new Uint8Array([1]))).toBeNull();});++ it('并发写入不超预算且同名文件原子去重', async () => {+ const vault = new SaveDepositVault();+ const ok = vault.deposit({ ghostId: 'g1', dirAbs: saveDir, workdirAbs: workdir });+ if (!ok.ok) throw new Error('deposit failed');++ const results = await Promise.all(+ Array.from({ length: GHOST_SAVE_DEPOSIT_MAX_USES + 2 }, () =>+ vault.write('g1', ok.receipt.token, 'parallel.txt', new Uint8Array([1])),+ ),+ );+ const successful = results.filter((result): result is { fileName: string } => result !== null);+ expect(successful).toHaveLength(GHOST_SAVE_DEPOSIT_MAX_USES);+ expect(new Set(successful.map((result) => result.fileName)).size).toBe(successful.length);+ expect(+ successful.reduce((sum, result) => sum + fs.statSync(path.join(saveDir, result.fileName)).size, 0),+ ).toBeLessThanOrEqual(GHOST_SAVE_DEPOSIT_MAX_TOTAL_BYTES);+ });++ it('出票后目标目录被替换为链接时拒绝越界写入', async () => {+ const parent = await fs.promises.mkdtemp(path.join(workdir, 'save-parent-'));+ const approved = path.join(parent, 'approved');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'save-ticket-outside-'));+ try {+ await fs.promises.mkdir(approved);+ const vault = new SaveDepositVault();+ const result = vault.deposit({ ghostId: 'g1', dirAbs: approved, workdirAbs: workdir });+ if (!result.ok) throw new Error('deposit failed');+ await fs.promises.rename(approved, path.join(parent, 'approved-old'));+ try {+ await fs.promises.symlink(+ outside,+ approved,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }+ expect(await vault.write('g1', result.receipt.token, 'escaped.txt', new Uint8Array([1]))).toBeNull();+ expect(fs.existsSync(path.join(outside, 'escaped.txt'))).toBe(false);+ } finally {+ await fs.promises.rm(parent, { recursive: true, force: true });+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });++ it('目录在校验后、独占创建前被替换时不把响应字节写出批准目录', async () => {+ const parent = await fs.promises.mkdtemp(path.join(workdir, 'save-race-parent-'));+ const approved = path.join(parent, 'approved');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'save-race-outside-'));+ const probe = path.join(parent, 'probe-link');+ try {+ await fs.promises.mkdir(approved);+ try {+ await fs.promises.symlink(+ outside,+ probe,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ await fs.promises.rm(probe, { force: true });+ } catch {+ return;+ }++ const vault = new SaveDepositVault();+ const result = vault.deposit({ ghostId: 'g1', dirAbs: approved, workdirAbs: workdir });+ if (!result.ok) throw new Error('deposit failed');+ const originalOpenSync = fs.openSync;+ let swapped = false;+ const openSpy = vi.spyOn(fs, 'openSync').mockImplementation((filePath, flags, mode) => {+ if (!swapped && String(filePath).endsWith('escaped.txt')) {+ swapped = true;+ fs.renameSync(approved, path.join(parent, 'approved-old'));+ fs.symlinkSync(+ outside,+ approved,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ }+ return originalOpenSync(filePath, flags, mode);+ });+ try {+ expect(+ await vault.write('g1', result.receipt.token, 'escaped.txt', new Uint8Array([1, 2, 3])),+ ).toBeNull();+ } finally {+ openSpy.mockRestore();+ }+ expect(fs.existsSync(path.join(outside, 'escaped.txt'))).toBe(false);+ } finally {+ await fs.promises.rm(parent, { recursive: true, force: true });+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });});describe('SaveDepositVault userGranted 旁路(workdir 外确认卡通过后)', () => {@@ -105,7 +203,13 @@ describe('SaveDepositVault userGranted 旁路(workdir 外确认卡通过后)', (try {const vault = new SaveDepositVault();expect(vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir }).ok).toBe(false);- const r = vault.deposit({ ghostId: 'g1', dirAbs: outside, workdirAbs: workdir, userGranted: true });+ const r = vault.deposit({+ ghostId: 'g1',+ dirAbs: outside,+ workdirAbs: workdir,+ userGranted: true,+ approvedRealPath: outside,+ });expect(r.ok).toBe(true);if (r.ok) {const written = await vault.write('g1', r.receipt.token, 'a.txt', new TextEncoder().encode('hi'));diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.tsindex 3e6f904cf3..01ed846cd8 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts@@ -2,14 +2,15 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';-import { packGhostDir } from '../forge';+import { packGhostDir as packGhostDirRaw } from '../forge';import { GhostManager } from '../GhostManager';import {checkSkillMdConsistency,ghostSkillLinkName,+ removeGhostSkillLinksForRoots,reconcileGhostSkillLinks as reconcileGhostSkillLinksRaw,} from '../skillSlot';@@ -20,6 +21,10 @@ let brainRoot: string;/** 与 GhostManager 缺省状态根同名(`<安装根>-install-state`),判据口径一致。 */let approvalStateRoot: string;+function packGhostDir(dir: string) {+ return packGhostDirRaw(dir, { sessionWorkdir: workDir });+}+beforeEach(async () => {workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-slot-test-'));homeDir = path.join(workDir, 'home');@@ -326,7 +331,7 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {process.platform === 'win32' ? 'junction' : 'dir',);await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });- expect(fs.existsSync(legacyLink)).toBe(false);+ expect(fs.lstatSync(legacyLink).isSymbolicLink()).toBe(true);});it('他 owner 的活链接不碰(多账号隔离);他 owner 的断链回收(防积尘)', async () => {@@ -354,6 +359,74 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {expect(fs.existsSync(liveLink)).toBe(false); // 断链回收(目标带 cindy-brain 段)});+ it('账号边界按 owner 根撤销全局 Cindy skill 投影,不删除外来链接', async () => {+ const ownerRoot = path.join(workDir, 'owners', 'bbb');+ const managedTarget = path.join(ownerRoot, 'cindy-brain', 'other-ghost', 'skills', 'foo');+ const foreignTarget = path.join(workDir, 'projects', 'other-ghost', 'skills', 'foo');+ await fs.promises.mkdir(managedTarget, { recursive: true });+ await fs.promises.mkdir(foreignTarget, { recursive: true });+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ const managedLink = path.join(sharedDir(), 'other-ghost--foo');+ const foreignLink = path.join(sharedDir(), 'foreign--foo');+ await fs.promises.symlink(managedTarget, managedLink, process.platform === 'win32' ? 'junction' : 'dir');+ await fs.promises.symlink(foreignTarget, foreignLink, process.platform === 'win32' ? 'junction' : 'dir');++ const result = await removeGhostSkillLinksForRoots([path.join(ownerRoot, 'cindy-brain')], homeDir);+ expect(result.changed).toBe(true);+ expect(fs.existsSync(managedLink)).toBe(false);+ expect(fs.existsSync(foreignLink)).toBe(true);+ });++ it('账号边界会按 raw link target 撤销已不存在 owner 根下的悬空投影', async () => {+ const ownerRoot = path.join(workDir, 'owners', 'bbb');+ const managedRoot = path.join(ownerRoot, 'cindy-brain');+ const managedTarget = path.join(managedRoot, 'other-ghost', 'skills', 'foo');+ await fs.promises.mkdir(managedTarget, { recursive: true });+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ const managedLink = path.join(sharedDir(), 'other-ghost--foo');+ await fs.promises.symlink(+ managedTarget,+ managedLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ await fs.promises.rm(managedRoot, { recursive: true, force: true });++ const result = await removeGhostSkillLinksForRoots([managedRoot], homeDir);++ expect(result.changed).toBe(true);+ expect(fs.existsSync(managedLink)).toBe(false);+ });++ it('账号边界读取全局技能根失败:记 warning 继续,不抛错阻断边界', async () => {+ // 撤链是尽力而为契约:读不动某个共享根不能把整轮撤链(以及登出)整体炸掉,+ // 否则一条无关坏项就能堵死账号边界。读失败记 warning,调用正常返回。+ const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');+ await fs.promises.mkdir(ownerRoot, { recursive: true });+ const readdir = vi.spyOn(fs.promises, 'readdir').mockRejectedValueOnce(+ Object.assign(new Error('denied'), { code: 'EACCES' }),+ );+ try {+ const result = await removeGhostSkillLinksForRoots([ownerRoot], homeDir);+ expect(result.warnings.some((w) => w.includes('Unable to read global skill root'))).toBe(true);+ } finally {+ readdir.mockRestore();+ }+ });++ it('账号边界不会把被替换成 symlink 的 owner 根当作受管根:记 warning 跳过,不抛错', async () => {+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-outside-'));+ const ownerRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');+ try {+ await fs.promises.mkdir(path.dirname(ownerRoot), { recursive: true });+ await fs.promises.symlink(outside, ownerRoot, process.platform === 'win32' ? 'junction' : 'dir');+ const result = await removeGhostSkillLinksForRoots([ownerRoot], homeDir);+ // 该根被记 warning 并跳过(不进 resolvedRoots),既不抛错也不把 symlink 目标当受管根。+ expect(result.warnings.some((w) => w.includes(ownerRoot))).toBe(true);+ } finally {+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });+it('目标缺 SKILL.md(如更新备份窗口)→ skip + warning,不建半截链', async () => {const bare = path.join(brainRoot, 'my-ghost', 'skills', 'foo');await fs.promises.mkdir(bare, { recursive: true }); // 故意不放 SKILL.mddiff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.tsindex 96c38fba2c..56e82dc78c 100644--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts@@ -244,7 +244,12 @@ function listSeedIdsInRoot(seedRootDir: string): string[] {.sort();}-/** 读墓碑列表(状态文件缺失 / 损坏一律当空,不阻断播种)。 */+/**+ * 读墓碑列表。状态文件缺失 = 无墓碑(返回空);**损坏/读不出则抛错 fail closed**+ * ——把损坏当空会让已卸载的随包意识复活(丢失卸载事实)。播种路径依赖这个抛错保持+ * fail closed;不能阻断的消费者(如 legacy 恢复状态查询)必须自己 try/catch 降级,+ * 而不是把损坏当空(见 getLegacyGhostRecoveryStatusForActiveSession)。+ */export function readBuiltinTombstones(repoRootDir: string): string[] {const result = readState(repoRootDir);if (!result.readable) {diff --git a/apps/desktop/src/main/cindy-brain/dirDeposit.ts b/apps/desktop/src/main/cindy-brain/dirDeposit.tsindex c71e6d7fb7..04771126c2 100644--- a/apps/desktop/src/main/cindy-brain/dirDeposit.ts+++ b/apps/desktop/src/main/cindy-brain/dirDeposit.ts@@ -41,9 +41,14 @@ import {export interface CollectedDirFile {/** 绝对路径(主机读盘用,不出主机)。 */absPath: string;+ /** 出票时解析出的物理路径;消费时必须仍指向同一对象。 */+ realPath: string;/** 相对目录根的 POSIX 风格路径(multipart filename,服务端按它还原结构)。 */relPath: string;size: number;+ dev: number;+ ino: number;+ mtimeMs: number;}/** 过户成功后注入 args.dir_deposit 的元数据(意识可见的全部信息)。 */@@ -88,6 +93,15 @@ export function collectDirFiles(let totalBytes = 0;const walk = (current: string): string | null => {+ try {+ const currentStat = fs.lstatSync(current);+ const currentReal = fs.realpathSync.native(current);+ if (!currentStat.isDirectory() || !isPathInsideDir(dirAbs, currentReal)) {+ return `目录结构在收集期间越出批准根:${path.relative(dirAbs, current)}`;+ }+ } catch {+ return null;+ }let entries: fs.Dirent[];try {entries = fs.readdirSync(current, { withFileTypes: true });@@ -102,9 +116,22 @@ export function collectDirFiles(if (err) return err;} else if (entry.isFile()) {if (EXCLUDE_FILE_NAMES.has(entry.name) || isEnvFile(entry.name)) continue;+ let fileStat: fs.Stats;+ let fileReal: string;+ try {+ const listed = fs.lstatSync(abs);+ if (!listed.isFile()) continue;+ fileReal = fs.realpathSync.native(abs);+ if (!isPathInsideDir(dirAbs, fileReal)) {+ return `文件结构在收集期间越出批准根:${path.relative(dirAbs, abs)}`;+ }+ fileStat = fs.statSync(abs);+ } catch {+ continue;+ }let size: number;try {- size = fs.statSync(abs).size;+ size = fileStat.size;} catch {continue;}@@ -112,7 +139,15 @@ export function collectDirFiles(return `单文件超过限额 ${GHOST_FETCH_DIR_UPLOAD_MAX_BYTES_PER_FILE} 字节:${path.relative(dirAbs, abs)}`;}const rel = path.relative(dirAbs, abs).split(path.sep).join('/');- files.push({ absPath: abs, relPath: rel, size });+ files.push({+ absPath: abs,+ realPath: fileReal,+ relPath: rel,+ size,+ dev: fileStat.dev,+ ino: fileStat.ino,+ mtimeMs: fileStat.mtimeMs,+ });totalBytes += size;if (files.length > GHOST_FETCH_DIR_UPLOAD_MAX_FILES) {return `文件数超过限额 ${GHOST_FETCH_DIR_UPLOAD_MAX_FILES},请清理无关文件或拆分上传`;@@ -140,6 +175,41 @@ export function isPathInsideDir(parentAbs: string, childAbs: string): boolean {return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));}+function sameCanonicalPath(left: string, right: string): boolean {+ const fold = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value);+ return fold(path.resolve(left)) === fold(path.resolve(right));+}++function sameCollectedFileIdentity(stat: fs.Stats, file: CollectedDirFile): boolean {+ if (stat.size !== file.size || stat.mtimeMs !== file.mtimeMs) return false;+ // Windows filesystems may report zero inode/device values. Size + mtime is+ // the fallback there; on POSIX, dev+ino also catches replacement by a file+ // reached through a swapped ancestor.+ return (file.dev === 0 && file.ino === 0) || (stat.dev === file.dev && stat.ino === file.ino);+}++async function readCollectedFile(file: CollectedDirFile): Promise<Uint8Array> {+ const currentRealPath = await fs.promises.realpath(file.absPath);+ if (!sameCanonicalPath(currentRealPath, file.realPath)) {+ throw new Error('deposited file path changed after confirmation');+ }+ const handle = await fs.promises.open(file.absPath, 'r');+ try {+ const before = await handle.stat();+ if (!sameCollectedFileIdentity(before, file)) {+ throw new Error('deposited file identity changed after confirmation');+ }+ const bytes = await handle.readFile();+ const after = await handle.stat();+ if (!sameCollectedFileIdentity(after, file)) {+ throw new Error('deposited file changed while being read');+ }+ return new Uint8Array(bytes);+ } finally {+ await handle.close().catch(() => undefined);+ }+}+interface VaultEntry {ghostId: string;files: CollectedDirFile[];@@ -167,8 +237,9 @@ export class DirDepositVault {dirAbs: string;workdirAbs: string | null;userGranted?: boolean;+ approvedRealPath?: string;}): { ok: true; receipt: DirDepositReceipt } | { ok: false; message: string } {- const { ghostId, dirAbs, workdirAbs, userGranted } = params;+ const { ghostId, dirAbs, workdirAbs, userGranted, approvedRealPath } = params;if (!path.isAbsolute(dirAbs)) {return { ok: false, message: `dir 必须是绝对路径,得到:${dirAbs}` };}@@ -201,6 +272,12 @@ export class DirDepositVault {} catch {return { ok: false, message: `目录不存在:${dirAbs}` };}+ if (userGranted && workdirAbs && !approvedRealPath) {+ return { ok: false, message: 'approved path is required for an outside-workdir grant' };+ }+ if (approvedRealPath && !sameCanonicalPath(realDir, approvedRealPath)) {+ return { ok: false, message: 'approved directory changed after confirmation' };+ }if (!userGranted && (!realWorkdir || !isPathInsideDir(realWorkdir, realDir))) {return { ok: false, message: '目录必须位于当前会话的工作目录内(不许过户 workdir 之外的路径)' };}@@ -215,7 +292,19 @@ export class DirDepositVault {if (stat.size > GHOST_FETCH_DIR_UPLOAD_MAX_BYTES_PER_FILE) {return { ok: false, message: `单文件超过限额 ${GHOST_FETCH_DIR_UPLOAD_MAX_BYTES_PER_FILE} 字节:${name}` };}- collected = { ok: true, files: [{ absPath: realDir, relPath: name, size: stat.size }], totalBytes: stat.size };+ collected = {+ ok: true,+ files: [{+ absPath: realDir,+ realPath: realDir,+ relPath: name,+ size: stat.size,+ dev: stat.dev,+ ino: stat.ino,+ mtimeMs: stat.mtimeMs,+ }],+ totalBytes: stat.size,+ };} else if (stat.isDirectory()) {collected = collectDirFiles(realDir);} else {@@ -257,7 +346,7 @@ export class DirDepositVault {files: entry.files.map((f) => ({relPath: f.relPath,size: f.size,- read: () => fs.promises.readFile(f.absPath).then((b) => new Uint8Array(b)),+ read: () => readCollectedFile(f),})),};}@@ -297,11 +386,53 @@ export interface SaveDepositReceipt {interface SaveVaultEntry {ghostId: string;dirAbs: string;+ dirDev: number;+ dirIno: number;usesLeft: number;bytesLeft: number;expiresAt: number;}+function sameFsIdentity(a: fs.Stats, b: fs.Stats): boolean {+ return a.dev !== 0 && a.ino !== 0 && b.dev === a.dev && b.ino === a.ino;+}++function writeAllToFd(fd: number, bytes: Uint8Array): Promise<void> {+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ return new Promise((resolve, reject) => {+ let offset = 0;+ const writeNext = (): void => {+ if (offset >= buffer.byteLength) {+ resolve();+ return;+ }+ fs.write(fd, buffer, offset, buffer.byteLength - offset, null, (error, written) => {+ if (error) {+ reject(error);+ return;+ }+ if (written <= 0) {+ reject(new Error('save deposit write made no progress'));+ return;+ }+ offset += written;+ writeNext();+ });+ };+ writeNext();+ });+}++function removeOpenedSaveFile(candidatePath: string, openedStat: fs.Stats): void {+ try {+ const current = fs.lstatSync(candidatePath);+ if (!current.isFile() || !sameFsIdentity(openedStat, current)) return;+ fs.rmSync(candidatePath, { force: true });+ } catch {+ // Best-effort cleanup only. Never delete a path whose identity changed.+ }+}+/** Windows 保留设备名(不区分大小写;带任意扩展名同样命中,如 NUL.pdf)。 */const WINDOWS_RESERVED_BASENAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i;@@ -326,17 +457,6 @@ export function sanitizeSaveFileName(raw: string | undefined): string {return cleaned;}-/** 防覆盖去重:已存在时在扩展名前插 " (n)"。 */-function dedupeFileName(dirAbs: string, fileName: string): string {- let candidate = fileName;- const ext = path.extname(fileName);- const stem = fileName.slice(0, fileName.length - ext.length);- for (let n = 1; fs.existsSync(path.join(dirAbs, candidate)); n++) {- candidate = `${stem} (${n})${ext}`;- }- return candidate;-}-/*** 下行落盘票据库:deposit 发票(验证目录在 workdir 内),use 验票拿写入* 闭包(TTL + ghostId 绑定 + 次数/字节双预算;写满自动作废)。@@ -351,8 +471,9 @@ export class SaveDepositVault {dirAbs: string;workdirAbs: string | null;userGranted?: boolean;+ approvedRealPath?: string;}): { ok: true; receipt: SaveDepositReceipt } | { ok: false; message: string } {- const { ghostId, dirAbs, workdirAbs, userGranted } = params;+ const { ghostId, dirAbs, workdirAbs, userGranted, approvedRealPath } = params;if (!path.isAbsolute(dirAbs)) {return { ok: false, message: `save_dir 必须是绝对路径,得到:${dirAbs}` };}@@ -382,6 +503,12 @@ export class SaveDepositVault {if (!stat.isDirectory()) {return { ok: false, message: `save_dir 不是目录:${dirAbs}` };}+ if (userGranted && workdirAbs && !approvedRealPath) {+ return { ok: false, message: 'approved path is required for an outside-workdir grant' };+ }+ if (approvedRealPath && !sameCanonicalPath(realDir, approvedRealPath)) {+ return { ok: false, message: 'approved directory changed after confirmation' };+ }if (!userGranted && (!realWorkdir || !isPathInsideDir(realWorkdir, realDir))) {return { ok: false, message: '落盘目录必须位于当前会话的工作目录内(不许写 workdir 之外)' };}@@ -390,6 +517,8 @@ export class SaveDepositVault {this.entries.set(token, {ghostId,dirAbs: realDir,+ dirDev: stat.dev,+ dirIno: stat.ino,usesLeft: GHOST_SAVE_DEPOSIT_MAX_USES,bytesLeft: GHOST_SAVE_DEPOSIT_MAX_TOTAL_BYTES,expiresAt: this.now() + GHOST_SAVE_DEPOSIT_TTL_MS,@@ -415,19 +544,101 @@ export class SaveDepositVault {this.entries.delete(token);return null;}- if (entry.usesLeft <= 0 || bytes.byteLength > entry.bytesLeft) return null;- const finalName = dedupeFileName(entry.dirAbs, sanitizeSaveFileName(fileName));try {- // 异步写:上限 256MB,同步写会把 main event loop 卡住数百 ms 到秒级- //(遇杀软实时扫描更糟),期间全部 IPC / 窗口交互冻结(规则 15)。- await fs.promises.writeFile(path.join(entry.dirAbs, finalName), bytes);+ const currentReal = fs.realpathSync.native(entry.dirAbs);+ const currentStat = fs.statSync(entry.dirAbs);+ if (+ !sameCanonicalPath(currentReal, entry.dirAbs) ||+ ((entry.dirDev !== 0 || entry.dirIno !== 0) &&+ (currentStat.dev !== entry.dirDev || currentStat.ino !== entry.dirIno))+ ) {+ return null;+ }} catch {return null;}+ if (entry.usesLeft <= 0 || bytes.byteLength > entry.bytesLeft) return null;++ // Reserve the finite budget before the first await. Otherwise parallel+ // callers all observe the same old allowance and can exceed both limits.entry.usesLeft -= 1;entry.bytesLeft -= bytes.byteLength;+ const reservedUses = 1;+ const reservedBytes = bytes.byteLength;+ const baseName = sanitizeSaveFileName(fileName);+ const ext = path.extname(baseName);+ const stem = baseName.slice(0, baseName.length - ext.length);+ let finalName: string | null = null;+ let openedPath: string | null = null;+ let openedStat: fs.Stats | null = null;+ let fd: number | null = null;+ try {+ // Reserve a name atomically. exists-then-write allows parallel calls to+ // choose the same path and overwrite each other.+ for (let n = 0; ; n += 1) {+ const candidate = n === 0 ? baseName : `${stem} (${n})${ext}`;+ const candidatePath = path.join(entry.dirAbs, candidate);+ try {+ // Open synchronously before the first await, then write through the+ // stable descriptor. Revalidate both the approved parent and the+ // opened directory entry before any response bytes are written.+ fd = fs.openSync(candidatePath, 'wx', 0o600);+ openedPath = candidatePath;+ openedStat = fs.fstatSync(fd);+ const currentReal = fs.realpathSync.native(entry.dirAbs);+ const currentDirStat = fs.statSync(entry.dirAbs);+ const currentPathStat = fs.statSync(candidatePath);+ const currentFileReal = fs.realpathSync.native(candidatePath);+ if (+ !sameCanonicalPath(currentReal, entry.dirAbs) ||+ ((entry.dirDev !== 0 || entry.dirIno !== 0) &&+ (currentDirStat.dev !== entry.dirDev || currentDirStat.ino !== entry.dirIno)) ||+ !sameCanonicalPath(path.dirname(currentFileReal), entry.dirAbs) ||+ (openedStat.dev !== 0 && openedStat.ino !== 0 &&+ !sameFsIdentity(openedStat, currentPathStat))+ ) {+ throw new Error('save deposit directory changed while opening target');+ }+ finalName = candidate;+ break;+ } catch (err) {+ if (fd !== null) {+ try {+ fs.closeSync(fd);+ } catch {+ // Ignore close failure; the write is already rejected.+ }+ fd = null;+ }+ if (openedPath && openedStat) removeOpenedSaveFile(openedPath, openedStat);+ openedPath = null;+ openedStat = null;+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') continue;+ throw err;+ }+ }+ await writeAllToFd(fd!, bytes);+ fs.closeSync(fd!);+ fd = null;+ } catch {+ if (fd !== null) {+ try {+ fs.closeSync(fd);+ } catch {+ // Ignore close failure; the write is already rejected.+ }+ }+ if (openedPath && openedStat) removeOpenedSaveFile(openedPath, openedStat);+ // Return only this call's reservation. Keep another caller's reservations+ // intact and do not resurrect an expired/replaced ticket.+ if (this.entries.get(token) === entry) {+ entry.usesLeft += reservedUses;+ entry.bytesLeft += reservedBytes;+ }+ return null;+ }if (entry.usesLeft <= 0 || entry.bytesLeft <= 0) this.entries.delete(token);- return { fileName: finalName };+ return { fileName: finalName! };}private sweep(): void {diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex b4627d0a22..72b80b7720 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -20,8 +20,11 @@ import { promisify } from 'node:util';import JSZip from 'jszip';import {+ GHOST_LOCALE_MAX_BYTES,GHOST_MANIFEST_FILE,+ GHOST_MANIFEST_MAX_BYTES,GHOST_SKILL_MD_MAX_BYTES,+ validateGhostManifestLocaleResource,validateGhostManifest,type GhostManifest,} from '../../shared/ghost.js';@@ -29,7 +32,6 @@ import {classifyGhostDirEntry,resolveGhostContentPath,} from './ghostContentTree.js';-import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';import { isPathInsideDir } from './dirDeposit.js';import { checkSkillMdConsistency } from './skillSlot.js';@@ -41,6 +43,218 @@ const MAX_NODE_TOTAL_BYTES = 256 * 1024 * 1024;const MAX_BASIC_CINDY_BYTES = 8 * 1024 * 1024;const MAX_NODE_CINDY_BYTES = 128 * 1024 * 1024;+class ForgeSourceChangedError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ForgeSourceChangedError';+ }+}++class ForgeSizeLimitError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ForgeSizeLimitError';+ }+}++function sameForgeFileIdentity(expected: fs.Stats, current: fs.Stats): boolean {+ if (!current.isFile() || expected.size !== current.size || expected.mtimeMs !== current.mtimeMs) {+ return false;+ }+ // Some Windows filesystems report zero dev/ino. Size + mtime is the portable+ // fallback there; when identity is available, replacement through a swapped+ // ancestor must also match the original object.+ return (expected.dev === 0 && expected.ino === 0) ||+ (expected.dev === current.dev && expected.ino === current.ino);+}++function sameForgeDirectoryIdentity(expected: fs.Stats, current: fs.Stats): boolean {+ if (!current.isDirectory()) return false;+ return (expected.dev === 0 && expected.ino === 0) ||+ (expected.dev === current.dev && expected.ino === current.ino);+}++function sameForgeCanonicalPath(left: string, right: string): boolean {+ const fold = (value: string) => (process.platform === 'win32' ? value.toLowerCase() : value);+ return fold(path.resolve(left)) === fold(path.resolve(right));+}++async function readForgeFileStable(+ absPath: string,+ sourceRoot: string,+ expectedFromWalk?: fs.Stats,+ maxBytes?: number,+): Promise<Buffer> {+ const realBeforeOpen = await realpathNative(absPath);+ if (!isPathInsideDir(sourceRoot, realBeforeOpen)) {+ throw new ForgeSourceChangedError('Forge source entry escaped the validated source root');+ }+ const pathStat = await fs.promises.lstat(absPath);+ if (!pathStat.isFile() || pathStat.isSymbolicLink()) {+ throw new ForgeSourceChangedError('Forge source entry changed after classification');+ }+ if (expectedFromWalk && !sameForgeFileIdentity(expectedFromWalk, pathStat)) {+ throw new ForgeSourceChangedError('Forge source file changed after classification');+ }++ const noFollow = fs.constants.O_NOFOLLOW ?? 0;+ let handle: Awaited<ReturnType<typeof fs.promises.open>>;+ try {+ handle = await fs.promises.open(absPath, fs.constants.O_RDONLY | noFollow);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'ELOOP' || code === 'ENOENT' || code === 'EISDIR' || code === 'ENOTDIR') {+ throw new ForgeSourceChangedError('Forge source entry changed before open');+ }+ throw error;+ }+ try {+ const opened = await handle.stat();+ if (!sameForgeFileIdentity(pathStat, opened)) {+ throw new ForgeSourceChangedError('Forge source file identity changed before read');+ }+ if (opened.nlink !== 1) {+ throw new ForgeSourceChangedError('Forge source file has aliases outside the validated tree');+ }+ if (maxBytes !== undefined && opened.size > maxBytes) {+ throw new ForgeSizeLimitError(`Forge source file exceeds the remaining size limit: ${absPath}`);+ }+ const bytes = Buffer.allocUnsafe(opened.size);+ let offset = 0;+ while (offset < bytes.byteLength) {+ const { bytesRead } = await handle.read(+ bytes,+ offset,+ bytes.byteLength - offset,+ null,+ );+ if (bytesRead === 0) break;+ offset += bytesRead;+ }+ if (offset !== bytes.byteLength) {+ throw new ForgeSourceChangedError('Forge source file shrank while being read');+ }+ const after = await handle.stat();+ if (!sameForgeFileIdentity(pathStat, after)) {+ throw new ForgeSourceChangedError('Forge source file changed while being read');+ }+ const realAfterRead = await realpathNative(absPath);+ if (!sameForgeCanonicalPath(realBeforeOpen, realAfterRead) ||+ !isPathInsideDir(sourceRoot, realAfterRead)) {+ throw new ForgeSourceChangedError('Forge source entry changed during read');+ }+ return bytes;+ } finally {+ await handle.close().catch(() => undefined);+ }+}++async function readForgeDirectoryEntriesStable(+ absPath: string,+ sourceRoot: string,+): Promise<fs.Dirent[]> {+ const before = await fs.promises.lstat(absPath);+ if (!before.isDirectory() || before.isSymbolicLink()) {+ throw new ForgeSourceChangedError('Forge source directory changed after classification');+ }+ const realBefore = await realpathNative(absPath);+ if (!isPathInsideDir(sourceRoot, realBefore)) {+ throw new ForgeSourceChangedError('Forge source directory escaped the validated source root');+ }+ const entries = await fs.promises.readdir(absPath, { withFileTypes: true });+ const after = await fs.promises.lstat(absPath);+ const realAfter = await realpathNative(absPath);+ if (!sameForgeDirectoryIdentity(before, after) ||+ !sameForgeCanonicalPath(realBefore, realAfter) ||+ !isPathInsideDir(sourceRoot, realAfter)) {+ throw new ForgeSourceChangedError('Forge source directory changed while being read');+ }+ return entries;+}++async function writeForgeFileStable(+ absPath: string,+ parentDir: string,+ bytes: Uint8Array,+): Promise<void> {+ const expectedParent = await fs.promises.lstat(parentDir);+ if (!expectedParent.isDirectory() || expectedParent.isSymbolicLink()) {+ throw new ForgeSourceChangedError('Forge output parent is not a regular directory');+ }+ const expectedParentReal = await realpathNative(parentDir);+ if (!sameForgeCanonicalPath(expectedParentReal, parentDir)) {+ throw new ForgeSourceChangedError('Forge output parent changed before write');+ }++ let expectedTarget: fs.Stats | null = null;+ try {+ expectedTarget = await fs.promises.lstat(absPath);+ if (!expectedTarget.isFile() || expectedTarget.isSymbolicLink()) {+ throw new ForgeSourceChangedError('Forge output path is not a regular file');+ }+ if (expectedTarget.nlink !== 1) {+ throw new ForgeSourceChangedError('Forge output path has aliases outside the validated tree');+ }+ } catch (error) {+ if (!isMissingFsError(error)) throw error;+ }++ let handle: Awaited<ReturnType<typeof fs.promises.open>>;+ const createdTarget = expectedTarget === null;+ try {+ handle = await fs.promises.open(absPath, expectedTarget ? 'r+' : 'wx');+ } catch (error) {+ if (!expectedTarget && isMissingFsError(error)) {+ throw new ForgeSourceChangedError('Forge output disappeared before write');+ }+ throw error;+ }+ try {+ const openedTarget = await handle.stat();+ const currentParent = await fs.promises.lstat(parentDir);+ const currentParentReal = await realpathNative(parentDir);+ if (!sameForgeDirectoryIdentity(expectedParent, currentParent) ||+ !sameForgeCanonicalPath(expectedParentReal, currentParentReal) ||+ !sameForgeCanonicalPath(currentParentReal, parentDir)) {+ throw new ForgeSourceChangedError('Forge output parent changed before bytes were written');+ }+ const currentTarget = await fs.promises.lstat(absPath);+ if (!currentTarget.isFile() || currentTarget.isSymbolicLink() ||+ currentTarget.nlink !== 1 ||+ !sameForgeFileIdentity(openedTarget, currentTarget) ||+ (expectedTarget && !sameForgeFileIdentity(expectedTarget, openedTarget))) {+ throw new ForgeSourceChangedError('Forge output path changed before bytes were written');+ }+ await handle.truncate(0);+ await handle.writeFile(bytes);+ const afterParent = await fs.promises.lstat(parentDir);+ const afterParentReal = await realpathNative(parentDir);+ if (!sameForgeDirectoryIdentity(expectedParent, afterParent) ||+ !sameForgeCanonicalPath(expectedParentReal, afterParentReal)) {+ throw new ForgeSourceChangedError('Forge output parent changed while writing');+ }+ } catch (error) {+ if (createdTarget) {+ try {+ const currentTarget = await fs.promises.lstat(absPath);+ const openedTarget = await handle.stat();+ if (sameForgeFileIdentity(currentTarget, openedTarget)) {+ await fs.promises.unlink(absPath);+ }+ } catch {+ // Best-effort cleanup only; never turn a boundary rejection into a write.+ }+ }+ throw error;+ } finally {+ await handle.close().catch(() => undefined);+ }+}++function isMissingFsError(error: unknown): boolean {+ return (error as NodeJS.ErrnoException).code === 'ENOENT';+}+/** 打包时跳过的目录/文件(源码目录里的开发残留,不属于意识本体)。 */function shouldSkip(name: string): boolean {if (name.startsWith('.')) return true; // .git / .DS_Store / .disabled 等@@ -55,6 +269,9 @@ export type ForgePackResult =ok: false;errorCode:| 'DIR_NOT_FOUND'+ | 'SOURCE_OUTSIDE_WORKDIR'+ | 'WORKDIR_NOT_LOCAL'+ | 'WORKDIR_READ_ONLY'| 'SOURCE_IS_INSTALLED_PLUGIN'| 'MANIFEST_INVALID'| 'ENTRY_MISSING'@@ -82,7 +299,7 @@ export type ForgeScaffoldResult =}| {ok: false;- errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'INTERNAL';+ errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'WORKDIR_NOT_LOCAL' | 'WORKDIR_READ_ONLY' | 'INTERNAL';message: string;};@@ -94,6 +311,25 @@ interface ForgeScaffoldInput {description?: string;}+export interface ForgeScaffoldWriteRequest {+ parentDir: string;+ targetName: string;+ expectedParent: {+ realPath: string;+ dev: number;+ ino: number;+ };+ files: Array<{ path: string; base64: string }>;+}++export type ForgeScaffoldWriteResult =+ | { ok: true }+ | { ok: false; errorCode: 'TARGET_EXISTS' | 'INTERNAL'; message: string };++export type ForgeScaffoldWriter = (+ request: ForgeScaffoldWriteRequest,+) => Promise<ForgeScaffoldWriteResult>;+/** 生成插件清单;先走正式校验,再允许任何文件落盘。 */function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {const common = {@@ -426,7 +662,11 @@ const realpathNative = promisify(fs.realpath.native);*/export async function scaffoldGhostDir(input: ForgeScaffoldInput,- options?: { sessionWorkdir?: string | null; forbiddenRootDirs?: readonly string[] },+ options?: {+ sessionWorkdir?: string | null;+ forbiddenRootDirs?: readonly string[];+ writeScaffold?: ForgeScaffoldWriter;+ },): Promise<ForgeScaffoldResult> {const template = input.template;if (!FORGE_SCAFFOLD_TEMPLATES.includes(template)) {@@ -494,6 +734,7 @@ export async function scaffoldGhostDir(};}}+ const targetDir = path.resolve(input.dir);const files = scaffoldFiles(input);// 显式收窄而非 as 断言:manifest 恒为 JSON 字符串,二进制项(占位图标)另存;// 未来若误把 manifest 写成 Buffer,这里在编译/测试期就报,而不是运行期 parse 炸。@@ -510,7 +751,6 @@ export async function scaffoldGhostDir(};}- const targetDir = path.resolve(input.dir);try {await fs.promises.lstat(targetDir);return {@@ -529,52 +769,81 @@ export async function scaffoldGhostDir(}const parentDir = path.dirname(targetDir);- let stagingDir: string | null = null;+ let parentStat: fs.Stats;+ let parentRealPath: string;try {- await fs.promises.mkdir(parentDir, { recursive: true });- stagingDir = await fs.promises.mkdtemp(- path.join(parentDir, `.${path.basename(targetDir)}-scaffold-`),- );- for (const [rel, content] of Object.entries(files)) {- const abs = path.join(stagingDir, rel);- await fs.promises.mkdir(path.dirname(abs), { recursive: true });- await fs.promises.writeFile(abs, content, { encoding: 'utf8', flag: 'wx' });+ parentStat = await fs.promises.lstat(parentDir);+ if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {+ return {+ ok: false,+ errorCode: 'INVALID_INPUT',+ message: 'dir 的父目录必须是工作目录内已存在的普通目录',+ };}- try {- await fs.promises.rename(stagingDir, targetDir);- stagingDir = null;- } catch (err) {- if (hasFsErrorCode(err, 'EEXIST') || hasFsErrorCode(err, 'ENOTEMPTY')) {- return {- ok: false,- errorCode: 'TARGET_EXISTS',- message: `目标已经存在,不会覆盖:${targetDir}`,- };- }- throw err;+ parentRealPath = await realpathNative(parentDir);+ if (+ !sameForgeCanonicalPath(parentRealPath, parentDir) ||+ !isPathInsideDir(realWorkdir, parentRealPath)+ ) {+ return {+ ok: false,+ errorCode: 'INVALID_INPUT',+ message: 'dir 的父目录必须是工作目录内已存在且没有链接祖先的普通目录',+ };}- return {- ok: true,- dir: targetDir,- template,- files: Object.keys(files).sort(),- nextSteps: [- '按需要修改 ghost.json、main.js 和 worker 源码。',- '调用 ghost_forge_pack 打包并让用户确认安装。',- 'Node 模板不允许在安装或首次运行时执行 npm install、npx 或 postinstall。',- ],- };} catch (err) {+ if (hasFsErrorCode(err, 'ENOENT')) {+ return {+ ok: false,+ errorCode: 'INVALID_INPUT',+ message: 'dir 的父目录必须先创建,并且必须位于当前工作目录内',+ };+ }return {ok: false,errorCode: 'INTERNAL',message: err instanceof Error ? err.message : String(err),};- } finally {- if (stagingDir) {- await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});- }}++ if (!options?.writeScaffold) {+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: 'Forge scaffold stable-directory capability is unavailable',+ };+ }+ const writeResult = await options.writeScaffold({+ parentDir,+ targetName: path.basename(targetDir),+ expectedParent: {+ realPath: parentRealPath,+ dev: parentStat.dev,+ ino: parentStat.ino,+ },+ files: Object.entries(files).map(([rel, content]) => ({+ path: rel,+ base64: (typeof content === 'string' ? Buffer.from(content, 'utf8') : content).toString('base64'),+ })),+ });+ if (!writeResult.ok) {+ return {+ ok: false,+ errorCode: writeResult.errorCode,+ message: writeResult.message,+ };+ }+ return {+ ok: true,+ dir: targetDir,+ template,+ files: Object.keys(files).sort(),+ nextSteps: [+ '按需要修改 ghost.json、main.js 和 worker 源码。',+ '调用 ghost_forge_pack 打包并让用户确认安装。',+ 'Node 模板不允许在安装或首次运行时执行 npm install、npx 或 postinstall。',+ ],+ };}/**@@ -584,9 +853,26 @@ export async function scaffoldGhostDir(*/export async function packGhostDir(dir: string,- options: { forbiddenRootDirs?: readonly string[] } = {},+ options: { sessionWorkdir?: string | null; forbiddenRootDirs?: readonly string[] } = {},): Promise<ForgePackResult> {try {+ if (!options.sessionWorkdir) {+ return {+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ message: 'Forge pack requires an active session workdir',+ };+ }+ let realWorkdir: string;+ try {+ realWorkdir = await realpathNative(path.resolve(options.sessionWorkdir));+ } catch {+ return {+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ message: 'The current session workdir does not exist',+ };+ }let stat: fs.Stats;try {stat = await fs.promises.stat(dir);@@ -597,6 +883,35 @@ export async function packGhostDir(return { ok: false, errorCode: 'DIR_NOT_FOUND', message: `不是目录:${dir}` };}const realSourceDir = await realpathNative(dir);+ if (!isPathInsideDir(realWorkdir, realSourceDir)) {+ return {+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ message: 'Forge source must be inside the current session workdir',+ };+ }+ const sourceBoundaryError = (): ForgePackResult => ({+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ message: 'Forge source changed after workdir validation',+ });+ const ensureSourceBoundary = async (): Promise<ForgePackResult | null> => {+ let currentSourceDir: string;+ try {+ currentSourceDir = await realpathNative(dir);+ } catch {+ return sourceBoundaryError();+ }+ const sameSource =+ isPathInsideDir(realSourceDir, currentSourceDir) &&+ isPathInsideDir(currentSourceDir, realSourceDir);+ return sameSource && isPathInsideDir(realWorkdir, currentSourceDir)+ ? null+ : sourceBoundaryError();+ };+ const boundaryError = await ensureSourceBoundary();+ if (boundaryError) return boundaryError;+ const sourceDir = realSourceDir;for (const forbiddenRoot of options.forbiddenRootDirs ?? []) {const resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);// 判定必须**双向**:源目录落在受管根内要拒(拿已安装插件当源码),源目录是受管根的@@ -617,12 +932,25 @@ export async function packGhostDir(}// 1) 清单先行:与装入侧同一套校验,错在打包期就报清楚。+ const validatedFileSnapshots = new Map<string, { rel: string; bytes: Buffer }>();+ const rememberValidatedSnapshot = (rel: string, bytes: Buffer): void => {+ validatedFileSnapshots.set(rel.toLowerCase(), { rel, bytes });+ };let manifestRaw: unknown;+ const boundaryBeforeManifest = await ensureSourceBoundary();+ if (boundaryBeforeManifest) return boundaryBeforeManifest;try {- manifestRaw = JSON.parse(- await fs.promises.readFile(path.join(dir, GHOST_MANIFEST_FILE), 'utf-8'),+ const manifestBytes = await readForgeFileStable(+ path.join(sourceDir, GHOST_MANIFEST_FILE),+ sourceDir,+ undefined,+ GHOST_MANIFEST_MAX_BYTES,);+ manifestRaw = JSON.parse(manifestBytes.toString('utf8'));+ rememberValidatedSnapshot(GHOST_MANIFEST_FILE, manifestBytes);} catch (err) {+ if (err instanceof ForgeSourceChangedError) throw err;+ if (err instanceof ForgeSizeLimitError) throw err;return {ok: false,errorCode: 'MANIFEST_INVALID',@@ -637,13 +965,40 @@ export async function packGhostDir(// 2) locale 资源必须真实、可解析且提供的条目合法(缺译回退原文,不拒)。// 与装入侧使用同一 validator,避免 Forge 能打包、安装却被拒的契约漂移。- const localeValidation = validateGhostLocaleResourcesInDirectory(dir, manifest);- if (!localeValidation.ok) {- return {- ok: false,- errorCode: 'MANIFEST_INVALID',- message: localeValidation.reason,- };+ for (const [locale, relativePath] of Object.entries(manifest.locales ?? {})) {+ const boundaryBeforeLocale = await ensureSourceBoundary();+ if (boundaryBeforeLocale) return boundaryBeforeLocale;+ try {+ const localePath = await resolveGhostContentPath(sourceDir, relativePath, {+ expect: 'file',+ label: `locales.${locale}`,+ });+ const localeBytes = await readForgeFileStable(+ localePath,+ sourceDir,+ undefined,+ GHOST_LOCALE_MAX_BYTES,+ );+ const localized = validateGhostManifestLocaleResource(+ JSON.parse(localeBytes.toString('utf8')) as unknown,+ manifest,+ );+ if (!localized.ok) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `locales.${locale} 不合格(${relativePath}):${localized.reason}`,+ };+ }+ rememberValidatedSnapshot(relativePath, localeBytes);+ } catch (error) {+ if (error instanceof ForgeSourceChangedError) throw error;+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `locales.${locale} 不可用(${relativePath}):${error instanceof Error ? error.message : String(error)}`,+ };+ }}// 3) 清单声明的入口文件必须真实在场(打包期拦,别等装入后沙箱 404)。@@ -652,13 +1007,17 @@ export async function packGhostDir(if (manifest.node?.entry) mustExist.push(manifest.node.entry);if (manifest.panel?.html) mustExist.push(manifest.panel.html);if (manifest.settingsHtml) mustExist.push(manifest.settingsHtml);+ for (const relativePath of Object.values(manifest.locales ?? {})) mustExist.push(relativePath);for (const item of manifest.skill?.items ?? []) mustExist.push(`${item.dir}/SKILL.md`);+ const requiredPackPaths = new Set(mustExist.map((rel) => rel.toLowerCase()));for (const rel of mustExist) {try {+ const boundaryBeforeEntry = await ensureSourceBoundary();+ if (boundaryBeforeEntry) return boundaryBeforeEntry;// 逐段解析(判据同装入侧 ghostContentTree):`stat` 会穿透链接,让"声明的// 文件是链接"通过检查,而下面的收集步按类型跳过链接 —— 包就少了这个文件,// 错误延迟到用户装入时才现形。这里直接拒,报清楚。- await resolveGhostContentPath(dir, rel, { expect: 'file', label: 'forge source' });+ await resolveGhostContentPath(sourceDir, rel, { expect: 'file', label: 'forge source' });} catch {return {ok: false,@@ -671,11 +1030,23 @@ export async function packGhostDir(// 3.5) skill 槽:SKILL.md frontmatter 与清单声明必须逐字一致。与装入侧// (GhostManager.parse)共用同一裁判,避免"Forge 能打包、安装被拒"的漂移。for (const item of manifest.skill?.items ?? []) {- const skillMdPath = path.join(dir, ...item.dir.split('/'), 'SKILL.md');+ const boundaryBeforeSkill = await ensureSourceBoundary();+ if (boundaryBeforeSkill) return boundaryBeforeSkill;+ const skillMdPath = path.join(sourceDir, ...item.dir.split('/'), 'SKILL.md');let content: string;try {- content = await fs.promises.readFile(skillMdPath, 'utf-8');+ content = (+ await readForgeFileStable(skillMdPath, sourceDir, undefined, GHOST_SKILL_MD_MAX_BYTES)+ ).toString('utf8');} catch (err) {+ if (err instanceof ForgeSourceChangedError) throw err;+ if (err instanceof ForgeSizeLimitError) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `${item.dir}/SKILL.md 过大(上限 ${GHOST_SKILL_MD_MAX_BYTES} 字节)`,+ };+ }return {ok: false,errorCode: 'ENTRY_MISSING',@@ -697,16 +1068,19 @@ export async function packGhostDir(message: `skill 条目 ${item.dir}:${consistencyError}`,};}+ rememberValidatedSnapshot(`${item.dir}/SKILL.md`, Buffer.from(content, 'utf8'));}// 4) 收集文件(递归,跳过开发残留),数量/体积设限。- const files: Array<{ rel: string; abs: string }> = [];+ const files: Array<{ rel: string; bytes: Buffer }> = [];let totalBytes = 0;const maxFiles = manifest.node ? MAX_NODE_FILES : MAX_BASIC_FILES;const maxTotalBytes = manifest.node ? MAX_NODE_TOTAL_BYTES : MAX_BASIC_TOTAL_BYTES;const seenPackPaths = new Set<string>();const walk = async (cur: string, relBase: string): Promise<ForgePackResult | null> => {- const entries = await fs.promises.readdir(cur, { withFileTypes: true });+ const boundaryBeforeRead = await ensureSourceBoundary();+ if (boundaryBeforeRead) return boundaryBeforeRead;+ const entries = await readForgeDirectoryEntriesStable(cur, sourceDir);for (const e of entries) {if (shouldSkip(e.name)) continue;const abs = path.join(cur, e.name);@@ -730,8 +1104,28 @@ export async function packGhostDir(const bad = await walk(abs, rel);if (bad) return bad;} else if (kind === 'file') {- files.push({ rel, abs });- totalBytes += (await fs.promises.stat(abs)).size;+ if (files.length >= maxFiles) {+ return { ok: false, errorCode: 'TOO_LARGE', message: `文件过多(上限 ${maxFiles} 个)` };+ }+ const validatedSnapshot = validatedFileSnapshots.get(foldedRel);+ if (validatedSnapshot && validatedSnapshot.rel !== rel) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `manifest 声明路径大小写不一致:${validatedSnapshot.rel} / ${rel}`,+ };+ }+ const bytes = validatedSnapshot?.bytes ??+ await readForgeFileStable(abs, sourceDir, undefined, maxTotalBytes - totalBytes);+ if (bytes.byteLength > maxTotalBytes - totalBytes) {+ return {+ ok: false,+ errorCode: 'TOO_LARGE',+ message: `总体积超上限(${maxTotalBytes} 字节)`,+ };+ }+ files.push({ rel, bytes });+ totalBytes += bytes.byteLength;if (files.length > maxFiles) {return { ok: false, errorCode: 'TOO_LARGE', message: `文件过多(上限 ${maxFiles} 个)` };}@@ -742,19 +1136,37 @@ export async function packGhostDir(message: `总体积超上限(${maxTotalBytes} 字节)`,};}+ } else if (requiredPackPaths.has(foldedRel)) {+ return {+ ok: false,+ errorCode: 'ENTRY_MISSING',+ message: `清单声明的文件不存在或不是普通文件(链接不可打包):${rel}`,+ };}}return null;};- const tooLarge = await walk(dir, '');+ const tooLarge = await walk(sourceDir, '');if (tooLarge) return tooLarge;+ const packedPaths = new Set(files.map((file) => file.rel.toLowerCase()));+ for (const required of requiredPackPaths) {+ if (!packedPaths.has(required)) {+ return {+ ok: false,+ errorCode: 'ENTRY_MISSING',+ message: `清单声明的文件不存在或不是普通文件(链接不可打包):${required}`,+ };+ }+ }// 5) 打包到源码目录自身(2026-07 Lizi 定案:产物跟源码住一起,拿取直观)。// 文件收集在写盘之前完成 + shouldSkip 跳过 *.cindy,自身产物不会进包;// 同名覆盖:同 id 同版本重打包语义上就是同一个包。const zip = new JSZip();for (const f of files) {- zip.file(f.rel, await fs.promises.readFile(f.abs));+ const boundaryBeforeZipRead = await ensureSourceBoundary();+ if (boundaryBeforeZipRead) return boundaryBeforeZipRead;+ zip.file(f.rel, f.bytes);}const buf = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });const maxCindyBytes = manifest.node ? MAX_NODE_CINDY_BYTES : MAX_BASIC_CINDY_BYTES;@@ -765,10 +1177,26 @@ export async function packGhostDir(message: `压缩包体积超上限(${maxCindyBytes} 字节)`,};}- const cindyPath = path.join(dir, `${manifest.id}-${manifest.version}.cindy`);- await fs.promises.writeFile(cindyPath, buf);+ const boundaryBeforeWrite = await ensureSourceBoundary();+ if (boundaryBeforeWrite) return boundaryBeforeWrite;+ const cindyPath = path.join(sourceDir, `${manifest.id}-${manifest.version}.cindy`);+ await writeForgeFileStable(cindyPath, sourceDir, buf);return { ok: true, cindyPath, manifest };} catch (err) {+ if (err instanceof ForgeSourceChangedError) {+ return {+ ok: false,+ errorCode: 'SOURCE_OUTSIDE_WORKDIR',+ message: err.message,+ };+ }+ if (err instanceof ForgeSizeLimitError) {+ return {+ ok: false,+ errorCode: 'TOO_LARGE',+ message: err.message,+ };+ }return {ok: false,errorCode: 'INTERNAL',@@ -2844,7 +3272,7 @@ if (r.ok && r.confirmed) {1. 新插件先调 \`ghost_forge_scaffold\` 生成骨架,或把已有源码放在用户工作目录下的一个文件夹里(如 \`my-ghost/\`);脚手架目标必须是新目录,绝不覆盖已有文件,- 也不能落在已安装插件目录或 Host 状态目录内(会被拒,理由同下一条);+ 其父目录必须是工作目录内已存在的普通目录;也不能落在已安装插件目录或 Host 状态目录内(会被拒,理由同下一条);2. **Forge 源码必须是当前会话工作目录里的独立作者目录**。已安装插件目录以及Host 管理的状态目录都不是源码区,禁止直接修改、打包或用路径别名绕过;若要继续开发已有插件,先把源码复制/迁出到工作目录中的新目录,再从该副本制作;diff --git a/apps/desktop/src/main/cindy-brain/forgeScaffoldCapability.ts b/apps/desktop/src/main/cindy-brain/forgeScaffoldCapability.tsnew file mode 100644index 0000000000..e48dfbbd71--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/forgeScaffoldCapability.ts@@ -0,0 +1,92 @@+import { utilityProcess } from 'electron';+import path from 'node:path';++import type {+ ForgeScaffoldWriteRequest,+ ForgeScaffoldWriteResult,+} from './forge.js';++/**+ * Consume a scaffold request from a utility process whose cwd is the already+ * validated parent directory. Relative mkdir/write/rename/rm operations then+ * stay bound to that directory even if an attacker swaps the path name after+ * the main process check. The worker also rechecks the parent identity before+ * and after consuming the request.+ */+export function writeForgeScaffoldWithStableParent(+ request: ForgeScaffoldWriteRequest,+): Promise<ForgeScaffoldWriteResult> {+ const entry = path.join(__dirname, 'forgeScaffoldWorkerProcess.js');+ const inheritedKeys = ['PATH', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL'] as const;+ const env: NodeJS.ProcessEnv = {};+ for (const key of inheritedKeys) {+ if (process.env[key] !== undefined) env[key] = process.env[key];+ }+ const child = utilityProcess.fork(entry, [], {+ cwd: request.parentDir,+ env,+ stdio: ['ignore', 'pipe', 'pipe'],+ serviceName: 'cindy-forge-scaffold',+ });+ const stderrChunks: Buffer[] = [];+ child.stderr?.on('data', (chunk: Buffer) => {+ if (Buffer.concat(stderrChunks).length < 16 * 1024) stderrChunks.push(Buffer.from(chunk));+ });++ return new Promise((resolve) => {+ let settled = false;+ let ready = false;+ const finish = (result: ForgeScaffoldWriteResult): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ // The worker is single-request by design. Always terminate it after a+ // result (including TARGET_EXISTS and INTERNAL) so repeated forge calls+ // cannot accumulate resident utility processes.+ child.kill();+ resolve(result);+ };+ const timer = setTimeout(() => {+ child.kill();+ finish({ ok: false, errorCode: 'INTERNAL', message: 'Forge scaffold worker timed out' });+ }, 30_000);+ timer.unref?.();++ child.on('message', (message: unknown) => {+ if (+ !ready &&+ message &&+ typeof message === 'object' &&+ (message as { type?: unknown }).type === 'ready'+ ) {+ ready = true;+ child.postMessage({ type: 'scaffold', request: {+ expectedParent: request.expectedParent,+ targetName: request.targetName,+ files: request.files,+ } });+ return;+ }+ if (!message || typeof message !== 'object') return;+ const result = message as Partial<ForgeScaffoldWriteResult>;+ if (result.ok === true) {+ finish({ ok: true });+ } else if (result.ok === false && (result.errorCode === 'TARGET_EXISTS' || result.errorCode === 'INTERNAL')) {+ finish({ ok: false, errorCode: result.errorCode, message: String(result.message ?? 'Forge scaffold worker failed') });+ }+ });+ child.on('error', (error: unknown) => {+ finish({+ ok: false,+ errorCode: 'INTERNAL',+ message: error instanceof Error ? error.message : String(error),+ });+ });+ child.on('exit', (code: number) => {+ if (!settled && code !== 0) {+ const stderr = Buffer.concat(stderrChunks).toString('utf8').trim();+ finish({ ok: false, errorCode: 'INTERNAL', message: stderr || `Forge scaffold worker exited (${code})` });+ }+ });+ });+}diff --git a/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.ts b/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.tsnew file mode 100644index 0000000000..75d41d5d7d--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/forgeScaffoldWorkerProcess.ts@@ -0,0 +1,132 @@+import fs from 'node:fs';+import path from 'node:path';++interface Request {+ expectedParent: { realPath: string; dev: number; ino: number };+ targetName: string;+ files: Array<{ path: string; base64: string }>;+}++interface ParentPortLike {+ postMessage(message: unknown): void;+ on(event: 'message', listener: (event: { data: unknown }) => void): void;+}++const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;+if (!parentPort) throw new Error('Forge scaffold worker missing parentPort');++function send(message: unknown): void {+ parentPort?.postMessage(message);+}++function samePath(left: string, right: string): boolean {+ const normalize = (value: string) => {+ const resolved = path.resolve(value);+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;+ };+ return normalize(left) === normalize(right);+}++function hasCode(error: unknown, code: string): boolean {+ return Boolean(error && typeof error === 'object' && 'code' in error && error.code === code);+}++function sameParentIdentity(stats: fs.Stats, expected: Request['expectedParent']): boolean {+ if (!stats.isDirectory() || stats.isSymbolicLink()) return false;+ return (expected.dev === 0 && expected.ino === 0) ||+ (stats.dev === expected.dev && stats.ino === expected.ino);+}++async function verifyParent(expected: Request['expectedParent']): Promise<void> {+ const stats = await fs.promises.lstat('.');+ if (!sameParentIdentity(stats, expected)) throw new Error('Forge scaffold parent identity changed');+ const real = await fs.promises.realpath('.');+ if (!samePath(real, expected.realPath)) throw new Error('Forge scaffold parent path changed');+}++function safeRelative(relative: string): boolean {+ if (!relative || relative.includes('\0') || path.isAbsolute(relative)) return false;+ const normalized = path.normalize(relative);+ return normalized !== '..' && !normalized.startsWith(`..${path.sep}`);+}++async function run(request: Request): Promise<void> {+ if (+ !request ||+ typeof request.targetName !== 'string' ||+ request.targetName !== path.basename(request.targetName) ||+ request.targetName === '.' ||+ request.targetName === '..' ||+ !Array.isArray(request.files) ||+ request.files.length > 32 ||+ request.files.some((file) => !file || !safeRelative(file.path) || typeof file.base64 !== 'string')+ ) {+ throw new Error('Invalid Forge scaffold worker request');+ }+ await verifyParent(request.expectedParent);++ try {+ await fs.promises.lstat(request.targetName);+ send({ ok: false, errorCode: 'TARGET_EXISTS', message: '目标已经存在,不会覆盖' });+ return;+ } catch (error) {+ if (!hasCode(error, 'ENOENT')) throw error;+ }++ let staging: string | null = null;+ try {+ staging = await fs.promises.mkdtemp(`.${request.targetName}-scaffold-`);+ for (const file of request.files) {+ const target = path.join(staging, file.path);+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL |+ (fs.constants.O_NOFOLLOW ?? 0);+ const handle = await fs.promises.open(target, flags, 0o600);+ try {+ await handle.writeFile(Buffer.from(file.base64, 'base64'));+ await handle.sync();+ } finally {+ await handle.close();+ }+ }+ await verifyParent(request.expectedParent);+ const stagingStat = await fs.promises.lstat(staging);+ if (!stagingStat.isDirectory() || stagingStat.isSymbolicLink()) {+ throw new Error('Forge scaffold staging directory changed');+ }+ try {+ await fs.promises.rename(staging, request.targetName);+ } catch (error) {+ if (hasCode(error, 'EEXIST') || hasCode(error, 'ENOTEMPTY')) {+ send({ ok: false, errorCode: 'TARGET_EXISTS', message: '目标已经存在,不会覆盖' });+ return;+ }+ throw error;+ }+ staging = null;+ await verifyParent(request.expectedParent);+ send({ ok: true });+ } finally {+ if (staging) {+ try {+ const stat = await fs.promises.lstat(staging);+ if (stat.isDirectory() && !stat.isSymbolicLink()) {+ await fs.promises.rm(staging, { recursive: true, force: true });+ }+ } catch {+ // Keep the boundary fail-closed; never retry cleanup through an unknown path.+ }+ }+ }+}++let handled = false;+send({ type: 'ready' });+parentPort.on('message', (event) => {+ const message = event.data as { type?: unknown; request?: Request };+ if (handled || message?.type !== 'scaffold' || !message.request) return;+ handled = true;+ run(message.request).catch((error) => {+ send({ ok: false, errorCode: 'INTERNAL', message: error instanceof Error ? error.message : String(error) });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 765bc7ee5f..29802ab55c 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -126,17 +126,24 @@ export interface GhostLegacyMigrationLedger {* "新字节 + 旧 receipt",恢复器旧逻辑(final 在位就删 backup)会把它固化成"按旧批准* 跑新代码"。*- * `packageSha256` 是判定「提交是否完成」的唯一信号:装入/更新写出的 receipt 一定带上- * 这次 `.cindy` 的哈希,所以启动恢复只需**同步**读 receipt、比对- * `receipt.packageSha256 === marker.packageSha256` —— 相等 = receipt 已写(提交完成),- * 不等/缺失 = 未提交。两者都是已落盘事实,判定不引入额外写窗口。+ * 新 marker 用 `receiptRevision` 作为本次事务的提交 nonce,避免更新前后包 hash 相同+ * 时把旧 receipt 误认成本次提交。`packageSha256` 与 phase 只用于兼容旧 marker;无法+ * 区分新旧 receipt 时必须走保守恢复方向,不得删除唯一 backup。*/export type GhostPendingMutation =- | { kind: 'install'; packageSha256: string; clearBuiltinTombstone?: boolean }+ | {+ kind: 'install';+ packageSha256: string;+ /** Revision of the receipt this transaction intends to publish. */+ receiptRevision?: string;+ clearBuiltinTombstone?: boolean;+ }| {kind: 'update';packageSha256: string;backupDirName: string;+ /** Revision of the receipt this transaction intends to publish. */+ receiptRevision?: string;/** Durable phase for distinguishing pre-rename crashes from swapped content. */phase?: 'prepared' | 'backed-up' | 'published';/** Hash of the previously approved bytes, when an approval existed. */@@ -566,6 +573,12 @@ export class GhostInstallReceiptStore {return { state: 'invalid', reason: 'journal packageSha256 is invalid' };}if (raw.kind === 'install') {+ if (+ raw.receiptRevision !== undefined &&+ (typeof raw.receiptRevision !== 'string' || !isRevision(raw.receiptRevision))+ ) {+ return { state: 'invalid', reason: 'journal receiptRevision is invalid' };+ }if (raw.clearBuiltinTombstone !== undefined &&typeof raw.clearBuiltinTombstone !== 'boolean'@@ -577,6 +590,9 @@ export class GhostInstallReceiptStore {mutation: {kind: 'install',packageSha256: raw.packageSha256,+ ...(typeof raw.receiptRevision === 'string'+ ? { receiptRevision: raw.receiptRevision }+ : {}),...(raw.clearBuiltinTombstone === true ? { clearBuiltinTombstone: true } : {}),},};@@ -596,6 +612,13 @@ export class GhostInstallReceiptStore {return { state: 'invalid', reason: 'journal update phase is invalid' };}const oldPackageSha256 = raw.oldPackageSha256;+ const receiptRevision = raw.receiptRevision;+ if (+ receiptRevision !== undefined &&+ (typeof receiptRevision !== 'string' || !isRevision(receiptRevision))+ ) {+ return { state: 'invalid', reason: 'journal receiptRevision is invalid' };+ }if (oldPackageSha256 !== undefined &&(typeof oldPackageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(oldPackageSha256))@@ -608,6 +631,7 @@ export class GhostInstallReceiptStore {kind: 'update',packageSha256: raw.packageSha256,backupDirName: raw.backupDirName,+ ...(receiptRevision !== undefined ? { receiptRevision } : {}),...(phase !== undefined ? { phase } : {}),...(oldPackageSha256 !== undefined ? { oldPackageSha256 } : {}),},@@ -916,12 +940,13 @@ export function createGhostInstallReceipt(input: {/** 由 `hashApprovedSkillContent` 从**这次批准的内容目录**现算,不可沿用旧值。 */skillContentSha256: Record<string, string>;packageSha256?: string;+ revision?: string;iconDataUrl?: string;}): GhostInstallReceipt {return {schemaVersion: RECEIPT_SCHEMA_VERSION,id: input.manifest.id,- revision: crypto.randomUUID(),+ revision: input.revision ?? crypto.randomUUID(),manifest: input.manifest,localeResources: input.localeResources,enabled: input.enabled,diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 55b6a7cf56..92ab1ab35a 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -112,7 +112,7 @@ import { mapGhostOauthConnectError } from './ghostOauthSetupError.js';import { reclaimLoopbackPort } from './portReclaim.js';import { GhostConnectionManager } from './ghostConnections.js';import { getResolvedMainLocale, t } from '../i18n.js';-import { reconcileGhostSkillLinks } from './skillSlot.js';+import { reconcileGhostSkillLinks, removeGhostSkillLinksForRoots } from './skillSlot.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import {FILO_GOOGLE_GHOST_ID,@@ -252,8 +252,10 @@ import * as localDbSchema from '../localDb/schema.js';import { eq } from 'drizzle-orm';import { requireAppCapability } from '../appCapabilities.js';import {+ acknowledgeRecoveredLegacyGhosts,getLegacyGhostRecoveryStatus,hasLegacyOwnerNamespaceClaim,+ listLegacyOwnerProjectionRoots,listLegacyGhostPluginSources,listLegacyGhostTombstoneRoots,recoverLegacyGhostPlugins,@@ -376,9 +378,21 @@ function getLegacyGhostRecoveryStatusForActiveSession(): LegacyGhostRecoveryStatownerId === null? new Set<string>(): new Set(- listLegacyGhostTombstoneRoots(ownerId, app.getPath('userData')).flatMap((root) =>- readBuiltinTombstones(root),- ),+ listLegacyGhostTombstoneRoots(ownerId, app.getPath('userData')).flatMap((root) => {+ try {+ return readBuiltinTombstones(root);+ } catch (err) {+ // 一份损坏的 legacy .builtin-provisioning.json 不能打死整个恢复入口(状态查询+ // 与重试都经此)。降级为"该根无墓碑"并记录;漏掉的 builtin 排除仍由 backfill 的+ // isTrustedBundledId 闸兜底,不会因此把随包 id 误迁 —— 对齐 ghosts:builtin-status+ // 的降级语义,而不是让 recovery UI 整体不可用(§5 恢复入口必须可用)。+ log.warn('legacy builtin tombstone root unreadable during recovery status; treated as empty', {+ root,+ error: err instanceof Error ? err.message : String(err),+ });+ return [] as string[];+ }+ }),);const reservedBuiltinCommands = new Set(listEligibleBuiltinCommands(@@ -403,6 +417,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe}const initialStatus = getLegacyGhostRecoveryStatusForActiveSession();if (!initialStatus.canRetry) return initialStatus;+ if (initialStatus.deferredReason === 'legacy-discovery-incomplete') return initialStatus;const releaseMutation = beginGhostMutation(expectedOwner);try {@@ -411,6 +426,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostReif (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();const authorizedStatus = getLegacyGhostRecoveryStatusForActiveSession();if (!authorizedStatus.canRetry) return authorizedStatus;+ if (authorizedStatus.deferredReason === 'legacy-discovery-incomplete') return authorizedStatus;const existingGhosts = getGhostManager().list();const existingGhostById = new Map(@@ -520,11 +536,15 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRethrow error;}if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();- if (result.moved === 0 && !result.provisioningStateMoved) {+ if (+ result.moved === 0 &&+ !result.provisioningStateMoved &&+ !result.recoveredIds?.length+ ) {restartStoppedActiveGhosts();return getLegacyGhostRecoveryStatusForActiveSession();}- if (result.moved > 0 || result.provisioningStateMoved) {+ if (result.moved > 0 || result.provisioningStateMoved || result.recoveredIds?.length) {brainRootCache = null;const restoredBeforeReconcile = getGhostManager().list();const movedGhostIds = new Set<string>();@@ -539,24 +559,26 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRegetGhostNodeRuntimeBroker().stop(ghost.manifest.id);}}- // 恢复搬进来的旧布局目录补 backfill:首轮迁移可能早已跑过并落了一次性 ledger- // (当时安装根还是空的),不补的话这批旧插件会全部卡在 legacy-unapproved,违反- // §5 升级无感红线。旁路只作用于本次恢复实际搬动/新增的 id(信任级与首轮迁移- // 等同:来源是恢复流程刚认领的旧世界布局,不是安装根里凭空冒出的目录)。- const recoveredLegacyIds = [- ...movedGhostIds,- ...restoredBeforeReconcile- .filter((ghost) => !existingGhostDirs.has(ghost.manifest.id))- .map((ghost) => ghost.manifest.id),- ];+ // 只有 owner recovery 在 rename 前写入并在本轮确认的 durable marker 才能进入+ // receipt backfill。不能从安装根扫描结果推断“刚搬入”,否则同一时间窗内由其他+ // 写者放入的无 receipt 目录会被当成 legacy 事实自动铸造批准。+ const recoveredLegacyIds = [...(result.recoveredIds ?? [])];if (recoveredLegacyIds.length > 0) {- await getGhostManager()- .backfillRecoveredLegacyGhosts(recoveredLegacyIds)- .catch((err) =>- log.warn('recovered legacy ghost backfill pass failed', {- error: err instanceof Error ? err.message : String(err),- }),+ try {+ const backfill = await getGhostManager().backfillRecoveredLegacyGhosts(+ recoveredLegacyIds,+ { includePending: true },);+ const pending = new Set(backfill.pending ?? []);+ await acknowledgeRecoveredLegacyGhosts(+ expectedOwner.dataOwnerId,+ recoveredLegacyIds.filter((id) => !pending.has(id)),+ );+ } catch (err) {+ log.warn('recovered legacy ghost backfill pass failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ }}const builtinReconcileSucceeded =result.deferredReason !== 'concurrent-live-instances' &&@@ -643,11 +665,25 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {await getGhostSetupCoordinator()?.waitForActionsIdle();}-/** Stop every sandbox before changing the active data owner. */-export function suspendAllGhosts(): void {+function listGhostOwnerProjectionRoots(): string[] {+ const activeOwnerRoot = ownerScopedUserDataPath();+ return [...new Set([+ path.join(activeOwnerRoot, 'brain'),+ path.join(activeOwnerRoot, 'cindy-brain'),+ path.join(activeOwnerRoot, 'ghost-install-state'),+ ...listLegacyOwnerProjectionRoots(app.getPath('userData')),+ ])];+}++/** Stop every sandbox and revoke global skill projections before changing the active data owner. */+export async function suspendAllGhosts(): Promise<void> {runtimeSingleton?.destroyAll();resetNodeRuntimeBrokerForAccountBoundary();brainRootCache = null;+ const skillCleanup = await removeGhostSkillLinksForRoots(listGhostOwnerProjectionRoots());+ for (const warning of skillCleanup.warnings) {+ log.warn('ghost owner skill cleanup warning', { warning });+ }}let ipcRegistered = false;@@ -685,6 +721,16 @@ function isTrustedBundledSource(id: string, sourceDir: string): boolean {return isTrustedBuiltinSeedSource(builtinSeedRootDirs(), id, sourceDir);}+/**+ * Forge scaffold/pack 绝不允许写入的 Host 受管根:安装内容根 + 批准状态根(来自+ * `managedRootDirs()`)+ **随包 seed 根**。seed 根漏在外面时,把 `.cindy` 产物写进+ * seed 目录会翻转播种指纹,下次启动触发整目录重播种(B-4);seed 根与内容/状态根+ * 物理不相交,不在 `managedRootDirs()` 内,必须在此显式并入。+ */+export function ghostForgeForbiddenRootDirs(): string[] {+ return [...getGhostManager().managedRootDirs(), ...builtinSeedRootDirs()];+}+function hasDisabledMarker(dir: string): boolean {try {fs.lstatSync(path.join(dir, '.disabled'));@@ -4596,7 +4642,8 @@ export function registerGhostIpc(): void {ipcMain.handle('ghosts:runtime-states', () => ({ states: runtime.listStates() }));// 面板错误态的「重载意识」:清熔断记账 + 重新拉起沙箱。- ipcMain.handle('ghosts:reload', async (_event, id: unknown) => {+ ipcMain.handle('ghosts:reload', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);if (typeof id !== 'string' || id.trim().length === 0) {throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');}diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.tsindex 99d692b758..e371fc37fe 100644--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@ -37,6 +37,7 @@*/import { promises as fsp } from 'node:fs';+import type { Dirent } from 'node:fs';import path from 'node:path';import matter from 'gray-matter';@@ -97,6 +98,100 @@ export interface ReconcileGhostSkillLinksResult {warnings: string[];}+/**+ * Remove Cindy-managed global skill projections for every owner root during an+ * account boundary. This is intentionally separate from the active-owner+ * reconcile: the latter must preserve user-owned foreign links, while a+ * boundary must revoke all Cindy-owned projections before the next owner is+ * visible.+ *+ * Best-effort by contract: the shared skill roots are world-writable and shared+ * with other tools, so a single unrelated bad entry (a self-referential link, an+ * inaccessible target segment) must NOT abort the whole revocation. Every failure+ * is collected into `warnings` and the sweep continues; callers log the warnings+ * but proceed with the account boundary. Throwing here would both strand old+ * owner links across the boundary (I-2) and block logout entirely (the teardown+ * path does not wrap this call).+ */+export async function removeGhostSkillLinksForRoots(+ managedRoots: readonly string[],+ homeDir?: string,+): Promise<{ changed: boolean; warnings: string[] }> {+ const warnings: string[] = [];+ let changed = false;+ const paths = sharedGlobalSkillsPaths(homeDir);+ const lexicalRoots = [...new Set(managedRoots.map(normalizeForCompare))];+ const resolvedRoots: string[] = [];+ for (const root of managedRoots) {+ try {+ const rootStat = await fsp.lstat(root);+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {+ warnings.push(`Managed owner skill root is not a regular directory: ${root}`);+ continue;+ }+ resolvedRoots.push(normalizeForCompare(await fsp.realpath(root)));+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ warnings.push(`Unable to resolve managed owner skill root ${root}: ${(err as Error).message}`);+ }+ }+ }+ if (lexicalRoots.length === 0) return { changed, warnings };++ for (const dir of [paths.sharedSkillsDir, paths.claudeSkillsDir, paths.codexSkillsDir]) {+ let entries: Dirent[];+ try {+ entries = await fsp.readdir(dir, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;+ warnings.push(`Unable to read global skill root ${dir}: ${(err as Error).message}`);+ continue;+ }+ for (const entry of entries) {+ if (!entry.isSymbolicLink()) continue;+ const linkPath = path.join(dir, entry.name);+ let target: string;+ let roots = resolvedRoots;+ try {+ target = normalizeForCompare(await fsp.realpath(linkPath));+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ // 无关的坏链(自环 ELOOP、目标段 EACCES)不能中断整轮撤链:记 warning 跳过。+ warnings.push(`Unable to resolve owner skill link ${linkPath}: ${(err as Error).message}`);+ continue;+ }+ let rawTarget: string;+ try {+ rawTarget = await fsp.readlink(linkPath);+ } catch (readlinkError) {+ if ((readlinkError as NodeJS.ErrnoException).code === 'ENOENT') continue;+ warnings.push(+ `Unable to read dangling owner skill link ${linkPath}: ${(readlinkError as Error).message}`,+ );+ continue;+ }+ target = normalizeForCompare(path.resolve(path.dirname(linkPath), rawTarget));+ roots = lexicalRoots;+ }+ if (!roots.some((root) => isSameOrInside(target, root))) continue;+ try {+ const stat = await fsp.lstat(linkPath);+ if (!stat.isSymbolicLink()) {+ warnings.push(`Skipped owner skill link that changed before removal: ${linkPath}`);+ continue;+ }+ await fsp.unlink(linkPath);+ changed = true;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') continue;+ warnings.push(`Unable to remove owner skill link ${linkPath}: ${(err as Error).message}`);+ continue;+ }+ }+ }+ return { changed, warnings };+}+interface ReconcileOptions {ghosts: InstalledGhost[];/** 当前 owner 的插件安装根(userData/.../cindy-brain)。 */@@ -146,6 +241,7 @@ function targetLooksGhostManaged(target: string,linkName: string,approvalStateDirName: string,+ managedRoots: readonly string[],): boolean {// 链接名必须完整符合我们自己的命名契约:`<合法 ghostId>--<合法技能名>`// (按最后一个 `--` 拆分,与 ghostSkillLinkName 同规)。只看 includes('--')@@ -165,6 +261,8 @@ function targetLooksGhostManaged(const segments = target.split(/[\\/]/).map((segment) => segment.toLowerCase());const stateDirName = approvalStateDirName.toLowerCase();const idLower = ghostId.toLowerCase();+ const normalizedTarget = normalizeForCompare(target);+ if (!managedRoots.some((root) => isSameOrInside(normalizedTarget, root))) return false;return segments.some((segment, index) =>(segment === 'cindy-brain' && segments[index + 1] === idLower) ||@@ -285,7 +383,7 @@ export async function reconcileGhostSkillLinks(const absTarget = path.isAbsolute(rawTarget)? rawTarget: path.resolve(sharedSkillsDir, rawTarget);- if (targetLooksGhostManaged(absTarget, entName, approvalStateDirName)) {+ if (targetLooksGhostManaged(absTarget, entName, approvalStateDirName, managedRootCompares)) {toRemove.push(entName);}}diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex 932caaf0d6..195b1b3e01 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -23,6 +23,14 @@ const tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'ghost-workdir-gate-')const prefsFile = () => path.join(tmpUserData, 'ghost-workdir-prefs.json');const logWarnMock = vi.fn();const grantAttachmentsMock = vi.fn();+const { packGhostDirMock } = vi.hoisted(() => ({ packGhostDirMock: vi.fn() }));+const releaseMutationMock = vi.fn();+const captureMutationOwnerMock = vi.fn(() => ({+ mode: 'local' as const,+ dataOwnerId: 'test',+ generation: 0,+}));+const acquireMutationLeaseMock = vi.fn(() => releaseMutationMock);vi.mock('electron', () => ({ app: { getPath: () => tmpUserData } }));vi.mock('../../appSessionState.js', () => ({@@ -51,19 +59,25 @@ const ensureReadyMock = vi.fn(assessment: { state: 'ready' as const, revision: 0, groups: [] },}),);-const sessionSnapshotMock = vi.fn(async () => ({+const sessionSnapshotMock = vi.fn(async (): Promise<{+ workingDir: string;+ permissionMode: string;+ planModeEnabled: boolean;+ remoteHostId: string | null;+}> => ({workingDir: WORKDIR,permissionMode: 'auto',planModeEnabled: false,remoteHostId: null,}));vi.mock('../../cindy-brain/index.js', () => ({- getGhostManager: () => ({ list: listMock }),+ getGhostManager: () => ({ list: listMock, managedRootDirs: () => [] }),+ ghostForgeForbiddenRootDirs: () => [],listAvailableGhostsForAuthorization: () => listMock(),findAvailableGhostForAuthorization: (id: string) =>listMock().find((ghost: any) => ghost.manifest?.id === id) ?? null,- captureGhostMutationOwnerForMcp: () => ({ mode: 'local', dataOwnerId: 'test', generation: 0 }),- acquireGhostMutationLeaseForMcp: () => () => {},+ captureGhostMutationOwnerForMcp: captureMutationOwnerMock,+ acquireGhostMutationLeaseForMcp: acquireMutationLeaseMock,getGhostPipeDispatcher: () => ({ callGhostTool: dispatchMock }),getGhostCardService: () => ({ registerCall: () => {}, finalizeCall: () => null }),getGhostSetupAssessment: setupAssessmentMock,@@ -90,7 +104,11 @@ vi.mock('../../cindy-brain/dirDeposit.js', () => ({vi.mock('../../cindy-brain/ghostGrantConfirmBridge.js', () => ({ getGhostGrantConfirmBridge: vi.fn() }));vi.mock('../../cindy-brain/ghostLocalPathGrant.js', () => ({ classifyLocalAttachmentPath: vi.fn() }));vi.mock('../../cindy-brain/cardService.js', () => ({ withCardToken: (r: unknown) => r }));-vi.mock('../../cindy-brain/forge.js', () => ({ FORGE_GUIDE: 'guide', packGhostDir: vi.fn() }));+vi.mock('../../cindy-brain/forge.js', () => ({+ FORGE_GUIDE: 'guide',+ packGhostDir: packGhostDirMock,+ scaffoldGhostDir: vi.fn(),+}));vi.mock('../../cindy-brain/openFileInstall.js', () => ({ handleIncomingCindyFile: vi.fn() }));vi.mock('../../localDb/ipc/sessions.js', () => ({getSessionFsSnapshot: sessionSnapshotMock,@@ -148,6 +166,9 @@ beforeEach(() => {});grantAttachmentsMock.mockReset();logWarnMock.mockClear();+ releaseMutationMock.mockClear();+ captureMutationOwnerMock.mockClear();+ acquireMutationLeaseMock.mockClear();sessionSnapshotMock.mockReset();sessionSnapshotMock.mockResolvedValue({workingDir: WORKDIR,@@ -155,9 +176,62 @@ beforeEach(() => {planModeEnabled: false,remoteHostId: null,});+ packGhostDirMock.mockReset();+ packGhostDirMock.mockResolvedValue({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: 'stop after gate assertion',+ });clearAllPrefs();});+describe('Forge session workdir gate', () => {+ it('holds the owner mutation lease across the Forge operation', async () => {+ const operation = makeDeps().forgePack({ dir: path.join(WORKDIR, 'plugin-src') });+ expect(captureMutationOwnerMock).toHaveBeenCalledTimes(1);+ expect(acquireMutationLeaseMock).toHaveBeenCalledTimes(1);+ expect(releaseMutationMock).not.toHaveBeenCalled();+ await operation;+ expect(releaseMutationMock).toHaveBeenCalledTimes(1);+ });++ it('passes the active session workdir into packGhostDir', async () => {+ await makeDeps().forgePack({ dir: path.join(WORKDIR, 'plugin-src') });+ expect(packGhostDirMock).toHaveBeenCalledWith(path.join(WORKDIR, 'plugin-src'), {+ sessionWorkdir: WORKDIR,+ forbiddenRootDirs: [],+ });+ });++ it('rejects remote workdirs before touching local Forge fs', async () => {+ sessionSnapshotMock.mockResolvedValueOnce({+ workingDir: '/remote/project',+ permissionMode: 'auto',+ planModeEnabled: false,+ remoteHostId: 'ssh-1',+ });+ const deps = makeDeps();+ await expect(deps.forgePack({ dir: '/remote/project/plugin-src' })).resolves.toMatchObject({+ ok: false,+ errorCode: 'WORKDIR_NOT_LOCAL',+ });+ expect(packGhostDirMock).not.toHaveBeenCalled();+ });++ it('rejects Forge writes in read-only or plan sessions', async () => {+ sessionSnapshotMock.mockResolvedValueOnce({+ workingDir: WORKDIR,+ permissionMode: 'ask',+ planModeEnabled: true,+ remoteHostId: null,+ });+ const deps = makeDeps();+ await expect(+ deps.forgeScaffold({ dir: path.join(WORKDIR, 'new-plugin'), template: 'plain', id: 'x', name: 'X' }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'WORKDIR_READ_ONLY' });+ });+});+afterAll(() => {fs.rmSync(tmpUserData, { recursive: true, force: true });});diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex beb2ce87f8..27f1d3baa4 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -55,6 +55,7 @@ import { drainGhostCallMedia } from '../cindy-brain/ghostMediaLedger.js';import {getGhostCardService,getGhostManager,+ ghostForgeForbiddenRootDirs,getGhostPipeDispatcher,getGhostSetupAssessment,acquireGhostMutationLeaseForMcp,@@ -66,6 +67,7 @@ import {import { getGhostSetupCoordinator } from '../cindy-brain/ghostSetupCoordinator.js';import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forge.js';+import { writeForgeScaffoldWithStableParent } from '../cindy-brain/forgeScaffoldCapability.js';import { workdirWriteVerdict } from '../cindy-brain/fsSlot.js';import { handleIncomingCindyFile } from '../cindy-brain/openFileInstall.js';import * as blobStore from '../cindy-media/blobStore.js';@@ -150,6 +152,60 @@ async function buildGhostSessionContext();}+type ForgeSessionFsGate =+ | { ok: true; workingDir: string }+ | {+ ok: false;+ errorCode: 'WORKDIR_NOT_LOCAL' | 'WORKDIR_READ_ONLY';+ message: string;+ };++async function withForgeOwnerLease<T>(operation: () => Promise<T>): Promise<T> {+ const owner = captureGhostMutationOwnerForMcp();+ const release = acquireGhostMutationLeaseForMcp(owner);+ try {+ return await operation();+ } finally {+ release();+ }+}++/**+ * Forge performs Host-side local filesystem writes. A raw MCP workingDir is+ * only a label; the authoritative session row decides whether it is local and+ * whether writes are currently allowed. Keep this gate next to the session+ * snapshot builder so scaffold/pack cannot silently drift into independent+ * caller-supplied path checks.+ */+async function getForgeSessionFsGate(+ sessionContext: LiziMcpSessionContext | undefined,+): Promise<ForgeSessionFsGate> {+ const sessionId = sessionContext?.sessionId ?? null;+ if (!sessionId) {+ return {+ ok: false,+ errorCode: 'WORKDIR_NOT_LOCAL',+ message: 'Forge requires an authoritative local session workdir',+ };+ }+ const snapshot = await getSessionFsSnapshot(sessionId);+ if (!snapshot?.workingDir || snapshot.remoteHostId) {+ return {+ ok: false,+ errorCode: 'WORKDIR_NOT_LOCAL',+ message: 'Forge cannot use a remote or unverified session workdir on the local host',+ };+ }+ if (workdirWriteVerdict(snapshot.permissionMode, snapshot.planModeEnabled) === 'deny') {+ return {+ ok: false,+ errorCode: 'WORKDIR_READ_ONLY',+ message: 'Forge is disabled while the current session workdir is read-only or in plan mode',+ };+ }+ return { ok: true, workingDir: snapshot.workingDir };+}+/** 意识显示名(确认卡标题用;查不到回落 id)。 */function ghostDisplayName(ghostId: string): string {const g = findAvailableGhostForAuthorization(ghostId);@@ -384,7 +440,11 @@ async function confirmDepositOutsideWorkdir(params: {lane: 'dir' | 'save_dir';dirAbs: string;workdirAbs: string | null;-}): Promise<{ ok: true; userGranted: boolean } | { ok: false; message: string }> {+}): Promise<+ | { ok: true; userGranted: false }+ | { ok: true; userGranted: true; approvedRealPath: string }+ | { ok: false; message: string }+> {if (!path.isAbsolute(params.dirAbs)) return { ok: true, userGranted: false };let real: string;let stat: fs.Stats;@@ -401,7 +461,7 @@ async function confirmDepositOutsideWorkdir(params: {params.sessionId &&dirGrantMemory.has(dirGrantMemoryKey(params.sessionId, params.ghostId, params.lane, real))) {- return { ok: true, userGranted: true };+ return { ok: true, userGranted: true, approvedRealPath: real };}let item: GhostGrantFileItem;@@ -441,7 +501,7 @@ async function confirmDepositOutsideWorkdir(params: {ghostId: params.ghostId,lane: params.lane,});- return { ok: true, userGranted: true };+ return { ok: true, userGranted: true, approvedRealPath: real };}/**@@ -889,6 +949,7 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): CindydirAbs: dir,workdirAbs: sessionWorkdir,userGranted: dirConfirm.userGranted,+ ...(dirConfirm.userGranted ? { approvedRealPath: dirConfirm.approvedRealPath } : {}),});if (!deposited.ok) {return { ok: false, errorCode: 'DIR_INVALID', message: deposited.message };@@ -914,6 +975,7 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): CindydirAbs: saveDir,workdirAbs: sessionWorkdir,userGranted: saveConfirm.userGranted,+ ...(saveConfirm.userGranted ? { approvedRealPath: saveConfirm.approvedRealPath } : {}),});if (!saveDeposited.ok) {return { ok: false, errorCode: 'DIR_INVALID', message: saveDeposited.message };@@ -1071,37 +1133,46 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindyreturn FORGE_GUIDE;},async forgeScaffold(request): Promise<CindyForgeScaffoldResult> {- const sessionWorkdir = resolveSessionContext()?.workingDir ?? null;- const result = await scaffoldGhostDir(request, {- sessionWorkdir,- forbiddenRootDirs: getGhostManager().managedRootDirs(),- });- if (result.ok) {- log.info('ghost forge scaffold created', {- dir: result.dir,- template: result.template,- files: result.files,+ return withForgeOwnerLease(async () => {+ const gate = await getForgeSessionFsGate(resolveSessionContext());+ if (!gate.ok) return gate;+ const result = await scaffoldGhostDir(request, {+ sessionWorkdir: gate.workingDir,+ forbiddenRootDirs: ghostForgeForbiddenRootDirs(),+ writeScaffold: writeForgeScaffoldWithStableParent,});- }- return result;+ if (result.ok) {+ log.info('ghost forge scaffold created', {+ dir: result.dir,+ template: result.template,+ files: result.files,+ });+ }+ return result;+ });},async forgePack({ dir }): Promise<CindyForgePackResult> {- const packed = await packGhostDir(dir, {- forbiddenRootDirs: getGhostManager().managedRootDirs(),+ return withForgeOwnerLease(async () => {+ const gate = await getForgeSessionFsGate(resolveSessionContext());+ if (!gate.ok) return gate;+ const packed = await packGhostDir(dir, {+ sessionWorkdir: gate.workingDir,+ forbiddenRootDirs: ghostForgeForbiddenRootDirs(),+ });+ if (!packed.ok) return packed;+ // 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则+ // 自动转"更新 vX → vY"),用户点头才真装。+ await handleIncomingCindyFile(packed.cindyPath, 'ghost-forge');+ log.info('ghost forge packed', { dir, cindyPath: packed.cindyPath, id: packed.manifest.id });+ return {+ ok: true,+ cindyPath: packed.cindyPath,+ id: packed.manifest.id,+ name: packed.manifest.name,+ version: packed.manifest.version,+ note: '已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。',+ };});- if (!packed.ok) return packed;- // 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则- // 自动转"更新 vX → vY"),用户点头才真装。- await handleIncomingCindyFile(packed.cindyPath, 'ghost-forge');- log.info('ghost forge packed', { dir, cindyPath: packed.cindyPath, id: packed.manifest.id });- return {- ok: true,- cindyPath: packed.cindyPath,- id: packed.manifest.id,- name: packed.manifest.name,- version: packed.manifest.version,- note: '已打包并弹出装入/更新确认框,请告知用户在应用内确认(装入默认沉睡)。',- };},logger: log,};diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.tsindex 482c283990..89e0ba48da 100644--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@ -1,4 +1,5 @@import { app } from 'electron';+import { randomUUID } from 'node:crypto';import fsSync from 'node:fs';import fs from 'node:fs/promises';import path from 'node:path';@@ -8,6 +9,7 @@ import { createLogger } from './logger.js';import {GHOST_MANIFEST_FILE,isOfficialGhostId,+ isValidGhostId,validateGhostManifest,} from '../shared/ghost.js';import {@@ -16,6 +18,7 @@ import {} from '../shared/legacyGhostRecovery.js';const CLAIM_MARKER = '.owner-namespace-claim-v1.json';+const LEGACY_GHOST_RECOVERY_MARKER = '.legacy-ghost-recovery-v1.json';const BUILTIN_PROVISIONING_STATE_FILE = '.builtin-provisioning.json';const LEGACY_PATHS = ['ghost-kv',@@ -54,12 +57,30 @@ interface ClaimMarker {complete: boolean;}+interface LegacyGhostRecoveryMarker {+ version: 1;+ ownerKey: string;+ pendingIds: string[];+ /** Deterministic content failures remain inside the frozen id whitelist. */+ failedIds?: string[];+}++type LegacyGhostRecoveryMarkerRead =+ | { kind: 'ready'; marker: LegacyGhostRecoveryMarker }+ | { kind: 'missing' }+ | { kind: 'deferred' }+ | { kind: 'invalid' };+interface MigrationDeps {userDataDir(): string;readFile(file: string): Promise<string>;writeFileExclusive(file: string, text: string): Promise<void>;writeFile(file: string, text: string): Promise<void>;- lstat(file: string): Promise<{ isDirectory(): boolean }>;+ lstat(file: string): Promise<{+ isDirectory(): boolean;+ isFile?: () => boolean;+ isSymbolicLink?: () => boolean;+ }>;readdir(dir: string): Promise<string[]>;mkdir(dir: string): Promise<void>;rename(source: string, target: string): Promise<void>;@@ -74,7 +95,8 @@ interface MigrationDeps {/** claim 被推迟(而非放弃)的原因;下次独占启动时自然重试完成。 */export type OwnerNamespaceClaimDeferredReason =| 'passive-shared-user-data'- | 'concurrent-live-instances';+ | 'concurrent-live-instances'+ | 'legacy-discovery-incomplete';export interface OwnerNamespaceMigrationResult {status: 'skipped' | 'deferred' | 'claimed-by-other-owner' | 'migrated' | 'partial';@@ -82,6 +104,8 @@ export interface OwnerNamespaceMigrationResult {conflicts: number;provisioningStateMoved?: boolean;deferredReason?: OwnerNamespaceClaimDeferredReason;+ /** Ghost directories moved before approval backfill; durable across restart. */+ recoveredIds?: string[];}const log = createLogger('ownerNamespaceMigration');@@ -145,6 +169,60 @@ async function readMarker(deps: MigrationDeps, markerPath: string): Promise<Clai}}+async function readLegacyGhostRecoveryMarker(+ deps: MigrationDeps,+ markerPath: string,+): Promise<LegacyGhostRecoveryMarkerRead> {+ let text: string;+ try {+ text = await deps.readFile(markerPath);+ } catch (error) {+ return isMissing(error) ? { kind: 'missing' } : { kind: 'deferred' };+ }+ try {+ const parsed = JSON.parse(text) as Partial<LegacyGhostRecoveryMarker>;+ const failedIds = parsed.failedIds ?? [];+ if (+ parsed.version === 1 &&+ typeof parsed.ownerKey === 'string' &&+ Array.isArray(parsed.pendingIds) &&+ parsed.pendingIds.every((id) => typeof id === 'string' && isValidGhostId(id)) &&+ Array.isArray(failedIds) &&+ failedIds.every((id) => typeof id === 'string' && isValidGhostId(id)) &&+ failedIds.every((id) => parsed.pendingIds?.includes(id))+ ) {+ const marker: LegacyGhostRecoveryMarker = {+ version: 1,+ ownerKey: parsed.ownerKey,+ pendingIds: [...new Set(parsed.pendingIds)],+ ...(failedIds.length > 0 ? { failedIds: [...new Set(failedIds)] } : {}),+ };+ return { kind: 'ready', marker };+ }+ return { kind: 'invalid' };+ } catch {+ return { kind: 'invalid' };+ }+}++async function writeLegacyGhostRecoveryMarker(+ deps: MigrationDeps,+ markerPath: string,+ marker: LegacyGhostRecoveryMarker,+): Promise<void> {+ await writeJsonAtomically(deps, markerPath, marker);+}++async function writeJsonAtomically(+ deps: MigrationDeps,+ targetPath: string,+ value: unknown,+): Promise<void> {+ const tempPath = `${targetPath}.${randomUUID()}.tmp`;+ await deps.writeFile(tempPath, JSON.stringify(value));+ await deps.rename(tempPath, targetPath);+}+function isPidAliveDefault(pid: number): boolean {try {process.kill(pid, 0);@@ -284,21 +362,62 @@ interface LegacyGhostDir {id: string;dir: string;command: string | null;+ rootStats: fsSync.Stats;+ dirStats: fsSync.Stats;+ rootRealPath: string;+ dirRealPath: string;+}++interface LegacyGhostDiscovery {+ ghosts: LegacyGhostDir[];+ deferredRoots: string[];+ deferredIds: string[];+ invalidIds: string[];+}++type LegacyGhostManifestRead =+ | { kind: 'ready'; command: string | null }+ | { kind: 'deferred' }+ | { kind: 'invalid' };++function sameLegacyDirectoryIdentity(expected: fsSync.Stats, current: fsSync.Stats): boolean {+ if (!current.isDirectory() || current.isSymbolicLink()) return false;+ if (expected.dev !== 0 || expected.ino !== 0 || current.dev !== 0 || current.ino !== 0) {+ return expected.dev === current.dev && expected.ino === current.ino;+ }+ return expected.birthtimeMs === current.birthtimeMs && expected.ctimeMs === current.ctimeMs;+}++function sameLegacyCanonicalPath(left: string, right: string): boolean {+ const fold = (value: string) => process.platform === 'win32' ? value.toLowerCase() : value;+ return fold(path.resolve(left)) === fold(path.resolve(right));}-function readValidLegacyGhostDir(+function isLegacyPathInside(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate);+ return relative.length > 0 && !path.isAbsolute(relative) &&+ relative !== '..' && !relative.startsWith(`..${path.sep}`);+}++function readLegacyGhostManifest(dir: string,expectedId: string,-): Pick<LegacyGhostDir, 'command'> | null {+): LegacyGhostManifestRead {+ let text: string;+ try {+ text = fsSync.readFileSync(path.join(dir, GHOST_MANIFEST_FILE), 'utf-8');+ } catch (error) {+ return isMissing(error) ? { kind: 'invalid' } : { kind: 'deferred' };+ }let raw: unknown;try {- raw = JSON.parse(fsSync.readFileSync(path.join(dir, GHOST_MANIFEST_FILE), 'utf-8'));+ raw = JSON.parse(text);} catch {- return null;+ return { kind: 'invalid' };}const parsed = validateGhostManifest(raw);- if (!parsed.ok || parsed.manifest.id !== expectedId) return null;- return { command: parsed.manifest.command ?? null };+ if (!parsed.ok || parsed.manifest.id !== expectedId) return { kind: 'invalid' };+ return { kind: 'ready', command: parsed.manifest.command ?? null };}function pathExistsNoFollowSync(@@ -333,21 +452,71 @@ function ownerScopedLegacyGhostRootDir(userDataDir: string, ownerKey: string): sreturn path.join(userDataDir, 'owners', ownerKey, 'brain');}-function listLegacyGhostDirsInRoots(+/** All legacy/content and approval projection roots that must be revoked at an owner boundary. */+export function listLegacyOwnerProjectionRoots(userDataDir: string): string[] {+ const ownersRoot = path.join(userDataDir, 'owners');+ const roots = [+ ...sharedLegacyGhostRootDirs(userDataDir),+ ];+ let entries: fsSync.Dirent[];+ try {+ entries = fsSync.readdirSync(ownersRoot, { withFileTypes: true });+ } catch (error) {+ if (isMissing(error)) return roots;+ throw error;+ }+ for (const entry of entries) {+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;+ const ownerRoot = path.join(ownersRoot, entry.name);+ roots.push(+ path.join(ownerRoot, 'brain'),+ path.join(ownerRoot, 'cindy-brain'),+ path.join(ownerRoot, 'ghost-install-state'),+ );+ }+ return roots;+}++function scanLegacyGhostDirsInRoots(roots: string[],-): LegacyGhostDir[] {- const result: LegacyGhostDir[] = [];+): LegacyGhostDiscovery {+ const result: LegacyGhostDiscovery = {+ ghosts: [],+ deferredRoots: [],+ deferredIds: [],+ invalidIds: [],+ };for (const root of roots) {+ let rootStats: fsSync.Stats;+ let rootRealPath: string;try {- const stats = fsSync.lstatSync(root);- if (!stats.isDirectory() || stats.isSymbolicLink()) continue;- } catch {+ rootStats = fsSync.lstatSync(root);+ if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) {+ result.invalidIds.push(root);+ continue;+ }+ rootRealPath = fsSync.realpathSync.native(root);+ } catch (error) {+ if (!isMissing(error)) result.deferredRoots.push(root);continue;}let entries: fsSync.Dirent[];try {entries = fsSync.readdirSync(root, { withFileTypes: true });+ } catch (error) {+ if (!isMissing(error)) result.deferredRoots.push(root);+ continue;+ }+ try {+ const rootAfterRead = fsSync.lstatSync(root);+ const rootRealAfterRead = fsSync.realpathSync.native(root);+ if (!sameLegacyDirectoryIdentity(rootStats, rootAfterRead) ||+ !sameLegacyCanonicalPath(rootRealPath, rootRealAfterRead)) {+ result.deferredRoots.push(root);+ continue;+ }} catch {+ result.deferredRoots.push(root);continue;}for (const entry of entries) {@@ -356,17 +525,84 @@ function listLegacyGhostDirsInRoots(let dirStats: fsSync.Stats;try {dirStats = fsSync.lstatSync(dir);- } catch {+ } catch (error) {+ if (!isMissing(error)) result.deferredIds.push(entry.name);+ continue;+ }+ if (!dirStats.isDirectory() || dirStats.isSymbolicLink()) {+ result.invalidIds.push(entry.name);continue;}- if (!dirStats.isDirectory() || dirStats.isSymbolicLink()) continue;- const valid = readValidLegacyGhostDir(dir, entry.name);- if (valid) result.push({ root, id: entry.name, dir, command: valid.command });+ let dirRealPath: string;+ try {+ dirRealPath = fsSync.realpathSync.native(dir);+ if (!isLegacyPathInside(rootRealPath, dirRealPath)) {+ result.invalidIds.push(entry.name);+ continue;+ }+ } catch (error) {+ if (!isMissing(error)) result.deferredIds.push(entry.name);+ continue;+ }+ const manifest = readLegacyGhostManifest(dir, entry.name);+ if (manifest.kind === 'deferred') {+ result.deferredIds.push(entry.name);+ } else if (manifest.kind === 'invalid') {+ result.invalidIds.push(entry.name);+ } else {+ try {+ const rootAfterManifest = fsSync.lstatSync(root);+ const dirAfterManifest = fsSync.lstatSync(dir);+ const rootRealAfterManifest = fsSync.realpathSync.native(root);+ const dirRealAfterManifest = fsSync.realpathSync.native(dir);+ if (!sameLegacyDirectoryIdentity(rootStats, rootAfterManifest) ||+ !sameLegacyDirectoryIdentity(dirStats, dirAfterManifest) ||+ !sameLegacyCanonicalPath(rootRealPath, rootRealAfterManifest) ||+ !sameLegacyCanonicalPath(dirRealPath, dirRealAfterManifest) ||+ !isLegacyPathInside(rootRealAfterManifest, dirRealAfterManifest)) {+ result.deferredIds.push(entry.name);+ continue;+ }+ } catch {+ result.deferredIds.push(entry.name);+ continue;+ }+ result.ghosts.push({+ root,+ id: entry.name,+ dir,+ command: manifest.command,+ rootStats,+ dirStats,+ rootRealPath,+ dirRealPath,+ });+ }}}return result;}+function listLegacyGhostDirsInRoots(roots: string[]): LegacyGhostDir[] {+ return scanLegacyGhostDirsInRoots(roots).ghosts;+}++function hasStableLegacyGhostSourceSync(legacy: LegacyGhostDir): boolean {+ try {+ const currentRoot = fsSync.lstatSync(legacy.root);+ const currentDir = fsSync.lstatSync(legacy.dir);+ const currentRootReal = fsSync.realpathSync.native(legacy.root);+ const currentDirReal = fsSync.realpathSync.native(legacy.dir);+ return sameLegacyDirectoryIdentity(legacy.rootStats, currentRoot) &&+ sameLegacyDirectoryIdentity(legacy.dirStats, currentDir) &&+ sameLegacyCanonicalPath(legacy.rootRealPath, currentRootReal) &&+ sameLegacyCanonicalPath(legacy.dirRealPath, currentDirReal) &&+ isLegacyPathInside(currentRootReal, currentDirReal);+ } catch {+ return false;+ }+}+function listSharedLegacyGhostDirs(userDataDir: string,): LegacyGhostDir[] {@@ -418,8 +654,20 @@ export function listLegacyGhostTombstoneRoots(): string[] {const ownerKey = dataOwnerStorageKey(ownerId);const targetRoot = path.join(userDataDir, 'owners', ownerKey, 'cindy-brain');- const sharedLegacyGhosts = listSharedLegacyGhostDirs(userDataDir);- const scopedLegacyGhosts = listOwnerScopedLegacyGhostDirs(userDataDir, ownerKey);+ const sharedDiscovery = scanLegacyGhostDirsInRoots(sharedLegacyGhostRootDirs(userDataDir));+ const scopedDiscovery = scanLegacyGhostDirsInRoots([+ ownerScopedLegacyGhostRootDir(userDataDir, ownerKey),+ ]);+ if (+ sharedDiscovery.deferredRoots.length > 0 ||+ sharedDiscovery.deferredIds.length > 0 ||+ scopedDiscovery.deferredRoots.length > 0 ||+ scopedDiscovery.deferredIds.length > 0+ ) {+ return [];+ }+ const sharedLegacyGhosts = sharedDiscovery.ghosts;+ const scopedLegacyGhosts = scopedDiscovery.ghosts;const markerRead = readMarkerSync(userDataDir);const sharedRecoveryBlocked =sharedLegacyGhosts.length > 0 &&@@ -493,15 +741,99 @@ export function getLegacyGhostRecoveryStatus(const root = userDataDir ?? app.getPath('userData');const ownerKey = dataOwnerStorageKey(session.dataOwnerId);- const sharedLegacyGhosts = listSharedLegacyGhostDirs(root);- const scopedLegacyGhosts = listOwnerScopedLegacyGhostDirs(root, ownerKey);+ const sharedDiscovery = scanLegacyGhostDirsInRoots(sharedLegacyGhostRootDirs(root));+ const scopedDiscovery = scanLegacyGhostDirsInRoots([+ ownerScopedLegacyGhostRootDir(root, ownerKey),+ ]);+ const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');+ const targetDiscovery = scanLegacyGhostDirsInRoots([targetRoot]);+ const sharedLegacyGhosts = sharedDiscovery.ghosts;+ const scopedLegacyGhosts = scopedDiscovery.ghosts;const legacyGhosts = [...sharedLegacyGhosts, ...scopedLegacyGhosts];- const legacyPluginCount = legacyGhosts.length;+ const recoveryMarkerRead = readLegacyGhostRecoveryMarkerSync(root, ownerKey);+ const recoveryMarker = recoveryMarkerRead.kind === 'ready'+ ? recoveryMarkerRead.marker+ : null;+ const sourceDiscoveryProblemIds = new Set([+ ...sharedDiscovery.deferredIds,+ ...sharedDiscovery.invalidIds,+ ...scopedDiscovery.deferredIds,+ ...scopedDiscovery.invalidIds,+ ]);+ const targetInvalidIds = new Set(+ targetDiscovery.invalidIds.filter((id) => recoveryMarker?.pendingIds.includes(id)),+ );+ const discoveryDeferred =+ sharedDiscovery.deferredRoots.length > 0 ||+ sharedDiscovery.deferredIds.length > 0 ||+ scopedDiscovery.deferredRoots.length > 0 ||+ scopedDiscovery.deferredIds.length > 0 ||+ targetDiscovery.deferredRoots.length > 0 ||+ targetDiscovery.deferredIds.length > 0;+ const discoveryHasInvalid =+ sourceDiscoveryProblemIds.size > 0 || targetDiscovery.invalidIds.length > 0;+ const installedTargetIds = new Set(targetDiscovery.ghosts.map((ghost) => ghost.id));+ const legacySourceIds = new Set(legacyGhosts.map((ghost) => ghost.id));+ const knownDiscoveryIds = new Set([+ ...legacySourceIds,+ ...sourceDiscoveryProblemIds,+ ...targetInvalidIds,+ ...(recoveryMarker?.pendingIds ?? []),+ ]);+ const deferredRootCount =+ sharedDiscovery.deferredRoots.length ++ scopedDiscovery.deferredRoots.length ++ targetDiscovery.deferredRoots.length;+ const knownDiscoveryCount = knownDiscoveryIds.size + deferredRootCount;+ if (recoveryMarkerRead.kind === 'invalid') {+ return {+ state: 'partial',+ legacyPluginCount: Math.max(1, knownDiscoveryCount),+ canRetry: false,+ };+ }+ if (recoveryMarkerRead.kind === 'deferred' || discoveryDeferred) {+ return {+ state: 'deferred',+ legacyPluginCount: Math.max(1, knownDiscoveryCount),+ canRetry: process.env.XDT_PASSIVE_SHARED_USER_DATA !== '1',+ deferredReason: 'legacy-discovery-incomplete',+ };+ }+ const recoveredIds = (recoveryMarker?.pendingIds ?? []).filter(+ (id) => installedTargetIds.has(id) && !legacySourceIds.has(id),+ );+ const unexpectedFrozenIds = recoveryMarker+ ? legacyGhosts.map((ghost) => ghost.id).filter((id) => !recoveryMarker.pendingIds.includes(id))+ : [];+ const legacyPluginCount = new Set([+ ...legacyGhosts.map((ghost) => ghost.id),+ ...sourceDiscoveryProblemIds,+ ...targetInvalidIds,+ ...recoveredIds,+ ...(recoveryMarker?.pendingIds ?? []),+ ]).size;+ if (discoveryHasInvalid && targetDiscovery.invalidIds.length > 0) {+ return { state: 'partial', legacyPluginCount: Math.max(1, legacyPluginCount), canRetry: false };+ }if (legacyPluginCount === 0) return NO_LEGACY_GHOST_RECOVERY;if (process.env.XDT_PASSIVE_SHARED_USER_DATA === '1') {return { state: 'deferred', legacyPluginCount, canRetry: false };}+ if (recoveredIds.length > 0) {+ if (hasConcurrentLiveInstanceSync(root, isPidAlive)) {+ return { state: 'deferred', legacyPluginCount, canRetry: false };+ }+ return { state: 'partial', legacyPluginCount, canRetry: true };+ }+ if (unexpectedFrozenIds.length > 0) {+ return { state: 'partial', legacyPluginCount, canRetry: false };+ }++ if (discoveryHasInvalid && legacyGhosts.length === 0) {+ return { state: 'partial', legacyPluginCount, canRetry: false };+ }const markerRead = readMarkerSync(root);const sharedRecoveryBlocked =sharedLegacyGhosts.length > 0 &&@@ -517,13 +849,13 @@ export function getLegacyGhostRecoveryStatus(return { state: 'deferred', legacyPluginCount, canRetry: false };}- const eligibleLegacyGhosts = sharedRecoveryBlocked ? scopedLegacyGhosts : legacyGhosts;- const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');+ const eligibleLegacyGhosts = (sharedRecoveryBlocked ? scopedLegacyGhosts : legacyGhosts)+ .filter((ghost) => !recoveryMarker || recoveryMarker.pendingIds.includes(ghost.id));if (!hasSafeRecoveryTargetChainSync(root, targetRoot)) {return { state: 'partial', legacyPluginCount, canRetry: false };}const occupiedCommands = new Set(- listLegacyGhostDirsInRoots([targetRoot])+ targetDiscovery.ghosts.map((legacy) => legacy.command?.toLowerCase() ?? null).filter((command): command is string => command !== null),);@@ -577,8 +909,41 @@ export async function recoverLegacyGhostPlugins(const userDataDir = deps.userDataDir();const ownerKey = dataOwnerStorageKey(ownerId);const markerPath = path.join(userDataDir, CLAIM_MARKER);- const sharedLegacyGhosts = listSharedLegacyGhostDirs(userDataDir);- const scopedLegacyGhosts = listOwnerScopedLegacyGhostDirs(userDataDir, ownerKey);+ const recoveryMarkerPath = path.join(+ userDataDir,+ 'owners',+ ownerKey,+ LEGACY_GHOST_RECOVERY_MARKER,+ );+ const sharedDiscovery = scanLegacyGhostDirsInRoots(sharedLegacyGhostRootDirs(userDataDir));+ const scopedDiscovery = scanLegacyGhostDirsInRoots([+ ownerScopedLegacyGhostRootDir(userDataDir, ownerKey),+ ]);+ const targetRoot = path.join(userDataDir, 'owners', ownerKey, 'cindy-brain');+ const targetDiscovery = scanLegacyGhostDirsInRoots([targetRoot]);+ const sharedLegacyGhosts = sharedDiscovery.ghosts;+ const scopedLegacyGhosts = scopedDiscovery.ghosts;+ const discoveryDeferred =+ sharedDiscovery.deferredRoots.length > 0 ||+ sharedDiscovery.deferredIds.length > 0 ||+ scopedDiscovery.deferredRoots.length > 0 ||+ scopedDiscovery.deferredIds.length > 0 ||+ targetDiscovery.deferredRoots.length > 0 ||+ targetDiscovery.deferredIds.length > 0;+ const discoveryInvalidCount = new Set([+ ...sharedDiscovery.invalidIds,+ ...scopedDiscovery.invalidIds,+ ]).size;+ if (discoveryDeferred) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'deferred',+ moved: 0,+ conflicts: discoveryInvalidCount,+ deferredReason: 'legacy-discovery-incomplete',+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }let marker: ClaimMarker | null = null;let eligibleSharedGhosts = sharedLegacyGhosts;let sharedRecoveryBlocked = false;@@ -597,6 +962,66 @@ export async function recoverLegacyGhostPlugins(});}}+ const recoveryMarkerRead = await readLegacyGhostRecoveryMarker(deps, recoveryMarkerPath);+ if (recoveryMarkerRead.kind === 'deferred') {+ log.warn('legacy ghost recovery deferred: durable recovery marker temporarily unreadable');+ const result: OwnerNamespaceMigrationResult = {+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'legacy-discovery-incomplete',+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ if (recoveryMarkerRead.kind === 'invalid') {+ log.warn('legacy ghost recovery blocked: durable recovery marker is invalid');+ const result: OwnerNamespaceMigrationResult = {+ status: 'partial',+ moved: 0,+ conflicts: sharedLegacyGhosts.length + scopedLegacyGhosts.length,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ const recoveryMarker = recoveryMarkerRead.kind === 'ready'+ ? recoveryMarkerRead.marker+ : null;+ let recoveryMarkerPersisted = recoveryMarker !== null;+ if (recoveryMarker && recoveryMarker.ownerKey !== ownerKey) {+ log.warn('legacy ghost recovery blocked: durable recovery marker owner mismatch', {+ expectedOwnerKey: ownerKey,+ actualOwnerKey: recoveryMarker.ownerKey,+ });+ const result: OwnerNamespaceMigrationResult = {+ status: 'partial',+ moved: 0,+ conflicts: sharedLegacyGhosts.length + scopedLegacyGhosts.length,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ const sourceDiscoveryIds = new Set([+ ...sharedLegacyGhosts.map((ghost) => ghost.id),+ ...scopedLegacyGhosts.map((ghost) => ghost.id),+ ...[...sharedDiscovery.invalidIds, ...scopedDiscovery.invalidIds]+ .filter((id) => isValidGhostId(id)),+ ]);+ const targetDiscoveryIds = new Set(targetDiscovery.ghosts.map((ghost) => ghost.id));+ const pendingRecoveryIds = new Set(recoveryMarker?.pendingIds ?? sourceDiscoveryIds);+ const failedRecoveryIds = new Set(+ recoveryMarker?.failedIds ??+ [...sourceDiscoveryIds].filter((id) =>+ [...sharedDiscovery.invalidIds, ...scopedDiscovery.invalidIds].includes(id),+ ),+ );+ for (const id of [...sharedDiscovery.invalidIds, ...scopedDiscovery.invalidIds]) {+ if (isValidGhostId(id) && pendingRecoveryIds.has(id)) failedRecoveryIds.add(id);+ }+ const movedThisRun = new Set<string>();+ const recoveredTargetIds = (): string[] => [...pendingRecoveryIds]+ .filter((id) => movedThisRun.has(id) || (targetDiscoveryIds.has(id) && !sourceDiscoveryIds.has(id)))+ .sort();if (sharedRecoveryBlocked &&scopedLegacyGhosts.length === 0 &&@@ -611,26 +1036,59 @@ export async function recoverLegacyGhostPlugins(recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;}-- const targetRoot = path.join(userDataDir, 'owners', ownerKey, 'cindy-brain');let movableLegacyGhosts: ReturnType<typeof listLegacyGhostDirs> = [];- let conflicts = sharedRecoveryBlocked ? sharedLegacyGhosts.length : 0;+ const unexpectedFrozenIds = recoveryMarker+ ? [...sourceDiscoveryIds].filter((id) => !pendingRecoveryIds.has(id))+ : [];+ let conflicts = (sharedRecoveryBlocked ? sharedLegacyGhosts.length : 0) ++ discoveryInvalidCount + unexpectedFrozenIds.length;+ const movableById = new Map<string, ReturnType<typeof listLegacyGhostDirs>>();for (const legacy of [...eligibleSharedGhosts, ...scopedLegacyGhosts]) {+ if (recoveryMarker && !pendingRecoveryIds.has(legacy.id)) {+ continue;+ }+ if (failedRecoveryIds.has(legacy.id)) {+ // A formerly invalid id may be retried after its manifest is repaired,+ // but it remains inside the original frozen whitelist.+ failedRecoveryIds.delete(legacy.id);+ }if (options.rejectReservedIds && isOfficialGhostId(legacy.id)) {conflicts += 1;continue;}if ((await pathType(deps, path.join(targetRoot, legacy.id))) === 'missing') {- movableLegacyGhosts.push(legacy);+ const siblings = movableById.get(legacy.id) ?? [];+ siblings.push(legacy);+ movableById.set(legacy.id, siblings);} else {conflicts += 1;}}+ for (const siblings of movableById.values()) {+ if (siblings.length === 1) {+ movableLegacyGhosts.push(siblings[0]);+ } else {+ // Same id in multiple legacy roots is ambiguous legacy state. Do not+ // move one copy and leave the other behind: that would create a target+ // which can never be safely backfilled or retried.+ conflicts += siblings.length;+ }+ }+ const activePendingIds = new Set([+ ...pendingRecoveryIds,+ ].filter((id) => sourceDiscoveryIds.has(id) || recoveredTargetIds().includes(id)));+ if (activePendingIds.size > 0) {+ movableLegacyGhosts = movableLegacyGhosts.filter((legacy) =>+ activePendingIds.has(legacy.id),+ );+ }if (movableLegacyGhosts.length === 0) {+ const recoveredIds = recoveredTargetIds();const result: OwnerNamespaceMigrationResult = {- status: conflicts > 0 ? 'partial' : 'skipped',+ status: conflicts > 0 || recoveredIds.length > 0 ? 'partial' : 'skipped',moved: 0,conflicts,+ ...(recoveredIds.length > 0 ? { recoveredIds } : {}),};recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;@@ -672,6 +1130,19 @@ export async function recoverLegacyGhostPlugins(return result;}+ // Freeze the recovery whitelist only after passive/concurrent ownership has+ // been ruled out. A deferred instance must not write durable recovery state.+ if (!recoveryMarkerPersisted && pendingRecoveryIds.size > 0 && !sharedRecoveryBlocked) {+ await deps.mkdir(path.dirname(recoveryMarkerPath));+ await writeLegacyGhostRecoveryMarker(deps, recoveryMarkerPath, {+ version: 1,+ ownerKey,+ pendingIds: [...pendingRecoveryIds].sort(),+ ...(failedRecoveryIds.size > 0 ? { failedIds: [...failedRecoveryIds].sort() } : {}),+ });+ recoveryMarkerPersisted = true;+ }+if (options.shouldAbort?.()) return { status: 'deferred', moved: 0, conflicts: 0 };await deps.mkdir(userDataDir);const sharedDirs = new Set(sharedLegacyGhosts.map((legacy) => legacy.dir));@@ -705,16 +1176,18 @@ export async function recoverLegacyGhostPlugins();}if (movableLegacyGhosts.length === 0) {+ const recoveredIds = recoveredTargetIds();const result: OwnerNamespaceMigrationResult = {- status: conflicts > 0 ? 'partial' : 'skipped',+ status: conflicts > 0 || recoveredIds.length > 0 ? 'partial' : 'skipped',moved: 0,conflicts,+ ...(recoveredIds.length > 0 ? { recoveredIds } : {}),};recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;}const occupiedCommands = new Set(- listLegacyGhostDirsInRoots([targetRoot])+ targetDiscovery.ghosts.map((legacy) => legacy.command?.toLowerCase() ?? null).filter((command): command is string => command !== null),);@@ -733,10 +1206,12 @@ export async function recoverLegacyGhostPlugins(}movableLegacyGhosts = commandSafeLegacyGhosts;if (movableLegacyGhosts.length === 0) {+ const recoveredIds = recoveredTargetIds();const result: OwnerNamespaceMigrationResult = {- status: conflicts > 0 ? 'partial' : 'skipped',+ status: conflicts > 0 || recoveredIds.length > 0 ? 'partial' : 'skipped',moved: 0,conflicts,+ ...(recoveredIds.length > 0 ? { recoveredIds } : {}),};recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;@@ -769,6 +1244,26 @@ export async function recoverLegacyGhostPlugins(}}}+ if (pendingRecoveryIds.size > 0) {+ if (!hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'partial',+ moved: 0,+ conflicts: conflicts + movableLegacyGhosts.length,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ await deps.mkdir(path.dirname(recoveryMarkerPath));+ const nextRecoveryMarker: LegacyGhostRecoveryMarker = {+ version: 1,+ ownerKey,+ pendingIds: [...pendingRecoveryIds].sort(),+ ...(failedRecoveryIds.size > 0 ? { failedIds: [...failedRecoveryIds].sort() } : {}),+ };+ await writeLegacyGhostRecoveryMarker(deps, recoveryMarkerPath, nextRecoveryMarker);+ recoveryMarkerPersisted = true;+ }const targetRootWasMissing = (await pathType(deps, targetRoot)) === 'missing';await deps.mkdir(targetRoot);if (!hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {@@ -919,9 +1414,18 @@ export async function recoverLegacyGhostPlugins(});break;}+ if (!hasStableLegacyGhostSourceSync(legacy)) {+ failed = true;+ conflicts += 1;+ log.warn('legacy ghost recovery refused source whose root or directory changed', {+ id: legacy.id,+ });+ continue;+ }try {await deps.rename(legacy.dir, target);moved += 1;+ movedThisRun.add(legacy.id);} catch (error) {failed = true;if ((error as NodeJS.ErrnoException).code === 'EEXIST') {@@ -990,6 +1494,7 @@ export async function recoverLegacyGhostPlugins(}}}+ const recoveredIds = recoveredTargetIds();const result: OwnerNamespaceMigrationResult = {status: failed || conflicts > 0 ? 'partial' : 'migrated',moved,@@ -998,17 +1503,107 @@ export async function recoverLegacyGhostPlugins(...(concurrentRecoveryInterrupted? { deferredReason: 'concurrent-live-instances' as const }: {}),+ ...(recoveredIds.length > 0 ? { recoveredIds } : {}),};recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;}+function readLegacyGhostRecoveryMarkerSync(+ userDataDir: string,+ ownerKey: string,+): LegacyGhostRecoveryMarkerRead {+ let text: string;+ try {+ text = fsSync.readFileSync(+ path.join(+ userDataDir,+ 'owners',+ ownerKey,+ LEGACY_GHOST_RECOVERY_MARKER,+ ),+ 'utf-8',+ );+ } catch (error) {+ return isMissing(error) ? { kind: 'missing' } : { kind: 'deferred' };+ }+ try {+ const parsed = JSON.parse(text) as Partial<LegacyGhostRecoveryMarker>;+ const failedIds = parsed.failedIds ?? [];+ if (+ parsed.version === 1 &&+ parsed.ownerKey === ownerKey &&+ Array.isArray(parsed.pendingIds) &&+ parsed.pendingIds.every((id) => typeof id === 'string' && isValidGhostId(id)) &&+ Array.isArray(failedIds) &&+ failedIds.every((id) => typeof id === 'string' && isValidGhostId(id)) &&+ failedIds.every((id) => parsed.pendingIds?.includes(id))+ ) {+ return { kind: 'ready', marker: {+ version: 1,+ ownerKey,+ pendingIds: [...new Set(parsed.pendingIds)],+ ...(failedIds.length > 0 ? { failedIds: [...new Set(failedIds)] } : {}),+ } };+ }+ return { kind: 'invalid' };+ } catch {+ return { kind: 'invalid' };+ }+}++/**+ * Acknowledge only Ghost ids whose approval backfill finished. Keeping the+ * marker until this point closes the rename -> receipt crash window.+ */+export async function acknowledgeRecoveredLegacyGhosts(+ ownerId: string,+ ids: readonly string[],+ deps: MigrationDeps = productionDeps,+): Promise<void> {+ if (ids.length === 0) return;+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(+ deps.userDataDir(),+ 'owners',+ ownerKey,+ LEGACY_GHOST_RECOVERY_MARKER,+ );+ const markerRead = await readLegacyGhostRecoveryMarker(deps, markerPath);+ if (markerRead.kind === 'missing') return;+ if (markerRead.kind === 'deferred') {+ throw new Error('legacy ghost recovery marker temporarily unreadable');+ }+ if (markerRead.kind === 'invalid') {+ throw new Error('invalid legacy ghost recovery marker');+ }+ const marker = markerRead.marker;+ if (marker.ownerKey !== ownerKey) {+ throw new Error('legacy ghost recovery marker owner mismatch');+ }+ const acknowledged = new Set(ids);+ const pendingIds = marker.pendingIds.filter((id) => !acknowledged.has(id));+ if (pendingIds.length === marker.pendingIds.length) return;+ await writeLegacyGhostRecoveryMarker(deps, markerPath, {+ version: 1,+ ownerKey,+ pendingIds,+ ...(marker.failedIds?.length+ ? { failedIds: marker.failedIds.filter((id) => !acknowledged.has(id)) }+ : {}),+ });+}+async function pathType(deps: MigrationDeps,file: string,-): Promise<'missing' | 'directory' | 'other'> {+): Promise<'missing' | 'directory' | 'file' | 'link' | 'other'> {try {- return (await deps.lstat(file)).isDirectory() ? 'directory' : 'other';+ const stat = await deps.lstat(file);+ if (stat.isSymbolicLink?.()) return 'link';+ if (stat.isDirectory()) return 'directory';+ if (stat.isFile?.()) return 'file';+ return 'other';} catch (error) {if (isMissing(error)) return 'missing';throw error;@@ -1038,13 +1633,21 @@ async function moveWithoutOverwrite(source: string,target: string,abortCheck?: () => Promise<void>,+ assertTargetChain?: () => void,): Promise<{ moved: number; conflicts: number }> {const sourceType = await pathType(deps, source);if (sourceType === 'missing') return { moved: 0, conflicts: 0 };+ // Legacy links and special files are not migratable data. Do not rename+ // them into the owner namespace where later consumers could follow them.+ if (sourceType === 'link' || sourceType === 'other') {+ return { moved: 0, conflicts: 1 };+ }const targetType = await pathType(deps, target);if (targetType === 'missing') {+ assertTargetChain?.();await deps.mkdir(path.dirname(target));+ assertTargetChain?.();try {await deps.rename(source, target);return { moved: 1, conflicts: 0 };@@ -1069,6 +1672,7 @@ async function moveWithoutOverwrite(path.join(source, name),path.join(target, name),abortCheck,+ assertTargetChain,);moved += result.moved;conflicts += result.conflicts;@@ -1250,6 +1854,22 @@ export async function claimLegacyOwnerNamespace(}await deps.mkdir(userDataDir);+ if (!hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {+ const existingLegacyPathCount = (+ await Promise.all(+ LEGACY_PATHS.map(async (relativePath) =>+ (await pathType(deps, path.join(userDataDir, relativePath))) !== 'missing',+ ),+ )+ ).filter(Boolean).length;+ const result: OwnerNamespaceMigrationResult = {+ status: 'partial',+ moved: 0,+ conflicts: existingLegacyPathCount,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }let marker = existingMarker;if (!marker) {marker = { version: 1, ownerKey, complete: false };@@ -1322,6 +1942,11 @@ export async function claimLegacyOwnerNamespace(source,path.join(targetRoot, relativePath),throttledAbortCheck,+ () => {+ if (!hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {+ throw new Error('owner namespace claim target chain is not link-free');+ }+ },);moved += result.moved;conflicts += result.conflicts;@@ -1368,7 +1993,7 @@ export async function claimLegacyOwnerNamespace(}}if (!failed) {- await deps.writeFile(markerPath, JSON.stringify({ ...marker, complete: true }));+ await writeJsonAtomically(deps, markerPath, { ...marker, complete: true });}log.info('legacy owner namespace claim completed', {ownerKey,@@ -1381,6 +2006,7 @@ export async function claimLegacyOwnerNamespace(export const __testing = {CLAIM_MARKER,+ LEGACY_GHOST_RECOVERY_MARKER,LEGACY_PATHS,isSameUserDataDir,pathExistsNoFollowSync,diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 66adbdacc5..b8ab1e6543 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -20,6 +20,8 @@ import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from './local/** 清单文件名(zip 根部)。 */export const GHOST_MANIFEST_FILE = 'ghost.json';+/** Maximum manifest bytes accepted by both Forge and package ingestion. */+export const GHOST_MANIFEST_MAX_BYTES = 256 * 1024;/** 意识文件扩展名。 */export const CINDY_FILE_EXT = '.cindy';diff --git a/apps/desktop/src/shared/legacyGhostRecovery.ts b/apps/desktop/src/shared/legacyGhostRecovery.tsindex 885f9c6678..1e34b19ecc 100644--- a/apps/desktop/src/shared/legacyGhostRecovery.ts+++ b/apps/desktop/src/shared/legacyGhostRecovery.ts@@ -10,6 +10,8 @@ export interface LegacyGhostRecoveryStatus {state: LegacyGhostRecoveryState;legacyPluginCount: number;canRetry: boolean;+ /** Discovery could not establish the complete legacy source set yet. */+ deferredReason?: 'legacy-discovery-incomplete';}export const NO_LEGACY_GHOST_RECOVERY: LegacyGhostRecoveryStatus = {diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.tsindex da64c706fc..7991cbb36b 100644--- a/packages/cindy-tools/src/types.ts+++ b/packages/cindy-tools/src/types.ts@@ -154,6 +154,9 @@ export type CindyGhostCallResult =/** ghost_forge_pack 的结构化失败分类(host 侧产生,原样透传给 agent)。 */export type CindyForgePackErrorCode =| 'DIR_NOT_FOUND' // 目录不存在或不是目录+ | 'SOURCE_OUTSIDE_WORKDIR' // 源目录不在当前会话工作目录内+ | 'WORKDIR_NOT_LOCAL' // 当前会话工作目录在远端或无法证明为本地+ | 'WORKDIR_READ_ONLY' // 当前会话禁止写入| 'SOURCE_IS_INSTALLED_PLUGIN' // 源目录命中 Host 管理的已安装插件或批准状态根| 'MANIFEST_INVALID' // ghost.json 缺失 / 不合法(message 带具体原因)| 'ENTRY_MISSING' // 清单声明的 entry / panel.html 等文件不在目录里@@ -191,7 +194,7 @@ export type CindyForgeScaffoldResult =}| {ok: false;- errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'INTERNAL';+ errorCode: 'INVALID_INPUT' | 'TARGET_EXISTS' | 'WORKDIR_NOT_LOCAL' | 'WORKDIR_READ_ONLY' | 'INTERNAL';message: string;};