Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): harden plugin approval owner boundaries
Yuewei-LLdc9614e17268
diff --cc apps/desktop/src/main/__tests__/accountDeletionIpc.test.tsindex 561aea155b,89360eacfd..033974faff--- a/apps/desktop/src/main/__tests__/accountDeletionIpc.test.ts+++ b/apps/desktop/src/main/__tests__/accountDeletionIpc.test.ts@@@ -30,30 -30,25 +30,21 @@@ function createDeps(overrides: Partial<clearReceipt: vi.fn(),consumeRestoredNotice: vi.fn().mockReturnValue(false),isConfirmedLocalSessionCurrent: vi.fn().mockReturnValue(true),- beginAccountBoundary: vi.fn().mockReturnValue(vi.fn()),-- teardownAccountBoundary: vi.fn().mockResolvedValue(undefined),-- clearLocalSession: vi.fn().mockReturnValue(true),++ clearLocalSession: vi.fn().mockResolvedValue(true),logWarn: vi.fn(),...overrides,};}describe('account deletion IPC handlers', () => {-- it('tears down account services before clearing the initiating local session', async () => {++ it('delegates the full account boundary transition to the local session clear', async () => {const order: string[] = [];const deps = createDeps({confirm: vi.fn().mockImplementation(async () => {order.push('confirm');return pendingStatus;}),- beginAccountBoundary: vi.fn().mockImplementation(() => {- order.push('begin-boundary');- return () => order.push('release-boundary');- }),-- teardownAccountBoundary: vi.fn().mockImplementation(async () => {-- order.push('teardown');-- }),-- clearLocalSession: vi.fn().mockImplementation(() => {++ clearLocalSession: vi.fn().mockImplementation(async () => {order.push('clear-local');return true;}),@@@ -65,19 -60,13 +56,13 @@@});expect(result).toEqual({ success: true, value: pendingStatus });- expect(order).toEqual([- 'confirm',- 'begin-boundary',- 'teardown',- 'clear-local',- 'release-boundary',- ]);- expect(order).toEqual(['confirm', 'teardown', 'clear-local']);++ expect(order).toEqual(['confirm', 'clear-local']);});-- it('still clears local auth when post-confirm teardown reports a non-fatal failure', async () => {++ it('reports deletion accepted when post-confirm local cleanup remains quarantined', async () => {const error = new Error('db worker already stopped');const deps = createDeps({-- teardownAccountBoundary: vi.fn().mockRejectedValue(error),++ clearLocalSession: vi.fn().mockRejectedValue(error),});const handlers = createAccountDeletionIpcHandlers(deps);@@@ -86,28 -75,9 +71,27 @@@).resolves.toEqual({ success: true, value: pendingStatus });expect(deps.clearLocalSession).toHaveBeenCalledOnce();expect(deps.logWarn).toHaveBeenCalledWith(-- 'account boundary teardown after deletion failed (non-fatal)',++ 'account boundary cleanup after deletion is incomplete; local auth remains fail closed',+ error,+ );+ });+- it('always releases the account boundary when local session clearing throws', async () => {- const releaseBoundary = vi.fn();++ it('does not expose local cleanup failures after irreversible server deletion', async () => {+ const error = new Error('local auth store unavailable');+ const deps = createDeps({- beginAccountBoundary: vi.fn().mockReturnValue(releaseBoundary),- clearLocalSession: vi.fn().mockImplementation(() => {- throw error;- }),++ clearLocalSession: vi.fn().mockRejectedValue(error),+ });++ await expect(+ createAccountDeletionIpcHandlers(deps).confirm({+ challengeId: 'challenge-id',+ code: '123456',+ }),- ).rejects.toThrow(error);- expect(releaseBoundary).toHaveBeenCalledOnce();++ ).resolves.toEqual({ success: true, value: pendingStatus });++ expect(deps.logWarn).toHaveBeenCalledWith(++ 'account boundary cleanup after deletion is incomplete; local auth remains fail closed',+ error,+ );});it('preserves auth-server failure codes and leaves the local session intact', async () => {@@@ -126,8 -96,7 +110,6 @@@success: false,code: 'ACCOUNT_DELETION_CHALLENGE_INVALID',});-- expect(deps.teardownAccountBoundary).not.toHaveBeenCalled();- expect(deps.beginAccountBoundary).not.toHaveBeenCalled();expect(deps.clearLocalSession).not.toHaveBeenCalled();});@@@ -142,8 -111,7 +124,6 @@@code: '123456',}),).resolves.toEqual({ success: true, value: pendingStatus });-- expect(deps.teardownAccountBoundary).not.toHaveBeenCalled();- expect(deps.beginAccountBoundary).not.toHaveBeenCalled();expect(deps.clearLocalSession).not.toHaveBeenCalled();expect(deps.logWarn).toHaveBeenCalledWith('account deletion confirmed after local auth identity changed; skip teardown',@@@ -206,7 -174,7 +186,6 @@@{ success: true, value: pendingStatus },]);expect(deps.confirm).toHaveBeenCalledOnce();-- expect(deps.teardownAccountBoundary).toHaveBeenCalledOnce();expect(deps.clearLocalSession).toHaveBeenCalledOnce();});});diff --cc apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.tsindex cd760d8f44,cd760d8f44..9f88c2c8af--- a/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts@@@ -79,11 -79,11 +79,13 @@@ describe('desktop auth account-deletioit('preserves a confirmed receipt on local clear but drops it on ordinary logout', () => {const localClearStart = source.indexOf(-- 'export function clearLocalSessionAfterAccountDeletion(): boolean {',++ 'export async function clearLocalSessionAfterAccountDeletion(): Promise<boolean> {',);const localClearEnd = source.indexOf('\n}\n\n/**\n * 当前展示资料', localClearStart);const localClearBody = source.slice(localClearStart, localClearEnd);-- expect(localClearBody).toContain('clearAuth();');++ expect(localClearBody).toContain('await withAccountFreeOwnerCommit({');++ expect(localClearBody).toContain("reason: 'account-deletion'");++ expect(localClearBody).toContain('validateBeforeCommit: () =>');expect(localClearBody).toContain('isConfirmedAccountDeletionSessionCurrent()');expect(localClearBody).not.toContain('clearAccountDeletionReceipt');@@@ -122,14 -122,14 +124,11 @@@const body = source.slice(start, end);expect(body).toContain('if (sessionInvalidationPromise) return sessionInvalidationPromise;');-- expect(body).toContain('await authSessionTeardown(reason);');-- expect(body).toContain('closeLocalDb();');-- expect(body).toContain('clearAuth({ notify: false, deferSessionCommit: true });');++ expect(body).toContain('await withAccountFreeOwnerCommit({');++ expect(body).toContain("nextMode: 'signed-out'");++ expect(body).toContain('clearOnFailure: true');expect(body).toContain('notifyAuthListeners();');expect(body).toContain('notifySessionExpired(');-- expect(body.indexOf('clearAuth({ notify: false, deferSessionCommit: true });')).toBeLessThan(-- body.indexOf('notifySessionExpired('),-- );});it('restores the localized renderer notification without leaking internal reason codes', () => {diff --cc apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.tsindex 0000000000,0000000000..c807326d4enew file mode 100644--- /dev/null+++ b/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.ts@@@ -1,0 -1,0 +1,414 @@@++import fs from 'node:fs';++import os from 'node:os';++import path from 'node:path';++++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++++const lockMock = vi.hoisted(() => ({ held: true }));++const pathMock = vi.hoisted(() => ({ homeDir: '', userDataDir: '' }));++++vi.mock('node:os', async () => {++ const actual = await vi.importActual<typeof import('node:os')>('node:os');++ return {++ ...actual,++ default: { ...actual, homedir: () => pathMock.homeDir },++ homedir: () => pathMock.homeDir,++ };++});++++vi.mock('electron', () => ({++ app: { getPath: () => pathMock.userDataDir },++}));++++vi.mock('../logger.js', () => ({++ createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),++}));++++vi.mock('../device-link/crossProcessLock.js', () => ({++ withCrossProcessLock: async (++ _lockPath: string,++ _options: unknown,++ task: (status: { held: true } | { held: false; reason: 'busy' }) => Promise<unknown>,++ ) => task(lockMock.held ? { held: true } : { held: false, reason: 'busy' }),++}));++++import {++ __testing,++ isGhostSkillProjectionBoundaryStableForOwner,++ readGhostSkillProjectionBoundaryState,++ withGhostSkillProjectionOwnerCommit,++ withGhostSkillProjectionReadOnlyOwner,++ withGhostSkillProjectionReconcile,++} from '../authBoundaryQuarantine.js';++++function readPersistedState(): unknown {++ return JSON.parse(++ fs.readFileSync(++ path.join(pathMock.homeDir, '.cindy', 'ghost-skill-projection-boundary.json'),++ 'utf8',++ ),++ );++}++++beforeEach(() => {++ pathMock.homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-auth-boundary-'));++ pathMock.userDataDir = path.join(pathMock.homeDir, 'profile-user-data');++ lockMock.held = true;++ delete process.env.XDT_PASSIVE_SHARED_USER_DATA;++ __testing.resetProcessQuarantine();++});++++afterEach(() => {++ delete process.env.XDT_PASSIVE_SHARED_USER_DATA;++ __testing.resetProcessQuarantine();++ vi.restoreAllMocks();++ fs.rmSync(pathMock.homeDir, { recursive: true, force: true });++});++++describe('Ghost skill projection boundary state', () => {++ it('stores the machine-user projection marker beside the shared home skill roots', () => {++ expect(__testing.filePath()).toBe(++ path.join(pathMock.homeDir, '.cindy', 'ghost-skill-projection-boundary.json'),++ );++ expect(__testing.filePath()).not.toContain(pathMock.userDataDir);++ });++++ it('accepts only versioned stable and pending records', () => {++ expect(++ __testing.normalizeRecord({++ version: 1,++ phase: 'stable',++ ownerId: 'owner-a',++ transitionId: 'transition-a',++ updatedAt: 123,++ }),++ ).toEqual({++ version: 1,++ phase: 'stable',++ ownerId: 'owner-a',++ transitionId: 'transition-a',++ updatedAt: 123,++ });++ expect(++ __testing.normalizeRecord({++ version: 1,++ phase: 'pending',++ previousOwnerId: 'owner-a',++ nextOwnerId: null,++ transitionId: 'transition-b',++ updatedAt: 124,++ }),++ ).toEqual({++ version: 1,++ phase: 'pending',++ previousOwnerId: 'owner-a',++ nextOwnerId: null,++ transitionId: 'transition-b',++ updatedAt: 124,++ });++ expect(++ __testing.normalizeRecord({++ version: 1,++ phase: 'quarantined',++ previousOwnerId: 'owner-a',++ nextOwnerId: 'owner-b',++ transitionId: 'transition-c',++ updatedAt: 125,++ }),++ ).toEqual({++ version: 1,++ phase: 'quarantined',++ previousOwnerId: 'owner-a',++ nextOwnerId: 'owner-b',++ transitionId: 'transition-c',++ updatedAt: 125,++ });++ });++++ it.each([++ null,++ {},++ { version: 2, phase: 'stable', ownerId: 'owner-a', transitionId: 't', updatedAt: 1 },++ { version: 1, phase: 'stable', ownerId: '', transitionId: 't', updatedAt: 1 },++ { version: 1, phase: 'stable', ownerId: 'owner-a', transitionId: '', updatedAt: 1 },++ { version: 1, phase: 'stable', ownerId: 'owner-a', transitionId: 't', updatedAt: -1 },++ {++ version: 1,++ phase: 'pending',++ previousOwnerId: undefined,++ nextOwnerId: 'owner-b',++ transitionId: 't',++ updatedAt: 1,++ },++ ])('rejects malformed boundary data %#', (value) => {++ expect(__testing.normalizeRecord(value)).toBeNull();++ });++++ it('keeps pending through the local commit and publishes stable afterward', async () => {++ const observations: string[] = [];++++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {++ const state = readPersistedState() as { phase: string; nextOwnerId: string };++ observations.push(`${state.phase}:${state.nextOwnerId}`);++ },++ commit: () => {++ const state = readPersistedState() as { phase: string; nextOwnerId: string };++ observations.push(`${state.phase}:${state.nextOwnerId}`);++ },++ });++++ expect(observations).toEqual(['pending:owner-a', 'pending:owner-a']);++ expect(readGhostSkillProjectionBoundaryState()).toMatchObject({++ phase: 'stable',++ ownerId: 'owner-a',++ });++ expect(JSON.parse(fs.readFileSync(__testing.quarantinePath(), 'utf8'))).toMatchObject({++ phase: 'released',++ });++ });++++ it('leaves a failed transition pending across a simulated restart', async () => {++ await expect(++ withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {++ throw new Error('sweep failed');++ },++ commit: () => undefined,++ }),++ ).rejects.toThrow('sweep failed');++++ expect(readGhostSkillProjectionBoundaryState()).toMatchObject({++ phase: 'pending',++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ });++ await expect(++ withGhostSkillProjectionReconcile('owner-a', async () => 'unexpected'),++ ).rejects.toThrow('not stable');++ });++++ it('publishes a durable quarantine before a transition can fail', async () => {++ await expect(++ withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {++ expect(readPersistedState()).toMatchObject({ phase: 'pending' });++ expect(JSON.parse(fs.readFileSync(__testing.quarantinePath(), 'utf8'))).toMatchObject({++ phase: 'quarantined',++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ });++ throw new Error('teardown failed');++ },++ commit: () => undefined,++ }),++ ).rejects.toThrow('teardown failed');++++ expect(readPersistedState()).toMatchObject({++ phase: 'pending',++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ });++ expect(fs.existsSync(__testing.quarantinePath())).toBe(true);++ expect(isGhostSkillProjectionBoundaryStableForOwner('owner-a')).toBe(false);++ await expect(++ withGhostSkillProjectionReconcile('owner-a', async () => 'unexpected'),++ ).rejects.toThrow('not stable');++ });++++ it('restores pending if the local owner commit fails after stable publication', async () => {++ await expect(++ withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: () => {++ throw new Error('local commit failed');++ },++ }),++ ).rejects.toThrow('local commit failed');++++ expect(readGhostSkillProjectionBoundaryState()).toMatchObject({++ phase: 'pending',++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ });++ });++++ it('requires a teardown hook whenever owner state is missing or mismatched', async () => {++ await expect(++ withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ commit: () => undefined,++ }),++ ).rejects.toThrow('requires a teardown hook');++ expect(fs.existsSync(__testing.filePath())).toBe(false);++ });++++ it('rejects both owner commits and reconcile when the shared lock is unavailable', async () => {++ lockMock.held = false;++ await expect(++ withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: () => undefined,++ }),++ ).rejects.toThrow('lock is busy or unavailable');++ await expect(++ withGhostSkillProjectionReconcile('owner-a', async () => undefined),++ ).rejects.toThrow('lock is busy or unavailable');++ });++++ it('allows reconcile only for the exact durable stable owner', async () => {++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: () => undefined,++ });++++ await expect(withGhostSkillProjectionReconcile('owner-a', async () => 42)).resolves.toBe(42);++ await expect(++ withGhostSkillProjectionReconcile('owner-b', async () => 42),++ ).rejects.toThrow('not stable');++ });++++ it('fails closed when the durable quarantine record is malformed', async () => {++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: () => undefined,++ });++ fs.writeFileSync(__testing.quarantinePath(), '{not-json', 'utf8');++++ expect(isGhostSkillProjectionBoundaryStableForOwner('owner-a')).toBe(false);++ await expect(++ withGhostSkillProjectionReconcile('owner-a', async () => 42),++ ).rejects.toThrow('quarantined');++ });++++ it('skips teardown for an exact stable same-owner commit', async () => {++ const prepareTransition = vi.fn(async () => {});++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition,++ commit: () => undefined,++ });++ prepareTransition.mockClear();++++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: 'owner-a',++ nextOwnerId: 'owner-a',++ prepareTransition,++ commit: () => undefined,++ });++++ expect(prepareTransition).not.toHaveBeenCalled();++ });++++ it('repairs a durable mismatch even when the requested next owner already matches', async () => {++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: () => undefined,++ });++ const prepareTransition = vi.fn(async () => {});++++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: 'owner-b',++ nextOwnerId: 'owner-a',++ prepareTransition,++ commit: () => undefined,++ });++++ expect(prepareTransition).toHaveBeenCalledWith({ ownerChanged: true });++ });++++ it('lets a passive process join only the exact stable owner without mutation', async () => {++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: () => undefined,++ });++ const before = fs.readFileSync(__testing.filePath(), 'utf8');++ process.env.XDT_PASSIVE_SHARED_USER_DATA = '1';++++ await expect(withGhostSkillProjectionReadOnlyOwner('owner-a', async () => 42)).resolves.toBe(42);++ await expect(++ withGhostSkillProjectionReadOnlyOwner('owner-b', async () => 42),++ ).rejects.toThrow('another active session');++ await expect(++ withGhostSkillProjectionOwnerCommit({++ previousOwnerId: 'owner-a',++ nextOwnerId: 'owner-b',++ prepareTransition: async () => {},++ commit: () => undefined,++ }),++ ).rejects.toThrow('cannot publish');++ expect(fs.readFileSync(__testing.filePath(), 'utf8')).toBe(before);++ });++++ it('serializes owner commit and reconcile inside one process', async () => {++ let releaseCommit!: () => void;++ const commitBlocked = new Promise<void>((resolve) => {++ releaseCommit = resolve;++ });++ const commitStarted = vi.fn();++ const reconcile = vi.fn(async () => 42);++ const ownerCommit = withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: async () => {++ commitStarted();++ await commitBlocked;++ },++ });++ await vi.waitFor(() => expect(commitStarted).toHaveBeenCalledOnce());++ const reconcileResult = withGhostSkillProjectionReconcile('owner-a', reconcile);++ await Promise.resolve();++ expect(reconcile).not.toHaveBeenCalled();++++ releaseCommit();++ await ownerCommit;++ await expect(reconcileResult).resolves.toBe(42);++ });++++ it('keeps a sticky process quarantine when stable publication is uncertain', async () => {++ const originalFsync = fs.fsyncSync.bind(fs);++ let fsyncCalls = 0;++ const stableFileFsyncCall = process.platform === 'win32' ? 3 : 5;++ vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => {++ fsyncCalls += 1;++ if (fsyncCalls === stableFileFsyncCall) throw new Error('stable fsync failed');++ return originalFsync(fd);++ });++++ await expect(++ withGhostSkillProjectionOwnerCommit({++ previousOwnerId: null,++ nextOwnerId: 'owner-a',++ prepareTransition: async () => {},++ commit: () => undefined,++ }),++ ).rejects.toThrow('stable fsync failed');++++ expect(isGhostSkillProjectionBoundaryStableForOwner('owner-a')).toBe(false);++ expect(fs.existsSync(__testing.quarantinePath())).toBe(true);++ await expect(++ withGhostSkillProjectionReconcile('owner-a', async () => undefined),++ ).rejects.toThrow('quarantined');++ });++});diff --cc apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex a5ae27743a,a5ae27743a..abb6d84fd9--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@@ -214,7 -214,7 +214,7 @@@ describe('auth login-flow reset', () =expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');expect(refreshBody).toContain('writePersistedAuthSession(data.refreshToken, refreshRealm);');expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');-- expect(refreshBody).toContain('previousUserId !== currentUser.id || authRealmChanged');++ expect(refreshBody).toContain('previousUserId !== nextUser.id || authRealmChanged');expect(refreshBody).toContain('if (authRealmChanged) {\n notifyAuthListeners();');expect(deviceLinkSource).toContain('restartDeviceLinkForAuthRealmChange();');@@@ -228,14 -228,14 +228,20 @@@const helperStart = source.indexOf('async function expireRuntimeAuth(');const helperEnd = source.indexOf('\n}\n\n// ── Public API', helperStart);const helperBody = source.slice(helperStart, helperEnd);-- expect(helperBody).toContain('beginAppSessionBoundary()');-- expect(helperBody).toContain('notifyRendererAuthBoundaryPending();');expect(helperBody).toContain('clearAuth({ notify: false,');-- expect(helperBody).toContain('await accountSwitchTeardown');-- expect(helperBody).toContain('closeLocalDb();');-- expect(helperBody).toContain('notifyAuthListeners();');++ expect(helperBody).toContain('await withAccountFreeOwnerCommit({');++ expect(helperBody).toContain('authAlreadyCleared: true');expect(helperBody).toContain('notifySessionExpired(reason);');++ const ownerCommitStart = source.indexOf('async function withAccountFreeOwnerCommit(');++ const ownerCommitEnd = source.indexOf('\n}\n\nasync function withCloudOwnerCommit(', ownerCommitStart);++ const ownerCommitBody = source.slice(ownerCommitStart, ownerCommitEnd);++ expect(ownerCommitBody).toContain('beginAppSessionBoundary()');++ expect(ownerCommitBody).toContain('notifyRendererAuthBoundaryPending();');++ expect(ownerCommitBody).toContain('await accountSwitchTeardown');++ expect(ownerCommitBody).toContain('await authSessionTeardown(opts.reason);');++ expect(ownerCommitBody).toContain('notifyAuthListeners();');++const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);const refreshBody = source.slice(refreshStart, refreshEnd);diff --cc apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.tsindex 6e54037923,6e54037923..9c7e149205--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts@@@ -197,6 -197,6 +197,30 @@@ describe('passive shared-userData instaexpect(body).toContain('removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);');});++ it('passive 登录不得在 owner gate 前消费共享 receipt 或 relogin marker', () => {++ const acceptStart = authSource.indexOf('async function acceptLoginOutcome(');++ const acceptEnd = authSource.indexOf('\n}\n\nasync function runLoginAction', acceptStart);++ const acceptBody = authSource.slice(acceptStart, acceptEnd);++ const acceptGuard = acceptBody.indexOf('if (!isPassiveSharedUserDataInstance()) {');++ expect(acceptGuard).toBeGreaterThan(-1);++ expect(acceptBody.indexOf('removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);')).toBeGreaterThan(++ acceptGuard,++ );++++ const completeStart = authSource.indexOf('async function completeLogin(');++ const completeEnd = authSource.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);++ const completeBody = authSource.slice(completeStart, completeEnd);++ const completeGuard = completeBody.indexOf('if (!isPassiveSharedUserDataInstance()) {');++ expect(completeGuard).toBeGreaterThan(-1);++ expect(completeBody.indexOf('removeSafe(LEGACY_REFRESH_TOKEN_KEY);')).toBeGreaterThan(++ completeGuard,++ );++ expect(completeBody.indexOf('removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);')).toBeGreaterThan(++ completeGuard,++ );++ expect(completeBody.indexOf('clearReloginFlag();')).toBeGreaterThan(completeGuard);++ });++it('冷启动确定性失效:passive 不删盘,非 passive 也只做 compare-and-delete', () => {const start = authSource.indexOf("if (action.kind === 'definitive-failure') {");const end = authSource.indexOf("} else if (action.kind === 'replacement-retry') {", start);diff --cc apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.tsindex 95cd2640bc,95cd2640bc..8285f4e732--- a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts+++ b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts@@@ -114,10 -114,10 +114,8 @@@ describe('desktop auth session-expiry dexpect(body).toContain("notifySessionExpired(reason === 'account-unavailable' ? 'account-unavailable' : 'unknown');",);-- // 弹窗必须发生在清态之后(渲染面保持到用户确认,但 main 侧立即转登出)。-- expect(body.indexOf('clearAuth({ notify: false });')).toBeLessThan(-- body.indexOf('notifySessionExpired('),-- );++ expect(body).toContain('await withAccountFreeOwnerCommit({');++ expect(body).toContain('clearOnFailure: true');});it('device-link 收到 relay auth-failed 时主动 refresh,把被顶下线汇入会话过期出口', () => {@@@ -151,4 -151,4 +149,56 @@@const teardownBody = deviceLinkSource.slice(teardownStart, teardownEnd);expect(teardownBody).toContain('clearTimeout(relayAuthRecoveryRetryTimer);');});++++ it('routes replacement refresh through the durable Ghost projection owner boundary', () => {++ const refreshStart = authSource.indexOf('export async function refresh(): Promise<boolean> {');++ const refreshEnd = authSource.indexOf('\n}\n\nexport async function logout()', refreshStart);++ const refreshBody = authSource.slice(refreshStart, refreshEnd);++++ expect(authSource).toContain('withGhostSkillProjectionOwnerCommit,');++ expect(authSource).toContain("from './authBoundaryQuarantine.js';");++ expect(refreshBody).toContain('writePersistedAuthSession(data.refreshToken, refreshRealm);');++ expect(refreshBody).toContain('await withCloudOwnerCommit({');++ expect(refreshBody).toContain('nextOwnerId: nextUser.id');++ expect(refreshBody.indexOf('writePersistedAuthSession(data.refreshToken, refreshRealm);')).toBeLessThan(++ refreshBody.indexOf('await withCloudOwnerCommit({'),++ );++ });++++ it('keeps the Ghost sweep inside the shared owner state machine', () => {++ const ghostSource = readFileSync(++ resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),++ 'utf8',++ ).replace(/\r\n/g, '\n');++ const start = ghostSource.indexOf('export async function suspendAllGhosts(): Promise<void> {');++ const end = ghostSource.indexOf('\n}\n', start);++ const body = ghostSource.slice(start, end);++++ expect(body).toContain('await removeGhostSkillLinksForRoots(listGhostOwnerProjectionRoots())');++ expect(body).toContain('throw new Error(`ghost owner skill cleanup incomplete');++ expect(body).not.toContain('AuthBoundaryQuarantine');++++ expect(ghostSource).toContain('await withGhostSkillProjectionReconcile(');++ expect(ghostSource).toContain('releaseLease = beginGhostMutation(owner);');++ expect(ghostSource.indexOf('await withGhostSkillProjectionReconcile(')).toBeLessThan(++ ghostSource.indexOf('releaseLease = beginGhostMutation(owner);'),++ );++ });++++ it('requires every Ghost runtime lookup to match the durable projection owner', () => {++ const ghostSource = readFileSync(++ resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),++ 'utf8',++ ).replace(/\r\n/g, '\n');++ const start = ghostSource.indexOf('export function isGhostAvailableForActiveSession(');++ const end = ghostSource.indexOf('\n}\n', start);++ const body = ghostSource.slice(start, end);++ expect(body).toContain('isGhostSkillProjectionBoundaryStableForOwner(activeOwner)');++++ const requireStart = ghostSource.indexOf('function requireGhostAvailableForActiveSession(');++ const requireEnd = ghostSource.indexOf('\n}\n', requireStart);++ const requireBody = ghostSource.slice(requireStart, requireEnd);++ expect(requireBody).toContain("throwIpcError(\n 'PRECONDITION_FAILED'");++ expect(requireBody).toContain('isAppSessionBoundaryPending()');++ });});diff --cc apps/desktop/src/main/__tests__/authStartupGate.test.tsindex 33acade5f5,33acade5f5..0565cea58c--- a/apps/desktop/src/main/__tests__/authStartupGate.test.ts+++ b/apps/desktop/src/main/__tests__/authStartupGate.test.ts@@@ -68,6 -68,6 +68,24 @@@ describe('awaitWithStartupTimeout', ()expect(onLateResult).toHaveBeenCalledWith('late-login');});++ it('supports an async timeout recovery before returning the fallback', async () => {++ const flow = new Promise<string>(() => undefined);++ const recovery = vi.fn(async () => {++ await Promise.resolve();++ });++ const p = awaitWithStartupTimeout(flow, {++ timeoutMs: 1000,++ onTimeout: async () => {++ await recovery();++ return 'recovered-fallback';++ },++ });++++ await vi.advanceTimersByTimeAsync(1000);++ await expect(p).resolves.toBe('recovered-fallback');++ expect(recovery).toHaveBeenCalledOnce();++ });++it('超时:flow 迟到 reject 时回调 onLateError,rejection 被消化', async () => {let rejectFlow!: (err: unknown) => void;const flow = new Promise<string>((_r, rej) => {diff --cc apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.tsindex 829d33d298,0000000000..391acc5fbcmode 100644,000000..100644--- a/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts@@@ -1,44 -1,0 +1,44 @@@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++describe('Ghost account-boundary teardown ordering', () => {+ const bootstrap = readFileSync(+ resolve(__dirname, '../bootstrap-electron.ts'),+ 'utf8',+ ).replace(/\r\n?/g, '\n');+ const ghostIndex = readFileSync(+ resolve(__dirname, '../cindy-brain/index.ts'),+ 'utf8',+ ).replace(/\r\n?/g, '\n');++ it('interrupts long setup, grant, and pipe waits before draining owner leases', () => {+ const start = bootstrap.indexOf(- 'async function teardownAuthAccountBoundary(reason: string): Promise<void> {',++ 'async function teardownGhostProjectionBoundary(reason: string): Promise<void> {',+ );+ const end = bootstrap.indexOf('\n}\n', start);+ const body = bootstrap.slice(start, end);+- const interrupt = body.indexOf('await interruptGhostCallsForAccountBoundary();');- const wait = body.indexOf('await waitForGhostMutations();');- const suspend = body.indexOf('suspendAllGhosts();');++ const interrupt = body.indexOf('interruptGhostCallsForAccountBoundary));');++ const wait = body.indexOf('waitForGhostMutations));');++ const suspend = body.indexOf('suspendAllGhosts);');++ expect(interrupt).toBeGreaterThan(-1);+ expect(interrupt).toBeLessThan(wait);+ expect(wait).toBeLessThan(suspend);+ });++ it('replaces the terminal Node broker after an owner boundary', () => {+ const helperStart = ghostIndex.indexOf(+ 'function resetNodeRuntimeBrokerForAccountBoundary(): void {',+ );+ const helperEnd = ghostIndex.indexOf('\n}', helperStart);+ const helper = ghostIndex.slice(helperStart, helperEnd);++ expect(helperStart).toBeGreaterThan(-1);+ expect(helper).toContain('broker.destroyAll();');+ expect(helper).toContain('nodeRuntimeBrokerSingleton = null;');+ expect(ghostIndex).toContain('resetNodeRuntimeBrokerForAccountBoundary();');+ });+});diff --cc apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex 958ada4c75,77822c90b5..af76cb72be--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@@ -379,467 -351,104 +379,957 @@@ describe('claimLegacyOwnerNamespace', (expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(false);});- it('leaves an empty claim incomplete when a peer registers before completion', async () => {+ it('leaves an empty claim incomplete when a peer registers before completion', async () => {+ const root = await tempRoot();+ // 没有任何 legacy 文件:搬迁循环全 continue,唯一的复查机会是写 complete 前。+ let scans = 0;+ const deps = realFsDeps(+ root,+ { isPidAlive: (pid) => pid === 9999 },+ {+ readdir: (dir: string) => {+ if (path.basename(dir) === '.dev-instances') {+ scans += 1;+ return Promise.resolve(scans <= 1 ? [] : ['9999.json']);+ }+ return fs.readdir(dir);+ },+ readFile: (file: string) =>+ path.basename(file) === '9999.json'+ ? Promise.resolve(JSON.stringify({ pid: 9999, userDataDir: root }))+ : fs.readFile(file, 'utf-8'),+ },+ );++ const result = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ deps,+ );++ expect(result).toMatchObject({ status: 'partial' });+ expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(false);++ const resumed = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ );+ expect(resumed).toMatchObject({ status: 'migrated' });+ expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(true);+ });++ it('reports migrated (not deferred) when the claim already completed, even with live neighbors', async () => {+ const root = await tempRoot();+ await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ );+ await writeDevInstanceRecord(root, 4242);++ const again = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root, { passiveSharedUserData: () => true, isPidAlive: () => true }),+ );++ expect(again).toEqual({ status: 'migrated', moved: 0, conflicts: 0 });+ });++ it('ignores stale registry records and records from other userData dirs', async () => {+ const root = await tempRoot();+ await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');+ await writeDevInstanceRecord(root, 4242); // isPidAlive=false → 已退出的残留+ await writeDevInstanceRecord(root, 5353, '/somewhere/else'); // 异常拷贝进来的他库记录+ await fs.writeFile(path.join(root, '.dev-instances', 'torn.json'), '{not-json', 'utf-8');++ const result = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root, { isPidAlive: (pid) => pid === 5353 }),+ );++ expect(result).toMatchObject({ status: 'migrated' });+ const targetRoot = path.join(root, 'owners', dataOwnerStorageKey('cloud-a'));+ await expect(fs.readFile(path.join(targetRoot, 'slack-hook.json'), 'utf-8')).resolves.toBe('legacy-hook');+ });++ it('allows only the first verified cloud owner to claim remaining legacy data', async () => {+ const root = await tempRoot();+ await fs.writeFile(path.join(root, 'builtin-tools-settings.json'), 'legacy');++ await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ );+ await fs.writeFile(path.join(root, 'ghost-workdir-prefs.json'), 'left-behind');+ const second = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-b', user: { id: 'cloud-b' } },+ realFsDeps(root),+ );++ expect(second).toEqual({ status: 'claimed-by-other-owner', moved: 0, conflicts: 0 });+ const secondRoot = path.join(root, 'owners', dataOwnerStorageKey('cloud-b'));+ await expect(fs.access(path.join(secondRoot, 'ghost-workdir-prefs.json'))).rejects.toThrow();+ const marker = JSON.parse(+ await fs.readFile(path.join(root, __testing.CLAIM_MARKER), 'utf-8'),+ ) as { ownerKey: string };+ expect(marker.ownerKey).toBe(dataOwnerStorageKey('cloud-a'));+ 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 () => {+ if (!(await canCreateFileSymlink())) return;+ 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();+ }+});++it('lstats owner projection namespaces when readdir returns unknown Dirent types', async () => {+ const root = await tempRoot();+ const ownerKey = dataOwnerStorageKey('cloud-a');+ await fs.mkdir(path.join(root, 'owners', ownerKey), { recursive: true });+ const directoryType = vi.spyOn(fsSync.Dirent.prototype, 'isDirectory').mockReturnValue(false);+ try {+ expect(listLegacyOwnerProjectionRoots(root)).toEqual(expect.arrayContaining([+ path.join(root, 'owners', ownerKey, 'brain'),+ path.join(root, 'owners', ownerKey, 'cindy-brain'),+ path.join(root, 'owners', ownerKey, 'ghost-install-state'),+ ]));+ } finally {+ directoryType.mockRestore();+ }+});++it('fails closed when an owner projection namespace is replaced by a link', async () => {+ const root = await tempRoot();+ const external = await tempRoot();+ const ownerKey = dataOwnerStorageKey('cloud-a');+ await fs.mkdir(path.join(root, 'owners'), { recursive: true });+ try {+ await fs.symlink(+ external,+ path.join(root, 'owners', ownerKey),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }+ expect(() => listLegacyOwnerProjectionRoots(root)).toThrow(+ 'owner projection namespace is not a regular directory',+ );+});++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;++ let markerProjectionAtRename: 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 = (++ const marker = (+ JSON.parse(await fs.readFile(markerPath, 'utf-8')) as {+ pendingIds: string[];++ approvalProjectionSha256ById: Record<string, string>;+ }- ).pendingIds;++ );++ markerPendingAtRename = marker.pendingIds;++ markerProjectionAtRename =++ marker.approvalProjectionSha256ById['legacy-plugin'] ?? null;+ }+ 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']);++ expect(markerProjectionAtRename).toMatch(/^[a-f0-9]{64}$/);+ 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,++ ) as {++ ownerKey: string;++ pendingIds: string[];++ approvalProjectionSha256ById: Record<string, string>;++ };++ expect(marker).toMatchObject({++ version: 2,+ ownerKey,+ pendingIds: ['legacy-plugin'],+ });++ expect(marker.approvalProjectionSha256ById['legacy-plugin']).toMatch(/^[a-f0-9]{64}$/);+ 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'],++ recoveredApprovalProjectionSha256ById: {++ 'legacy-plugin': marker.approvalProjectionSha256ById['legacy-plugin'],++ },++ });++ });++++ it('refreshes a stale frozen projection on a later retry while the 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');++ const markerPath = path.join(++ root,++ 'owners',++ ownerKey,++ __testing.LEGACY_GHOST_RECOVERY_MARKER,++ );++ await writeGhostDirAtPath(source, 'legacy-plugin');++ let mutated = false;++++ const first = await recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root, {}, {++ rename: async (from: string, to: string) => {++ await fs.rename(from, to);++ if (path.resolve(to) !== path.resolve(markerPath) || mutated) return;++ mutated = true;++ await fs.writeFile(++ path.join(source, 'ghost.json'),++ JSON.stringify({++ schemaVersion: 2,++ id: 'legacy-plugin',++ name: 'Plugin legacy-plugin',++ version: '1.0.1',++ kind: 'chip',++ entry: 'main.js',++ slots: ['tool'],++ tools: [++ { name: 'do_thing', description: 'Do something' },++ { name: 'new_thing', description: 'New thing' },++ ],++ }),++ );++ },++ }),++ );++++ expect(mutated).toBe(true);++ expect(first).toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });++ await expect(fs.access(source)).resolves.toBeUndefined();++ await expect(fs.access(target)).rejects.toThrow();++ const firstMarker = JSON.parse(await fs.readFile(markerPath, 'utf8')) as {++ approvalProjectionSha256ById: Record<string, string>;++ };++ const staleDigest = firstMarker.approvalProjectionSha256ById['legacy-plugin'];++ expect(staleDigest).toMatch(/^[a-f0-9]{64}$/);++++ __testing.resetLegacyGhostRecoveryState();++ const second = await recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root),++ );++++ const secondMarker = JSON.parse(await fs.readFile(markerPath, 'utf8')) as {++ approvalProjectionSha256ById: Record<string, string>;++ };++ const refreshedDigest = secondMarker.approvalProjectionSha256ById['legacy-plugin'];++ expect(refreshedDigest).toMatch(/^[a-f0-9]{64}$/);++ expect(refreshedDigest).not.toBe(staleDigest);++ expect(second).toMatchObject({++ status: 'migrated',++ moved: 1,++ conflicts: 0,++ recoveredIds: ['legacy-plugin'],++ recoveredApprovalProjectionSha256ById: {++ 'legacy-plugin': refreshedDigest,++ },++ });++ await expect(fs.access(source)).rejects.toThrow();++ await expect(fs.access(target)).resolves.toBeUndefined();++ });++++ it('re-freezes an empty digest map when 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');++ const markerPath = path.join(++ root,++ 'owners',++ ownerKey,++ __testing.LEGACY_GHOST_RECOVERY_MARKER,++ );++ await writeGhostDirAtPath(source, 'legacy-plugin');++ await fs.mkdir(path.dirname(markerPath), { recursive: true });++ await fs.writeFile(++ markerPath,++ JSON.stringify({++ version: 1,++ ownerKey,++ pendingIds: ['legacy-plugin'],++ approvalProjectionSha256ById: {},++ }),++ );++++ expect(++ getLegacyGhostRecoveryStatus(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ root,++ ),++ ).toMatchObject({ state: 'partial', legacyPluginCount: 1, canRetry: true });++++ const result = await recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root),++ );++ const marker = JSON.parse(await fs.readFile(markerPath, 'utf8')) as {++ approvalProjectionSha256ById: Record<string, string>;++ };++ const refreshedDigest = marker.approvalProjectionSha256ById['legacy-plugin'];++++ expect(refreshedDigest).toMatch(/^[a-f0-9]{64}$/);++ expect(result).toMatchObject({++ status: 'migrated',++ moved: 1,++ conflicts: 0,++ recoveredIds: ['legacy-plugin'],++ recoveredApprovalProjectionSha256ById: {++ 'legacy-plugin': refreshedDigest,++ },++ });++ await expect(fs.access(source)).rejects.toThrow();++ await expect(fs.access(target)).resolves.toBeUndefined();++ });++++ it('keeps a target-only recovery marker with an empty digest map fail closed', async () => {++ const root = await tempRoot();++ const ownerId = 'cloud-a';++ const ownerKey = dataOwnerStorageKey(ownerId);++ 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(target, 'legacy-plugin');++ await fs.mkdir(path.dirname(markerPath), { recursive: true });++ await fs.writeFile(++ markerPath,++ JSON.stringify({++ version: 1,++ ownerKey,++ pendingIds: ['legacy-plugin'],++ approvalProjectionSha256ById: {},++ }),++ );++++ expect(++ getLegacyGhostRecoveryStatus(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ root,++ ),++ ).toMatchObject({ state: 'partial', legacyPluginCount: 1, canRetry: false });++++ const result = await recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root),++ );++++ expect(result).toEqual({ status: 'partial', moved: 0, conflicts: 1 });++ await expect(fs.readFile(markerPath, 'utf8').then(JSON.parse)).resolves.toMatchObject({++ version: 2,++ ownerKey,++ pendingIds: ['legacy-plugin'],++ });++ await expect(fs.readFile(path.join(target, 'ghost.json'), 'utf-8')).resolves.toContain(++ '"id":"legacy-plugin"',++ );++ });++++ it('keeps a target-only legacy marker without frozen digests fail closed', async () => {++ const root = await tempRoot();++ const ownerId = 'cloud-a';++ const ownerKey = dataOwnerStorageKey(ownerId);++ 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(target, 'legacy-plugin');++ await fs.mkdir(path.dirname(markerPath), { recursive: true });++ await fs.writeFile(++ markerPath,++ JSON.stringify({++ version: 1,++ ownerKey,++ pendingIds: ['legacy-plugin'],++ }),++ );++++ const result = await recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root),++ );++++ expect(result).toEqual({++ status: 'partial',++ moved: 0,++ conflicts: 1,++ });++ await expect(fs.readFile(markerPath, 'utf8').then(JSON.parse)).resolves.toMatchObject({++ version: 2,++ ownerKey,++ pendingIds: ['legacy-plugin'],++ });++ await expect(fs.readFile(path.join(target, 'ghost.json'), 'utf-8')).resolves.toContain(++ '"id":"legacy-plugin"',++ );++ });++++ it('upgrades a target-only v1 marker before returning its frozen projection', async () => {++ const root = await tempRoot();++ const ownerId = 'cloud-a';++ const ownerKey = dataOwnerStorageKey(ownerId);++ const target = path.join(root, 'owners', ownerKey, 'cindy-brain', 'legacy-plugin');++ const markerPath = path.join(++ root,++ 'owners',++ ownerKey,++ __testing.LEGACY_GHOST_RECOVERY_MARKER,++ );++ const frozenDigest = 'a'.repeat(64);++ await writeGhostDirAtPath(target, 'legacy-plugin');++ await fs.mkdir(path.dirname(markerPath), { recursive: true });++ await fs.writeFile(++ markerPath,++ JSON.stringify({++ version: 1,++ ownerKey,++ pendingIds: ['legacy-plugin'],++ approvalProjectionSha256ById: { 'legacy-plugin': frozenDigest },++ }),++ );++++ await expect(++ recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root),++ ),++ ).resolves.toMatchObject({++ status: 'partial',++ moved: 0,++ recoveredIds: ['legacy-plugin'],++ recoveredApprovalProjectionSha256ById: { 'legacy-plugin': frozenDigest },++ });++ await expect(fs.readFile(markerPath, 'utf8').then(JSON.parse)).resolves.toEqual({++ version: 2,++ ownerKey,++ pendingIds: ['legacy-plugin'],++ approvalProjectionSha256ById: { 'legacy-plugin': frozenDigest },+ });+ });+++ it.each(['manifest', 'disabled', 'trust', 'locale', 'icon', 'skill'] as const)(++ 'refuses an in-place %s approval projection change after the durable freeze',++ async (kind) => {++ 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');++ const manifest = {++ schemaVersion: 2,++ id: 'legacy-plugin',++ name: 'Legacy plugin',++ version: '1.0.0',++ kind: 'chip',++ entry: 'main.js',++ icon: 'assets/icon.png',++ locales: { en: 'locales/en.json' },++ slots: ['tool', 'skill'],++ tools: [{ name: 'do_thing', description: 'Do something' }],++ skill: {++ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],++ },++ };++ await fs.writeFile(path.join(source, 'ghost.json'), JSON.stringify(manifest));++ await fs.mkdir(path.join(source, 'assets'), { recursive: true });++ await fs.writeFile(path.join(source, 'assets', 'icon.png'), 'ORIGINAL ICON');++ await fs.mkdir(path.join(source, 'locales'), { recursive: true });++ await fs.writeFile(++ path.join(source, 'locales', 'en.json'),++ JSON.stringify({ name: 'Original name' }),++ );++ await fs.mkdir(path.join(source, 'skills', 'demo'), { recursive: true });++ await fs.writeFile(++ path.join(source, 'skills', 'demo', 'SKILL.md'),++ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',++ );++ let mutated = false;++++ const result = await recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root, {}, {++ rename: async (from: string, to: string) => {++ await fs.rename(from, to);++ if (path.resolve(to) !== path.resolve(markerPath) || mutated) return;++ mutated = true;++ if (kind === 'manifest') {++ await fs.writeFile(++ path.join(source, 'ghost.json'),++ JSON.stringify({++ ...manifest,++ tools: [++ ...manifest.tools,++ { name: 'new_thing', description: 'New privileged tool' },++ ],++ }),++ );++ } else if (kind === 'disabled') {++ await fs.writeFile(path.join(source, '.disabled'), '');++ } else if (kind === 'trust') {++ await fs.writeFile(++ path.join(source, '.cindy-trust.json'),++ JSON.stringify({++ level: 'verified-publisher',++ publisherSigned: true,++ publisherVerified: true,++ reviewed: false,++ }),++ );++ } else if (kind === 'locale') {++ await fs.writeFile(++ path.join(source, 'locales', 'en.json'),++ JSON.stringify({ name: 'Replaced name' }),++ );++ } else if (kind === 'icon') {++ await fs.writeFile(path.join(source, 'assets', 'icon.png'), 'REPLACED ICON');++ } else {++ await fs.writeFile(++ path.join(source, 'skills', 'demo', 'SKILL.md'),++ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',++ );++ }++ },++ }),++ );++++ expect(mutated).toBe(true);++ expect(result).toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });++ await expect(fs.access(source)).resolves.toBeUndefined();++ await expect(fs.access(target)).rejects.toThrow();++ const marker = JSON.parse(await fs.readFile(markerPath, 'utf8')) as {++ approvalProjectionSha256ById: Record<string, string>;++ };++ expect(marker.approvalProjectionSha256ById['legacy-plugin']).toMatch(/^[a-f0-9]{64}$/);++ },++ );+++ 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,++ version: 2,+ ownerKey,+ pendingIds: ['stale-plugin'],+ });+ });+- it('continues a mixed recovery marker when one id is already in the target', async () => {++ it('continues only source-present ids in a mixed recovery marker', async () => {const root = await tempRoot();- // 没有任何 legacy 文件:搬迁循环全 continue,唯一的复查机会是写 complete 前。- let scans = 0;- const deps = realFsDeps(+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(root,- { isPidAlive: (pid) => pid === 9999 },- {- readdir: (dir: string) => {- if (path.basename(dir) === '.dev-instances') {- scans += 1;- return Promise.resolve(scans <= 1 ? [] : ['9999.json']);- }- return fs.readdir(dir);- },- readFile: (file: string) =>- path.basename(file) === '9999.json'- ? Promise.resolve(JSON.stringify({ pid: 9999, userDataDir: root }))- : fs.readFile(file, 'utf-8'),- },+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,);-- const result = await claimLegacyOwnerNamespace(- { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- deps,+ 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');- expect(result).toMatchObject({ status: 'partial' });- expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(false);+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({- status: 'migrated',++ status: 'partial',+ moved: 1,- recoveredIds: ['already-moved', 'still-legacy'],++ conflicts: 1,++ recoveredIds: ['still-legacy'],+ });++ const marker = JSON.parse(await fs.readFile(markerPath, 'utf8')) as {++ approvalProjectionSha256ById: Record<string, string>;++ };++ expect(marker.approvalProjectionSha256ById).not.toHaveProperty('already-moved');++ expect(marker.approvalProjectionSha256ById['still-legacy']).toMatch(/^[a-f0-9]{64}$/);+ await expect(+ fs.access(path.join(root, 'owners', ownerKey, 'cindy-brain', 'still-legacy')),+ ).resolves.toBeUndefined();++ await expect(++ fs.access(path.join(root, 'owners', ownerKey, 'cindy-brain', 'already-moved')),++ ).resolves.toBeUndefined();+ });- const resumed = await claimLegacyOwnerNamespace(- { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- realFsDeps(root),+ 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',);- expect(resumed).toMatchObject({ status: 'migrated' });- expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(true);++ 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('reports migrated (not deferred) when the claim already completed, even with live neighbors', async () => {+ it('acknowledges only completed durable backfill ids', async () => {const root = await tempRoot();- await claimLegacyOwnerNamespace(- { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- realFsDeps(root),+ 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 writeDevInstanceRecord(root, 4242);- const again = await claimLegacyOwnerNamespace(- { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- realFsDeps(root, { passiveSharedUserData: () => true, isPidAlive: () => true }),+ await acknowledgeRecoveredLegacyGhosts(+ ownerId,+ ['completed-plugin'],+ realFsDeps(root),);- expect(again).toEqual({ status: 'migrated', moved: 0, conflicts: 0 });+ await expect(fs.readFile(markerPath, 'utf-8').then(JSON.parse)).resolves.toEqual({- version: 1,++ version: 2,+ ownerKey,+ pendingIds: ['retry-plugin'],+ });});- it('ignores stale registry records and records from other userData dirs', async () => {++ it('removes the recovery marker after the last pending id is acknowledged', async () => {+ const root = await tempRoot();- await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');- await writeDevInstanceRecord(root, 4242); // isPidAlive=false → 已退出的残留- await writeDevInstanceRecord(root, 5353, '/somewhere/else'); // 异常拷贝进来的他库记录- await fs.writeFile(path.join(root, '.dev-instances', 'torn.json'), '{not-json', 'utf-8');++ 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'],++ approvalProjectionSha256ById: {++ 'completed-plugin': 'a'.repeat(64),++ },++ }),++ );+- const result = await claimLegacyOwnerNamespace(- { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- realFsDeps(root, { isPidAlive: (pid) => pid === 5353 }),++ await acknowledgeRecoveredLegacyGhosts(++ ownerId,++ ['completed-plugin'],++ realFsDeps(root),+ );+- expect(result).toMatchObject({ status: 'migrated' });- const targetRoot = path.join(root, 'owners', dataOwnerStorageKey('cloud-a'));- await expect(fs.readFile(path.join(targetRoot, 'slack-hook.json'), 'utf-8')).resolves.toBe('legacy-hook');++ await expect(fs.access(markerPath)).rejects.toThrow();+ });+- it('allows only the first verified cloud owner to claim remaining legacy data', async () => {++ it('writes an empty recovery marker when final acknowledge cannot unlink', async () => {+ const root = await tempRoot();- await fs.writeFile(path.join(root, 'builtin-tools-settings.json'), 'legacy');++ 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'],++ approvalProjectionSha256ById: {++ 'completed-plugin': 'a'.repeat(64),++ },++ }),++ );+- await claimLegacyOwnerNamespace(- { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- realFsDeps(root),++ await acknowledgeRecoveredLegacyGhosts(++ ownerId,++ ['completed-plugin'],++ realFsDeps(root, {}, {++ unlink: async () => {++ throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });++ },++ }),+ );- await fs.writeFile(path.join(root, 'ghost-workdir-prefs.json'), 'left-behind');- const second = await claimLegacyOwnerNamespace(- { mode: 'cloud', dataOwnerId: 'cloud-b', user: { id: 'cloud-b' } },- realFsDeps(root),++++ await expect(fs.readFile(markerPath, 'utf8').then(JSON.parse)).resolves.toEqual({++ version: 2,++ ownerKey,++ pendingIds: [],++ });++ });++++ it('treats a legacy empty recovery marker as absent for fresh discovery', 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: [] }));++ await writeGhostDirAtPath(path.join(root, 'brain', 'fresh-plugin'), 'fresh-plugin');+- expect(second).toEqual({ status: 'claimed-by-other-owner', moved: 0, conflicts: 0 });- const secondRoot = path.join(root, 'owners', dataOwnerStorageKey('cloud-b'));- await expect(fs.access(path.join(secondRoot, 'ghost-workdir-prefs.json'))).rejects.toThrow();- const marker = JSON.parse(- await fs.readFile(path.join(root, __testing.CLAIM_MARKER), 'utf-8'),- ) as { ownerKey: string };- expect(marker.ownerKey).toBe(dataOwnerStorageKey('cloud-a'));- expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(true);- expect(hasLegacyOwnerNamespaceClaim('cloud-b', root)).toBe(false);++ await expect(++ recoverLegacyGhostPlugins(++ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },++ realFsDeps(root),++ ),++ ).resolves.toMatchObject({++ status: 'migrated',++ moved: 1,++ conflicts: 0,++ recoveredIds: ['fresh-plugin'],++ });++ await expect(++ fs.access(path.join(root, 'owners', ownerKey, 'cindy-brain', 'fresh-plugin')),++ ).resolves.toBeUndefined();+ });-});+-describe('legacy Ghost plugin recovery', () => {it('does not follow a linked legacy repository root', async () => {const root = await tempRoot();const externalRoot = await tempRoot();@@@ -2042,6 -1481,6 +2532,7 @@@ function realFsDepswriteFileExclusive: (file: string, text: string) =>fs.writeFile(file, text, { encoding: 'utf-8', flag: 'wx' }),writeFile: (file: string, text: string) => fs.writeFile(file, text, 'utf-8'),++ unlink: (file: string) => fs.unlink(file),lstat: (file: string) => fs.lstat(file),readdir: (dir: string) => fs.readdir(dir),mkdir: async (dir: string) => {diff --cc apps/desktop/src/main/accountDeletionIpc.tsindex 98244313f8,c4a0f4df61..b1a2391eac--- a/apps/desktop/src/main/accountDeletionIpc.ts+++ b/apps/desktop/src/main/accountDeletionIpc.ts@@@ -31,9 -31,8 +31,7 @@@ export interface AccountDeletionIpcDepclearReceipt(): void;consumeRestoredNotice(): boolean;isConfirmedLocalSessionCurrent(): boolean;- beginAccountBoundary(): () => void;-- teardownAccountBoundary(): Promise<void>;-- clearLocalSession(): boolean;++ clearLocalSession(): Promise<boolean>;logWarn(message: string, error?: unknown): void;}@@@ -109,23 -108,15 +107,16 @@@ export function createAccountDeletionIpreturn { success: true, value: status };}- // Hold the owner boundary across both teardown and the session commit.- // Otherwise a new owner-bound mutation can start after teardown's- // waitForIdle and race with clearLocalSession switching the namespace.- const releaseBoundary = deps.beginAccountBoundary();- // Teardown failures are non-fatal here: keeping the initiator logged in- // would be more misleading and less safe than completing local logout.try {- // Teardown failures are non-fatal here: keeping the initiator logged in- // would be more misleading and less safe than completing local logout.- try {- await deps.teardownAccountBoundary();- } catch (error) {- deps.logWarn('account boundary teardown after deletion failed (non-fatal)', error);- }- if (!deps.clearLocalSession()) {- await deps.teardownAccountBoundary();++ if (!(await deps.clearLocalSession())) {+ deps.logWarn('local auth identity changed during account deletion teardown; skip clear');+ }- } finally {- releaseBoundary();+ } catch (error) {- deps.logWarn('account boundary teardown after deletion failed (non-fatal)', error);- }- if (!deps.clearLocalSession()) {- deps.logWarn('local auth identity changed during account deletion teardown; skip clear');++ deps.logWarn(++ 'account boundary cleanup after deletion is incomplete; local auth remains fail closed',++ error,++ );++ return { success: true, value: status };}return { success: true, value: status };})();diff --cc apps/desktop/src/main/appCapabilities.tsindex f940cff398,f940cff398..d58b258f1c--- a/apps/desktop/src/main/appCapabilities.ts+++ b/apps/desktop/src/main/appCapabilities.ts@@@ -37,8 -37,8 +37,9 @@@ export function deriveAppCapabilities}export function getAppCapabilities(): AppCapabilities {++ const session = getActiveAppSession();return deriveAppCapabilities(-- getActiveAppSession().mode,++ session.mode,isAppSessionBoundaryPending(),);}diff --cc apps/desktop/src/main/appSessionState.tsindex f2f0e6574a,f2f0e6574a..fba955fead--- a/apps/desktop/src/main/appSessionState.ts+++ b/apps/desktop/src/main/appSessionState.ts@@@ -13,6 -13,6 +13,7 @@@ import { createLogger } from './logger.import { createOverrideSettingsFile } from './maker-host/override-settings-file.js';import { LOCAL_PROFILE_DATA_OWNER_ID } from './profile/profileRegistryModel.js';import type { DataOwnerPushStamp } from '../shared/dataOwnerPush.js';++import { isGhostSkillProjectionBoundaryStableForOwner } from './authBoundaryQuarantine.js';export type AppSessionMode = 'signed-out' | 'local' | 'cloud';@@@ -142,6 -142,6 +143,13 @@@ export function beginAppSessionBoundary}export function isAppSessionBoundaryPending(): boolean {++ if (boundaryDepth > 0) return true;++ const session = ensureLoaded();++ return !isGhostSkillProjectionBoundaryStableForOwner(session.dataOwnerId);++}++++/** Process-local transition state, excluding a durable owner mismatch. */++export function isAppSessionBoundaryLocallyPending(): boolean {return boundaryDepth > 0;}@@@ -181,4 -181,4 +189,31 @@@ export function commitActiveAppSessionreturn { ...active };}++/** Update only this process after a passive instance signs out or is quarantined. */++export function commitVolatileAppSession(++ mode: AppSessionMode,++ cloudOwnerId?: string | null,++): ActiveAppSession {++ const previous = ensureLoaded();++ let dataOwnerId: string | null = null;++ if (mode === 'local') {++ dataOwnerId = LOCAL_DATA_OWNER_ID;++ } else if (mode === 'cloud') {++ const normalized = cloudOwnerId?.trim();++ if (!normalized) throw new Error('cloud app session requires a verified data owner');++ dataOwnerId = normalized;++ }++ active = {++ mode,++ dataOwnerId,++ generation: previous.generation + 1,++ };++ log.info('volatile app session committed', {++ mode,++ dataOwnerId,++ generation: active.generation,++ });++ return { ...active };++}++export const __testing = { normalize };diff --cc apps/desktop/src/main/authBoundaryQuarantine.tsindex 0000000000,0000000000..c63e3d738enew file mode 100644--- /dev/null+++ b/apps/desktop/src/main/authBoundaryQuarantine.ts@@@ -1,0 -1,0 +1,499 @@@++/**++ * Cross-process state machine for the globally visible Ghost skill projection.++ *++ * Owner-scoped plugin bytes live under userData, but the links consumed by++ * agents live in shared home directories. Every owner transition and every++ * Ghost reconcile therefore uses the same strict lock and durable owner state.++ * Missing, malformed, or pending state never authorizes a reconcile.++ */++import fs from 'node:fs';++import path from 'node:path';++import crypto from 'node:crypto';++import os from 'node:os';++++import { app } from 'electron';++++import { withCrossProcessLock } from './device-link/crossProcessLock.js';++import { createLogger } from './logger.js';++import { atomicWriteFileSync } from './utils/atomicWriteFile.js';++import { readBoundedFileNoFollowSync } from './utils/readBoundedFile.js';++++const log = createLogger('ghost-skill-projection-boundary');++const FILE_NAME = 'ghost-skill-projection-boundary.json';++const QUARANTINE_FILE_NAME = 'ghost-skill-projection-boundary.quarantine.json';++const MAX_BYTES = 16 * 1024;++let processProjectionQuarantined = false;++++export type GhostSkillProjectionBoundaryState =++ | {++ version: 1;++ phase: 'stable';++ ownerId: string | null;++ transitionId: string;++ updatedAt: number;++ }++ | {++ version: 1;++ phase: 'pending';++ previousOwnerId: string | null;++ nextOwnerId: string | null;++ transitionId: string;++ updatedAt: number;++ }++ | {++ version: 1;++ phase: 'quarantined';++ previousOwnerId: string | null;++ nextOwnerId: string | null;++ transitionId: string;++ updatedAt: number;++ };++++interface OwnerCommitOptions<T> {++ previousOwnerId: string | null;++ nextOwnerId: string | null;++ prepareTransition?: (context: { ownerChanged: boolean }) => Promise<void>;++ prepareCommit?: () => Promise<void>;++ commit: () => T | Promise<T>;++}++++type StateRead =++ | { kind: 'ok'; state: GhostSkillProjectionBoundaryState }++ | { kind: 'missing' | 'invalid' };++++type QuarantineState =++ | Extract<GhostSkillProjectionBoundaryState, { phase: 'quarantined' }>++ | {++ version: 1;++ phase: 'released';++ transitionId: string;++ updatedAt: number;++ };++++type QuarantineRead =++ | { kind: 'ok'; state: QuarantineState }++ | { kind: 'missing' | 'invalid' };++++function filePath(): string {++ // This marker deliberately lives beside the shared home-level Ghost skill++ // projection. It must be visible to every Cindy instance using this OS user;++ // profile-scoped application state remains under app.getPath('userData').++ return path.join(os.homedir(), '.cindy', FILE_NAME);++}++++function quarantinePath(): string {++ return path.join(os.homedir(), '.cindy', QUARANTINE_FILE_NAME);++}++++function lockPath(): string {++ return `${filePath()}.lock`;++}++++function normalizeOwnerId(value: unknown): string | null | undefined {++ if (value === null) return null;++ if (typeof value !== 'string') return undefined;++ const normalized = value.trim();++ return normalized === '' ? undefined : normalized;++}++++function normalizeOwnerArgument(value: string | null): string | null {++ const normalized = normalizeOwnerId(value);++ if (normalized === undefined) throw new Error('Ghost skill projection owner is invalid');++ return normalized;++}++++function isPassiveSharedUserDataInstance(): boolean {++ return !app.isPackaged && process.env.XDT_PASSIVE_SHARED_USER_DATA === '1';++}++++function normalizeRecord(raw: unknown): GhostSkillProjectionBoundaryState | null {++ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;++ const value = raw as Record<string, unknown>;++ if (value.version !== 1) return null;++ if (typeof value.transitionId !== 'string' || value.transitionId.trim() === '') return null;++ if (++ typeof value.updatedAt !== 'number' ||++ !Number.isFinite(value.updatedAt) ||++ value.updatedAt < 0++ ) {++ return null;++ }++ if (value.phase === 'stable') {++ const ownerId = normalizeOwnerId(value.ownerId);++ if (ownerId === undefined) return null;++ return {++ version: 1,++ phase: 'stable',++ ownerId,++ transitionId: value.transitionId,++ updatedAt: value.updatedAt,++ };++ }++ if (value.phase === 'pending') {++ const previousOwnerId = normalizeOwnerId(value.previousOwnerId);++ const nextOwnerId = normalizeOwnerId(value.nextOwnerId);++ if (previousOwnerId === undefined || nextOwnerId === undefined) return null;++ return {++ version: 1,++ phase: 'pending',++ previousOwnerId,++ nextOwnerId,++ transitionId: value.transitionId,++ updatedAt: value.updatedAt,++ };++ }++ if (value.phase === 'quarantined') {++ const previousOwnerId = normalizeOwnerId(value.previousOwnerId);++ const nextOwnerId = normalizeOwnerId(value.nextOwnerId);++ if (previousOwnerId === undefined || nextOwnerId === undefined) return null;++ return {++ version: 1,++ phase: 'quarantined',++ previousOwnerId,++ nextOwnerId,++ transitionId: value.transitionId,++ updatedAt: value.updatedAt,++ };++ }++ return null;++}++++function normalizeQuarantineRecord(raw: unknown): QuarantineState | null {++ const boundary = normalizeRecord(raw);++ if (boundary?.phase === 'quarantined') return boundary;++ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;++ const value = raw as Record<string, unknown>;++ if (++ value.version !== 1++ || value.phase !== 'released'++ || typeof value.transitionId !== 'string'++ || value.transitionId.trim() === ''++ || typeof value.updatedAt !== 'number'++ || !Number.isFinite(value.updatedAt)++ || value.updatedAt < 0++ ) {++ return null;++ }++ return {++ version: 1,++ phase: 'released',++ transitionId: value.transitionId,++ updatedAt: value.updatedAt,++ };++}++++function readState(): StateRead {++ return readStateFile(filePath(), normalizeRecord);++}++++function readQuarantineState(): QuarantineRead {++ return readStateFile(quarantinePath(), normalizeQuarantineRecord);++}++++function readStateFile<T>(++ targetPath: string,++ normalize: (raw: unknown) => T | null,++): { kind: 'ok'; state: T } | { kind: 'missing' | 'invalid' } {++ let bytes: Buffer | null;++ try {++ bytes = readBoundedFileNoFollowSync(targetPath, MAX_BYTES);++ } catch (error) {++ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };++ log.error('Ghost skill projection boundary could not be read', error);++ return { kind: 'invalid' };++ }++ if (!bytes) return { kind: 'invalid' };++ try {++ const state = normalize(JSON.parse(bytes.toString('utf8')));++ return state ? { kind: 'ok', state } : { kind: 'invalid' };++ } catch {++ return { kind: 'invalid' };++ }++}++++function isDurablyQuarantined(): boolean {++ const observed = readQuarantineState();++ return observed.kind === 'invalid'++ || (observed.kind === 'ok' && observed.state.phase === 'quarantined');++}++++function syncCommittedState(file: string): void {++ const noFollow = fs.constants.O_NOFOLLOW ?? 0;++ // Windows rejects fsync on a read-only handle with EPERM. Open the freshly++ // replaced private marker read/write so the durability gate works on both++ // supported desktop platforms; O_NOFOLLOW still rejects a raced symlink.++ const fd = fs.openSync(file, fs.constants.O_RDWR | (fs.constants.O_NONBLOCK ?? 0) | noFollow);++ try {++ fs.fsyncSync(fd);++ } finally {++ fs.closeSync(fd);++ }++ if (process.platform === 'win32') return;++ const dirFd = fs.openSync(path.dirname(file), fs.constants.O_RDONLY);++ try {++ fs.fsyncSync(dirFd);++ } finally {++ fs.closeSync(dirFd);++ }++}++++function writeState(state: GhostSkillProjectionBoundaryState): void {++ writeStateFile(filePath(), state);++}++++function writeQuarantineState(state: Extract<GhostSkillProjectionBoundaryState, { phase: 'quarantined' }>): void {++ writeStateFile(quarantinePath(), state);++}++++function writeStateFile(++ file: string,++ state: GhostSkillProjectionBoundaryState | QuarantineState,++): void {++ atomicWriteFileSync(file, JSON.stringify(state));++ // The caller may publish a new owner immediately after this returns. Flush++ // both the replacement file and, where supported, the containing directory.++ syncCommittedState(file);++}++++function clearQuarantineState(transitionId: string): void {++ writeStateFile(quarantinePath(), {++ version: 1,++ phase: 'released',++ transitionId,++ updatedAt: Date.now(),++ });++}++++async function withStrictBoundaryLock<T>(task: () => Promise<T>): Promise<T> {++ const previous = inProcessBoundaryTail;++ let releaseInProcess: () => void = () => undefined;++ inProcessBoundaryTail = new Promise<void>((resolve) => {++ releaseInProcess = () => resolve();++ });++ await previous;++ try {++ const file = filePath();++ fs.mkdirSync(path.dirname(file), { recursive: true });++ return await withCrossProcessLock(++ lockPath(),++ {++ label: 'ghost-skill-projection-boundary',++ waitMs: 12_000,++ // Nonce-verified takeover and a recoverable reclaim gate make a crashed++ // owner reclaimable without allowing a live owner to be overwritten.++ allowStaleTakeover: true,++ requireProcessIdentity: true,++ allowMalformedStaleTakeover: false,++ },++ async (status) => {++ if (!status.held) {++ throw new Error('Ghost skill projection boundary lock is busy or unavailable');++ }++ return task();++ },++ );++ } finally {++ releaseInProcess();++ }++}++++let inProcessBoundaryTail: Promise<void> = Promise.resolve();++++/**++ * Serialize an application owner commit with the global Ghost skill projection.++ *++ * A stable matching owner may commit without another sweep, but still commits++ * under the same lock as reconcile. Missing/invalid/pending/mismatched state++ * first writes a durable quarantine record, then a pending record, before the++ * full teardown and sweep. A failed transition keeps the durable state++ * non-stable even after this process releases its in-memory boundary. The local++ * session commits while the durable state is still pending, so all owner-bound++ * consumers remain fail closed. The matching stable owner is only published++ * after that commit succeeds.++ */++export async function withGhostSkillProjectionOwnerCommit<T>(++ options: OwnerCommitOptions<T>,++): Promise<T> {++ if (isPassiveSharedUserDataInstance()) {++ throw new Error('Passive shared-userData instances cannot publish the Ghost projection owner');++ }++ const previousOwnerId = normalizeOwnerArgument(options.previousOwnerId);++ const nextOwnerId = normalizeOwnerArgument(options.nextOwnerId);++ return withStrictBoundaryLock(async () => {++ const observed = readState();++ const stable =++ observed.kind === 'ok' && observed.state.phase === 'stable'++ ? observed.state++ : null;++ const previousMatches = stable?.ownerId === previousOwnerId;++ const requiresTransition =++ processProjectionQuarantined++ || isDurablyQuarantined()++ || stable?.ownerId !== nextOwnerId++ || !previousMatches;++ const ownerChanged = previousOwnerId !== nextOwnerId;++ const transitionId = crypto.randomUUID();++ const prepareTransition = options.prepareTransition;++++ if (requiresTransition) {++ if (!prepareTransition) {++ throw new Error('Ghost skill projection owner transition requires a teardown hook');++ }++ processProjectionQuarantined = true;++ }++++ try {++ if (requiresTransition) {++ const prepare = prepareTransition;++ if (!prepare) {++ throw new Error('Ghost skill projection owner transition requires a teardown hook');++ }++ const previousStateOwnerId = stable?.ownerId ?? previousOwnerId;++ writeQuarantineState({++ version: 1,++ phase: 'quarantined',++ previousOwnerId: previousStateOwnerId,++ nextOwnerId,++ transitionId,++ updatedAt: Date.now(),++ });++ writeState({++ version: 1,++ phase: 'pending',++ previousOwnerId: previousStateOwnerId,++ nextOwnerId,++ transitionId,++ updatedAt: Date.now(),++ });++ await prepare({ ownerChanged });++ }++ await options.prepareCommit?.();++ const result = await options.commit();++ if (requiresTransition) {++ writeState({++ version: 1,++ phase: 'stable',++ ownerId: nextOwnerId,++ transitionId,++ updatedAt: Date.now(),++ });++ clearQuarantineState(transitionId);++ processProjectionQuarantined = false;++ }++ return result;++ } catch (error) {++ if (requiresTransition) {++ try {++ writeState({++ version: 1,++ phase: 'pending',++ previousOwnerId: stable?.ownerId ?? previousOwnerId,++ nextOwnerId,++ transitionId,++ updatedAt: Date.now(),++ });++ } catch (stateError) {++ log.error(++ 'Ghost skill projection boundary could not preserve pending after owner transition failed',++ stateError,++ );++ try {++ writeQuarantineState({++ version: 1,++ phase: 'quarantined',++ previousOwnerId: stable?.ownerId ?? previousOwnerId,++ nextOwnerId,++ transitionId,++ updatedAt: Date.now(),++ });++ } catch (quarantineError) {++ log.error(++ 'Ghost skill projection boundary could not preserve durable quarantine',++ quarantineError,++ );++ }++ }++ }++ throw error;++ }++ });++}++++/** Allow link mutation only for the globally stable owner, under the same lock. */++export async function withGhostSkillProjectionReconcile<T>(++ ownerId: string,++ reconcile: () => Promise<T>,++): Promise<T> {++ if (isPassiveSharedUserDataInstance()) {++ throw new Error('Passive shared-userData instances cannot mutate the Ghost skill projection');++ }++ const normalizedOwnerId = ownerId.trim();++ if (!normalizedOwnerId) throw new Error('Ghost skill reconcile requires a committed owner');++ return withStrictBoundaryLock(async () => {++ if (processProjectionQuarantined || isDurablyQuarantined()) {++ throw new Error(++ 'Ghost skill projection is quarantined after an uncertain owner commit; projection is not stable',++ );++ }++ const observed = readState();++ if (++ observed.kind !== 'ok' ||++ observed.state.phase !== 'stable' ||++ observed.state.ownerId !== normalizedOwnerId++ ) {++ throw new Error('Ghost skill projection is not stable for the active owner');++ }++ return reconcile();++ });++}++++/** Join an already-published owner without allowing this process to mutate it. */++export async function withGhostSkillProjectionReadOnlyOwner<T>(++ ownerId: string,++ commit: () => T | Promise<T>,++): Promise<T> {++ const normalizedOwnerId = normalizeOwnerArgument(ownerId);++ if (normalizedOwnerId === null) {++ throw new Error('Read-only Ghost projection join requires a committed owner');++ }++ return withStrictBoundaryLock(async () => {++ if (!isGhostSkillProjectionBoundaryStableForOwner(normalizedOwnerId)) {++ throw new Error('Ghost skill projection is owned by another active session');++ }++ return commit();++ });++}++++export function readGhostSkillProjectionBoundaryState(): GhostSkillProjectionBoundaryState | null {++ const observed = readState();++ return observed.kind === 'ok' ? observed.state : null;++}++++export function isGhostSkillProjectionBoundaryStableForOwner(ownerId: string | null): boolean {++ if (processProjectionQuarantined || isDurablyQuarantined()) return false;++ const normalizedOwnerId = normalizeOwnerArgument(ownerId);++ const observed = readState();++ return observed.kind === 'ok'++ && observed.state.phase === 'stable'++ && observed.state.ownerId === normalizedOwnerId;++}++++export function assertGhostSkillProjectionStableOwner(ownerId: string): void {++ const normalizedOwnerId = ownerId.trim();++ if (!normalizedOwnerId) throw new Error('Ghost skill projection requires a committed owner');++ if (!isGhostSkillProjectionBoundaryStableForOwner(normalizedOwnerId)) {++ throw new Error('Ghost skill projection is not stable for the active owner');++ }++}++++export const __testing = {++ filePath,++ quarantinePath,++ lockPath,++ normalizeRecord,++ readState,++ resetProcessQuarantine: () => {++ processProjectionQuarantined = false;++ },++ maxBytes: MAX_BYTES,++};diff --cc apps/desktop/src/main/authManager.tsindex 41c6ad524a,41c6ad524a..1997c5a0c1--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@@ -41,7 -41,7 +41,6 @@@ importtype ProviderConfig,type SocialProvider,} from '@cindy/auth-client';--import { closeDb as closeLocalDb } from './localDb';import { readReloginFlag, clearReloginFlag } from './updateService';import * as canaryFlagStore from './canaryFlagStore';import { decodeAccessTokenOrgSlug } from './authTokenClaims';@@@ -72,6 -72,6 +71,11 @@@ import { createDesktopPollCredentials,import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures';import { createLogger } from './logger';++import {++ isGhostSkillProjectionBoundaryStableForOwner,++ withGhostSkillProjectionOwnerCommit,++ withGhostSkillProjectionReadOnlyOwner,++} from './authBoundaryQuarantine.js';import { buildFocusDeepLink } from './deepLink';import { getResolvedMainLocale, t } from './i18n';import {@@@ -91,8 -91,8 +95,11 @@@ importimport {beginAppSessionBoundary,commitActiveAppSession,++ commitVolatileAppSession,getActiveAppSession,getActiveDataOwnerPushStamp,++ isAppSessionBoundaryPending,++ LOCAL_DATA_OWNER_ID,type AppSessionMode,} from './appSessionState.js';import {@@@ -236,9 -236,9 +243,11 @@@ type AccountSwitchTeardown = (context:/** Releases every account-scoped runtime before terminal local sign-out. */type AuthSessionTeardown = (reason: string) => void | Promise<void>;++type ProjectionRepairTeardown = (reason: string) => void | Promise<void>;let accountSwitchTeardown: AccountSwitchTeardown | null = null;let authSessionTeardown: AuthSessionTeardown | null = null;++let projectionRepairTeardown: ProjectionRepairTeardown | null = null;// ── Module-level state ──────────────────────────────────────────────────────@@@ -796,6 -796,6 +805,205 @@@ function mergeMembershipWithExisting};}++/** Serialize a verified cloud owner commit with the shared Ghost projection. */++async function withCloudOwnerCommit<T>(opts: {++ previousOwnerId: string | null;++ nextOwnerId: string;++ prepareTransition: () => Promise<void>;++ prepareCommit?: () => Promise<void>;++ commit: () => T | Promise<T>;++}): Promise<T> {++ if (isPassiveSharedUserDataInstance()) {++ return withGhostSkillProjectionReadOnlyOwner(opts.nextOwnerId, opts.commit);++ }++ let releaseBoundary: (() => void) | null = null;++ try {++ return await withGhostSkillProjectionOwnerCommit({++ previousOwnerId: opts.previousOwnerId,++ nextOwnerId: opts.nextOwnerId,++ prepareTransition: async ({ ownerChanged }) => {++ notifyRendererAuthBoundaryPending();++ releaseBoundary = beginAppSessionBoundary();++ if (ownerChanged) {++ await opts.prepareTransition();++ } else {++ if (!projectionRepairTeardown) {++ throw new Error('Ghost projection repair requires a teardown hook');++ }++ await projectionRepairTeardown('same-owner-projection-recovery');++ }++ },++ prepareCommit: opts.prepareCommit,++ commit: opts.commit,++ });++ } finally {++ const release = releaseBoundary as (() => void) | null;++ release?.();++ if (release) notifyRenderer();++ }++}++++/**++ * Publish an account-free owner only after the same global Ghost projection++ * transition used by cloud login and account replacement has completed.++ *++ * The auth fields are cleared in the commit callback, after the durable++ * pending marker and teardown. If the transition cannot be persisted or the++ * sweep fails, the local session is still made account-free, but the durable++ * boundary remains non-stable so a later cloud owner cannot commit without a++ * fresh sweep.++ */++async function withAccountFreeOwnerCommit(opts: {++ reason: string;++ nextMode: Extract<AppSessionMode, 'signed-out' | 'local'>;++ preservePersistedRefreshToken?: boolean;++ notify?: boolean;++ clearOnFailure?: boolean;++ authAlreadyCleared?: boolean;++ validateBeforeCommit?: () => boolean;++ shouldClearOnFailure?: () => boolean;++}): Promise<void> {++ let authCleared = opts.authAlreadyCleared ?? false;++ let releaseBoundary: (() => void) | null = null;++ const notify = opts.notify ?? true;++ const previousOwnerId = getActiveAppSession().dataOwnerId;++ if (isPassiveSharedUserDataInstance()) {++ if (opts.validateBeforeCommit && !opts.validateBeforeCommit()) {++ throw new AuthApiError(++ 'AUTH_FLOW_SUPERSEDED',++ 409,++ 'Account-free owner transition was superseded before commit',++ );++ }++ if (!authCleared) {++ clearAuth({++ notify: false,++ nextMode: opts.nextMode,++ preservePersistedRefreshToken: true,++ deferSessionCommit: true,++ });++ authCleared = true;++ }++ commitVolatileAppSession(opts.nextMode);++ if (notify) {++ notifyRenderer();++ notifyAuthListeners();++ }++ return;++ }++ try {++ await withGhostSkillProjectionOwnerCommit({++ previousOwnerId,++ nextOwnerId: opts.nextMode === 'local' ? LOCAL_DATA_OWNER_ID : null,++ prepareTransition: async ({ ownerChanged }) => {++ notifyRendererAuthBoundaryPending();++ releaseBoundary = beginAppSessionBoundary();++ if (ownerChanged) {++ if (!authSessionTeardown) {++ throw new Error('account-free owner transition requires a teardown hook');++ }++ await authSessionTeardown(opts.reason);++ } else {++ if (!projectionRepairTeardown) {++ throw new Error('account-free projection repair requires a teardown hook');++ }++ await projectionRepairTeardown(opts.reason);++ }++ },++ prepareCommit: async () => {++ if (opts.validateBeforeCommit && !opts.validateBeforeCommit()) {++ throw new AuthApiError(++ 'AUTH_FLOW_SUPERSEDED',++ 409,++ 'Account-free owner transition was superseded before commit',++ );++ }++ },++ commit: () => {++ if (!authCleared) {++ clearAuth({++ notify: false,++ nextMode: opts.nextMode,++ preservePersistedRefreshToken: opts.preservePersistedRefreshToken,++ deferSessionCommit: true,++ });++ authCleared = true;++ }++ commitActiveAppSession(opts.nextMode);++ },++ });++ } catch (error) {++ // A terminal auth path must not leave an in-memory cloud owner active. The++ // durable state is intentionally left missing/pending so future cloud++ // publication remains fail-closed until another full transition succeeds.++ if (opts.clearOnFailure && (opts.shouldClearOnFailure?.() ?? true)) {++ if (!authCleared) {++ clearAuth({++ notify: false,++ nextMode: 'signed-out',++ preservePersistedRefreshToken: opts.preservePersistedRefreshToken,++ deferSessionCommit: true,++ });++ authCleared = true;++ }++ // The durable app-session write may be the operation that failed. Keep++ // the process account-free without retrying that write on this path.++ try {++ commitVolatileAppSession('signed-out');++ } catch (sessionError) {++ log.error('failed to commit volatile signed-out fallback', sessionError);++ }++ }++ throw error;++ } finally {++ const release = releaseBoundary as (() => void) | null;++ release?.();++ if (release && notify) notifyRenderer();++ }++++ if (notify) {++ notifyRenderer();++ notifyAuthListeners();++ }++}++++async function recoverAccountFreeOwnerAtStartup(++ mode: Extract<AppSessionMode, 'signed-out' | 'local'>,++ reason: string,++): Promise<void> {++ const ownerId = mode === 'local' ? LOCAL_DATA_OWNER_ID : null;++ if (isGhostSkillProjectionBoundaryStableForOwner(ownerId)) {++ if (getActiveAppSession().mode !== mode || getActiveAppSession().dataOwnerId !== ownerId) {++ if (isPassiveSharedUserDataInstance()) {++ commitVolatileAppSession(mode);++ } else {++ commitActiveAppSession(mode);++ }++ }++ return;++ }++ await withAccountFreeOwnerCommit({++ reason,++ nextMode: mode,++ notify: false,++ clearOnFailure: mode === 'signed-out',++ preservePersistedRefreshToken: true,++ });++}++++function commitCloudAppSession(ownerId: string): void {++ if (isPassiveSharedUserDataInstance()) {++ commitVolatileAppSession('cloud', ownerId);++ } else {++ commitActiveAppSession('cloud', ownerId);++ }++}++++async function finishColdStartSignedOut(reason: string): Promise<AuthState> {++ await recoverAccountFreeOwnerAtStartup('signed-out', reason);++ return snapshotLoggedOutAuthState();++}++export function setAccountSwitchTeardown(teardown: AccountSwitchTeardown | null): void {accountSwitchTeardown = teardown;}@@@ -804,6 -804,6 +1012,10 @@@ export function setAuthSessionTeardown(authSessionTeardown = teardown;}++export function setProjectionRepairTeardown(teardown: ProjectionRepairTeardown | null): void {++ projectionRepairTeardown = teardown;++}++// ── User-level API key sync ─────────────────────────────────────────────────//// 已移除。XD 网关 key / Mivo key 均为 **本地 only**(Electron safeStorage),@@@ -1284,7 -1284,7 +1496,7 @@@ function snapshotAuthState(): AuthStatmode: appSession.mode,dataOwnerId: appSession.dataOwnerId,ownerGeneration: appSession.generation,-- canEnterApp: appSession.mode !== 'signed-out',++ canEnterApp: appSession.mode !== 'signed-out' && !isAppSessionBoundaryPending(),isAuthenticated: isCloudAuthenticated,isCanary: currentUser !== null && canaryFlagStore.read(),deviceId,@@@ -1513,34 -1513,34 +1725,27 @@@ async function expireRuntimeAuthreason: SessionExpiredReason = 'unknown',opts: { preservePersistedRefreshToken?: boolean } = {},): Promise<void> {-- const releaseBoundary = beginAppSessionBoundary();-- notifyRendererAuthBoundaryPending();clearAuth({notify: false,++ nextMode: 'signed-out',preservePersistedRefreshToken: opts.preservePersistedRefreshToken,deferSessionCommit: true,});try {-- if (accountSwitchTeardown) {-- await accountSwitchTeardown({ previousUserId, nextUserId: 'signed-out' });-- } else {-- log.warn(-- 'runtime auth expiry teardown hook is not registered; falling back to localDb close',-- );-- }-- } catch (err) {-- // A teardown failure must not restore an expired credential. Continue with-- // the local DB close and signed-out notifications, while keeping evidence-- // for diagnosing the stale owner runtime.-- log.error('runtime auth expiry owner teardown failed', err);-- }-- try {-- closeLocalDb();++ await withAccountFreeOwnerCommit({++ reason,++ nextMode: 'signed-out',++ preservePersistedRefreshToken: opts.preservePersistedRefreshToken,++ notify: false,++ clearOnFailure: true,++ authAlreadyCleared: true,++ });} catch (err) {-- log.error('closeLocalDb on runtime auth expiry failed', err);++ // A teardown or durable-state failure must not restore an expired++ // credential. The helper has already cleared the in-memory owner; leave++ // the durable boundary non-stable for the next recovery attempt.++ log.error('runtime auth expiry owner transition failed', err);} finally {-- commitActiveAppSession('signed-out');-- releaseBoundary();notifyRenderer();notifyAuthListeners();notifySessionExpired(reason);@@@ -1556,38 -1556,38 +1761,28 @@@export function invalidateSession(reason: string): Promise<void> {if (sessionInvalidationPromise) return sessionInvalidationPromise;++ clearAuth({ notify: false, nextMode: 'signed-out', deferSessionCommit: true });++// Schedule teardown one microtask later so the single-flight promise can be// published and credentials can be cleared synchronously first. API calls// that detect the rejection may themselves run inside a scheduler/service// being torn down; they must be able to unwind without a stop-await cycle.-- const releaseBoundary = beginAppSessionBoundary();const run = Promise.resolve().then(async () => {try {-- if (authSessionTeardown) {-- await authSessionTeardown(reason);-- } else {-- log.warn(-- `auth session teardown hook is not registered for ${reason}; falling back to localDb close`,-- );-- }-- } catch (error) {-- log.error(`auth session teardown on ${reason} failed (non-fatal)`, error);-- }-- try {-- closeLocalDb();++ await withAccountFreeOwnerCommit({++ reason,++ nextMode: 'signed-out',++ notify: false,++ clearOnFailure: true,++ authAlreadyCleared: true,++ });} catch (error) {-- log.error(`closeLocalDb on ${reason} failed (non-fatal)`, error);-- } finally {-- commitActiveAppSession('signed-out');-- releaseBoundary();++ log.error(`auth session owner transition on ${reason} failed`, error);}++ notifyRenderer();++ notifyAuthListeners();});sessionInvalidationPromise = run;-- // Keep the current renderer surface in place until its session-expired-- // dialog is acknowledged. Main-process consumers still need the immediate-- // logged-out transition so no account-scoped work can restart meanwhile.-- clearAuth({ notify: false, deferSessionCommit: true });-- notifyAuthListeners();// invalidateSession 的 reason 是调用方语境串而非服务端失效码,这里只把// 「账号不可用」显式归类,其余统一走通用过期文案。notifySessionExpired(reason === 'account-unavailable' ? 'account-unavailable' : 'unknown');@@@ -1669,25 -1669,25 +1864,27 @@@ export function hasNoPersistedAuthCrede);}--/** Enter the account-free local session after the host has torn down old runtime state. */--export function enterLocalMode(): AuthState {++/** Enter the account-free local session through the shared projection boundary. */++export async function enterLocalMode(): Promise<AuthState> {browserAuthorizationSlot.cancelActive();// Local mode has a different data owner. Drop process-local generic OAuth// tokens before switching the committed owner so cloud credentials cannot// be reused by the account-free session.getProviderSecretStore().invalidateCaches();-- clearAuth({ notify: false, nextMode: 'local' });-- notifyRenderer();-- notifyAuthListeners();++ await withAccountFreeOwnerCommit({++ reason: 'enter-local-mode',++ nextMode: 'local',++ });return snapshotAuthState();}/** Leave local mode without deleting its owner-scoped data. */--export function exitLocalMode(): AuthState {++export async function exitLocalMode(): Promise<AuthState> {if (getActiveAppSession().mode !== 'local') return snapshotAuthState();-- clearAuth({ notify: false, nextMode: 'signed-out' });-- notifyRenderer();-- notifyAuthListeners();++ await withAccountFreeOwnerCommit({++ reason: 'exit-local-mode',++ nextMode: 'signed-out',++ });return snapshotAuthState();}@@@ -1817,7 -1817,7 +2014,9 @@@ export async function confirmAccountDelreceipt.authIdentity !== expectedIdentity ||receipt.realm !== activeAuthRealm) {-- removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);++ if (!isPassiveSharedUserDataInstance()) {++ removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);++ }throw new AuthApiError('ACCOUNT_DELETION_RECEIPT_MISSING',400,@@@ -1890,14 -1890,14 +2089,22 @@@ export function isConfirmedAccountDelet);}--export function clearLocalSessionAfterAccountDeletion(): boolean {++export async function clearLocalSessionAfterAccountDeletion(): Promise<boolean> {if (!isConfirmedAccountDeletionSessionCurrent()) return false;-- try {-- closeLocalDb();-- } catch (error) {-- log.error('closeLocalDb after account deletion failed', error);-- }-- clearAuth();++ const expectedCredential = confirmedAccountDeletionCredential;++ await withAccountFreeOwnerCommit({++ reason: 'account-deletion',++ nextMode: 'signed-out',++ clearOnFailure: true,++ validateBeforeCommit: () =>++ expectedCredential !== null &&++ confirmedAccountDeletionCredential === expectedCredential &&++ isConfirmedAccountDeletionSessionCurrent(),++ shouldClearOnFailure: () =>++ expectedCredential !== null &&++ confirmedAccountDeletionCredential === expectedCredential &&++ isConfirmedAccountDeletionSessionCurrent(),++ });return true;}@@@ -1982,6 -1982,6 +2189,7 @@@ export async function initialize(option// Local mode is a committed account-free session. It must win before any// persisted cloud refresh token is inspected or any auth network call runs.if (getActiveAppSession().mode === 'local') {++ await recoverAccountFreeOwnerAtStartup('local', 'cold-start-local-recovery');return snapshotAuthState();}// 进程内已登录快路径:auth 状态是 main 进程全局的,主窗登录后其它 renderer@@@ -1992,7 -1992,7 +2200,25 @@@// 冷启动时 accessToken/currentUser 必为空,不影响下方完整初始化流程// (relogin marker 消费、持久化 refresh_token 校验)。if (accessToken && currentUser) {-- commitActiveAppSession('cloud', currentUser.id);++ if (!isGhostSkillProjectionBoundaryStableForOwner(currentUser.id)) {++ const previousSession = getActiveAppSession();++ await withCloudOwnerCommit({++ previousOwnerId: previousSession.dataOwnerId,++ nextOwnerId: currentUser.id,++ prepareTransition: async () => {++ if (!accountSwitchTeardown) {++ throw new Error('active cloud owner recovery requires a teardown hook');++ }++ await accountSwitchTeardown({++ previousUserId: previousSession.dataOwnerId ?? previousSession.mode,++ nextUserId: currentUser!.id,++ });++ },++ commit: () => commitCloudAppSession(currentUser!.id),++ });++ } else {++ commitCloudAppSession(currentUser.id);++ }return snapshotAuthState();}@@@ -2000,7 -2000,7 +2226,7 @@@// (副窗 mount / renderer reload 都会走到这里)。直到显式登录或进程重启为止。if (passiveLocalSignOut) {log.info('passive shared-userData instance stays signed out locally (tombstone)');-- commitActiveAppSession('signed-out');++ commitVolatileAppSession('signed-out');return snapshotLoggedOutAuthState();}@@@ -2026,7 -2026,7 +2252,7 @@@reloginFlag.version,);passiveLocalSignOut = true;-- commitActiveAppSession('signed-out');++ commitVolatileAppSession('signed-out');return snapshotLoggedOutAuthState();}log.info(@@@ -2040,8 -2040,8 +2266,7 @@@removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);removeSafe(LEGACY_REFRESH_TOKEN_KEY);clearReloginFlag();-- commitActiveAppSession('signed-out');-- return snapshotLoggedOutAuthState();++ return finishColdStartSignedOut('cold-start-relogin-required');}// Old Feishu-auth refresh tokens are intentionally not portable to auth-server.@@@ -2069,8 -2069,8 +2294,7 @@@}}if (!persistedSession) {-- commitActiveAppSession('signed-out');-- return snapshotLoggedOutAuthState();++ return finishColdStartSignedOut('cold-start-no-persisted-session');}try {await loadClientEndpointsForRealm(persistedSession.realm);@@@ -2078,8 -2078,8 +2302,7 @@@// 对端区域清单暂不可用时保留原子凭据;退回构建区 refresh 会把有效 token// 当成非法凭据,因此本次仅以未登录放行 UI,下一次 initialize/重启可重试。log.warn('persisted auth realm manifest unavailable; keeping session for retry', error);-- commitActiveAppSession('signed-out');-- return snapshotLoggedOutAuthState();++ return finishColdStartSignedOut('cold-start-realm-manifest-unavailable');}const storedToken = persistedSession.refreshToken;@@@ -2097,10 -2097,10 +2320,17 @@@const coldStartCompletion = coldStartAuthInFlight;return awaitWithStartupTimeout(coldStartCompletion, {timeoutMs: COLD_START_AUTH_GATE_TIMEOUT_MS,-- onTimeout: () => {++ onTimeout: async () => {options.onColdStartPending?.(coldStartCompletion);log.warn(-- `cold-start auth still pending after ${COLD_START_AUTH_GATE_TIMEOUT_MS}ms — unblocking startup as logged out, flow continues in background`,++ `cold-start auth still pending after ${COLD_START_AUTH_GATE_TIMEOUT_MS}ms — recovering the account-free projection before startup continues`,++ );++ // A signed-out fallback is not safe until the shared Ghost projection++ // has been swept. Otherwise the previous cloud owner's links remain++ // available to local/anonymous Agent processes during a slow refresh.++ await recoverAccountFreeOwnerAtStartup(++ 'signed-out',++ 'cold-start-timeout-recovery',);return snapshotLoggedOutAuthState();},@@@ -2123,7 -2123,7 +2353,6 @@@ async function runColdStartRefreshFlowstoredRealm: AuthRegion,): Promise<AuthState> {const epochAtStart = authStateEpoch;-- let releaseBoundary: (() => void) | null = null;const epochChanged = (point: string): boolean => {if (authStateEpoch === epochAtStart) return false;log.warn(@@@ -2166,8 -2166,8 +2395,7 @@@// 共享 userData 的另一个实例已切到其它区域。旧区域请求无论成功失败都不能// 覆盖/删除新原子记录;本实例本次以未登录返回,后续 initialize 可加载新清单。log.warn('cold-start auth realm changed on disk; discarding stale refresh result');-- commitActiveAppSession('signed-out');-- return snapshotLoggedOutAuthState();++ return finishColdStartSignedOut('cold-start-realm-changed');}if (!refreshResult.ok) {// 只在「确定性凭据失效」时清除 token。429 限流 / 5xx / 断网等瞬时失败保留 token,@@@ -2201,8 -2201,8 +2429,7 @@@`cold-start refresh still failing after ${attempts} attempt(s) — keeping refresh token, starting logged out`,);}-- commitActiveAppSession('signed-out');-- return snapshotLoggedOutAuthState();++ return finishColdStartSignedOut(`cold-start-refresh-${action.kind}`);}const refreshData = refreshResult.data as RefreshResponse;@@@ -2216,48 -2216,48 +2443,50 @@@log.warn(`cold-start refresh rejected cross-realm personal session realm=${storedRealm} buildRegion=${AUTH_REGION}`,);-- commitActiveAppSession('signed-out');-- return snapshotLoggedOutAuthState();-- }-- if (accountSwitchTeardown) {-- // Cold-start refresh may outlive initialize()'s startup timeout. Keep-- // the owner boundary held for the entire late commit sequence so stale-- // IPC cannot reopen the previous owner's database while teardown,-- // namespace claiming, and session publication are still in flight.-- releaseBoundary = beginAppSessionBoundary();-- await accountSwitchTeardown({-- previousUserId: getActiveAppSession().dataOwnerId ?? 'signed-out',-- nextUserId: refreshData.membership.id,-- });-- if (epochChanged('after-cold-start-teardown')) {-- releaseBoundary();-- releaseBoundary = null;-- return snapshotAuthState();-- }-- }-- await claimLegacyNamespaceForVerifiedUser(refreshData.membership.id);-- if (epochChanged('after-owner-namespace-claim')) {-- releaseBoundary?.();-- releaseBoundary = null;-- return snapshotAuthState();-- }-- if (storedRealm !== activeAuthRealm) {-- activateClientEndpointRealm(storedRealm);-- activeAuthRealm = storedRealm;++ return finishColdStartSignedOut('cold-start-incompatible-membership');}++ // Refresh is token-rotating. Preserve the server-issued replacement before++ // the cross-process projection gate can reject or defer the owner commit.writePersistedAuthSession(refreshData.refreshToken, storedRealm);lastAcceptedRefreshToken = refreshData.refreshToken;---- accessToken = refreshData.accessToken;-- // 2026-07 起身份完全以 auth membership 为准(产品 /api/user/me 已退役)。-- currentUser = mapMembershipToAuthUser(refreshData.membership);-- commitActiveAppSession('cloud', currentUser.id);-- persistedRefreshTokenNeedsIdentityCheck = false;-- clearReplacementIntegrationReloadTimers();++ const previousSession = getActiveAppSession();++ await withCloudOwnerCommit({++ previousOwnerId: previousSession.dataOwnerId,++ nextOwnerId: refreshData.membership.id,++ prepareTransition: async () => {++ if (!accountSwitchTeardown) {++ throw new Error('cold-start cloud owner transition requires a teardown hook');++ }++ await accountSwitchTeardown({++ previousUserId: previousSession.dataOwnerId ?? previousSession.mode,++ nextUserId: refreshData.membership.id,++ });++ if (epochChanged('after-cold-start-teardown')) {++ throw new Error('cold-start cloud owner transition was superseded');++ }++ },++ prepareCommit: async () => {++ await claimLegacyNamespaceForVerifiedUser(refreshData.membership.id);++ if (epochChanged('after-owner-namespace-claim')) {++ throw new Error('cold-start cloud owner commit was superseded');++ }++ },++ commit: () => {++ if (storedRealm !== activeAuthRealm) {++ activateClientEndpointRealm(storedRealm);++ activeAuthRealm = storedRealm;++ }++ accessToken = refreshData.accessToken;++ currentUser = mapMembershipToAuthUser(refreshData.membership);++ commitCloudAppSession(currentUser.id);++ persistedRefreshTokenNeedsIdentityCheck = false;++ clearReplacementIntegrationReloadTimers();++ },++ });scheduleCanaryFlagSync({token: refreshData.accessToken,expectedAuthEpoch: epochAtStart,-- expectedUserId: currentUser.id,++ expectedUserId: refreshData.membership.id,});scheduleRefresh(refreshData.accessToken);// XD / Mivo key 均为本地 only,不再在冷启动从服务器同步到本地。@@@ -2269,8 -2269,8 +2498,6 @@@// 广播拿到冷启动状态——不广播就永远收不到 auto-login 事件。notifyRenderer();notifyAuthListeners();-- releaseBoundary?.();-- releaseBoundary = null;return snapshotAuthState();} catch (err) {// 网络类失败都在 apiFetch 内部消化(返回 status 0),能走到这里的是 refresh 成功@@@ -2291,10 -2291,10 +2518,9 @@@}resetActiveAuthRealmToBuild();}-- releaseBoundary?.();-- releaseBoundary = null;-- if (!epochChanged('catch-return')) commitActiveAppSession('signed-out');-- return epochChanged('catch-return-state') ? snapshotAuthState() : snapshotLoggedOutAuthState();++ if (epochChanged('catch-return')) return snapshotAuthState();++ await finishColdStartSignedOut('cold-start-local-state-sync-failed');++ return snapshotLoggedOutAuthState();}}@@@ -2363,28 -2363,28 +2589,7 @@@ async function completeLoginoutcome.accountDeletionRestored === true || pendingAccountDeletionRestored;const nextUser = mapMembershipToAuthUser(outcome.membership);const previousSession = getActiveAppSession();-- let releaseBoundary: (() => void) | null = null;-- if (previousSession.dataOwnerId !== nextUser.id) {-- releaseBoundary = beginAppSessionBoundary();-- try {-- if (accountSwitchTeardown) {-- await accountSwitchTeardown({-- previousUserId: previousSession.dataOwnerId ?? previousSession.mode,-- nextUserId: nextUser.id,-- });-- } else {-- closeLocalDb();-- }-- } catch (err) {-- releaseBoundary();-- releaseBoundary = null;-- throw err;-- }-- }-- // legacy 飞书集成清理已随主机 token 链退役(2026-07-17):这里不再有登录前-- // 的异步清理窗口,epoch 守卫保留给未来在提交前重新引入 await 的改动兜底。if (authStateEpoch !== loginEpoch) {-- releaseBoundary?.();throw new AuthApiError('AUTH_FLOW_SUPERSEDED',409,@@@ -2392,50 -2392,50 +2597,65 @@@);}-- try {-- await claimLegacyNamespaceForVerifiedUser(nextUser.id);-- } catch (error) {-- // The boundary must not remain pending if legacy namespace claiming fails.-- releaseBoundary?.();-- releaseBoundary = null;-- throw error;-- }-- if (authStateEpoch !== loginEpoch) {-- releaseBoundary?.();-- throw new AuthApiError(-- 'AUTH_FLOW_SUPERSEDED',-- 409,-- 'Login was superseded by a newer auth action',-- );-- }---- try {-- pendingAccountToken = null;-- pendingAccountDeletionRestored = false;-- accessToken = outcome.accessToken;-- persistedRefreshTokenNeedsIdentityCheck = false;-- clearReplacementIntegrationReloadTimers();-- const committedRealm = pendingAuthRealm ?? AUTH_REGION;-- activateClientEndpointRealm(committedRealm);-- activeAuthRealm = committedRealm;-- writePersistedAuthSession(outcome.refreshToken, committedRealm);-- removeSafe(LEGACY_REFRESH_TOKEN_KEY);-- lastAcceptedRefreshToken = outcome.refreshToken;-- removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);-- accountDeletionRestoredNoticePending = deletionWasRestored;-- clearReloginFlag();-- // 显式登录解除 passive 本地登出墓碑(见 passiveLocalSignOut)。-- passiveLocalSignOut = false;-- currentUser = nextUser;-- commitActiveAppSession('cloud', currentUser.id);-- pendingAuthRealm = null;-- } finally {-- releaseBoundary?.();-- }++ const committedRealm = pendingAuthRealm ?? AUTH_REGION;++ await withCloudOwnerCommit({++ previousOwnerId: previousSession.dataOwnerId,++ nextOwnerId: nextUser.id,++ prepareTransition: async () => {++ if (!accountSwitchTeardown) {++ throw new Error('login cloud owner transition requires a teardown hook');++ }++ await accountSwitchTeardown({++ previousUserId: previousSession.dataOwnerId ?? previousSession.mode,++ nextUserId: nextUser.id,++ });++ },++ prepareCommit: async () => {++ if (authStateEpoch !== loginEpoch) {++ throw new AuthApiError(++ 'AUTH_FLOW_SUPERSEDED',++ 409,++ 'Login was superseded by a newer auth action',++ );++ }++ await claimLegacyNamespaceForVerifiedUser(nextUser.id);++ if (authStateEpoch !== loginEpoch) {++ throw new AuthApiError(++ 'AUTH_FLOW_SUPERSEDED',++ 409,++ 'Login was superseded by a newer auth action',++ );++ }++ },++ commit: () => {++ pendingAccountToken = null;++ pendingAccountDeletionRestored = false;++ accessToken = outcome.accessToken;++ persistedRefreshTokenNeedsIdentityCheck = false;++ clearReplacementIntegrationReloadTimers();++ activateClientEndpointRealm(committedRealm);++ activeAuthRealm = committedRealm;++ writePersistedAuthSession(outcome.refreshToken, committedRealm);++ if (!isPassiveSharedUserDataInstance()) {++ removeSafe(LEGACY_REFRESH_TOKEN_KEY);++ }++ lastAcceptedRefreshToken = outcome.refreshToken;++ if (!isPassiveSharedUserDataInstance()) {++ removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);++ clearReloginFlag();++ }++ accountDeletionRestoredNoticePending = deletionWasRestored;++ // 显式登录解除 passive 本地登出墓碑(见 passiveLocalSignOut)。++ passiveLocalSignOut = false;++ currentUser = nextUser;++ commitCloudAppSession(currentUser.id);++ pendingAuthRealm = null;++ },++ });scheduleCanaryFlagSync({token: outcome.accessToken,expectedAuthEpoch: loginEpoch,-- expectedUserId: currentUser.id,++ expectedUserId: nextUser.id,});scheduleRefresh(outcome.accessToken);getProviderSecretStore().reconcileOwner(outcome.membership.id);@@@ -2452,7 -2452,7 +2672,9 @@@ async function acceptLoginOutcome(outcoif (outcome.status === 'ok' || outcome.status === 'select_account') {// Membership selection already establishes which passport owns the new// login. A receipt from the previous login must not survive this boundary.-- removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);++ if (!isPassiveSharedUserDataInstance()) {++ removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);++ }}if ((outcome.status === 'ok' || outcome.status === 'select_account') &&@@@ -2944,10 -2944,10 +3166,17 @@@ export async function refresh(): Promis});} else {resetActiveAuthRealmToBuild();-- commitActiveAppSession('signed-out');++ await recoverAccountFreeOwnerAtStartup(++ 'signed-out',++ 'runtime-incompatible-membership',++ );}return false;}++ // Refresh is token-rotating. Preserve the replacement before any owner++ // projection transition can defer this process.++ writePersistedAuthSession(data.refreshToken, refreshRealm);++ lastAcceptedRefreshToken = data.refreshToken;const needsIdentityCheck =replacementRetries > 0 ||persistedRefreshTokenNeedsIdentityCheck ||@@@ -2957,73 -2957,73 +3186,47 @@@// instance. Verify / reconcile the account before accepting its access token,// otherwise renderer state could still show account A while API calls use B.persistedRefreshTokenNeedsIdentityCheck = true;-- writePersistedAuthSession(data.refreshToken, refreshRealm);-- lastAcceptedRefreshToken = data.refreshToken;--const previousUserId = currentUser?.id ?? null;const nextUser = mergeMembershipWithExisting(data.membership, currentUser);const accountSwitched = previousUserId !== null && previousUserId !== nextUser.id;-- let releaseBoundary: (() => void) | null = null;if (accountSwitched) {log.warn(`runtime replacement refresh switched authenticated user from ${previousUserId} to ${nextUser.id}; reconciling auth state`,);-- notifyRendererAuthBoundaryPending();-- releaseBoundary = beginAppSessionBoundary();-- try {-- if (accountSwitchTeardown) {-- await accountSwitchTeardown({ previousUserId, nextUserId: nextUser.id });-- } else {-- log.warn(-- 'runtime replacement account switch teardown hook is not registered; falling back to localDb close only',-- );-- }-- closeLocalDb();-- } catch (err) {-- releaseBoundary();-- releaseBoundary = null;-- log.error('runtime replacement account switch teardown failed', err);-- notifyRenderer();-- scheduleRefreshRetryAfterTransientFailure();-- return false;-- }-- if (refreshWasSuperseded('after-account-switch-teardown')) {-- releaseBoundary();-- return false;-- }}---- if (accountSwitched) {-- try {++ await withCloudOwnerCommit({++ previousOwnerId: getActiveAppSession().dataOwnerId,++ nextOwnerId: nextUser.id,++ prepareTransition: async () => {++ if (!accountSwitchTeardown) {++ throw new Error('runtime cloud owner transition requires a teardown hook');++ }++ await accountSwitchTeardown({++ previousUserId: previousUserId ?? getActiveAppSession().mode,++ nextUserId: nextUser.id,++ });++ if (refreshWasSuperseded('after-account-switch-teardown')) {++ throw new Error('runtime cloud owner transition was superseded');++ }++ },++ prepareCommit: async () => {await claimLegacyNamespaceForVerifiedUser(nextUser.id);-- } catch (err) {-- // Namespace claiming is still inside the owner boundary. Always-- // release it before retrying so a failed claim cannot permanently-- // block all owner-bound IPC work.-- releaseBoundary?.();-- releaseBoundary = null;-- throw err;-- }-- if (refreshWasSuperseded('after-owner-namespace-claim')) {-- releaseBoundary?.();-- releaseBoundary = null;-- return false;-- }-- }---- if (authRealmChanged) {-- activateClientEndpointRealm(refreshRealm);-- activeAuthRealm = refreshRealm;-- }-- accessToken = data.accessToken;-- currentUser = nextUser;-- try {-- commitActiveAppSession('cloud', currentUser.id);-- } finally {-- releaseBoundary?.();-- }++ if (refreshWasSuperseded('after-owner-namespace-claim')) {++ throw new Error('runtime cloud owner commit was superseded');++ }++ },++ commit: () => {++ if (authRealmChanged) {++ activateClientEndpointRealm(refreshRealm);++ activeAuthRealm = refreshRealm;++ }++ accessToken = data.accessToken;++ currentUser = nextUser;++ commitCloudAppSession(currentUser.id);++ },++ });persistedRefreshTokenNeedsIdentityCheck = false;-- getProviderSecretStore().reconcileOwner(currentUser.id);++ getProviderSecretStore().reconcileOwner(nextUser.id);if (accountSwitched) {try {await clearPerAccountIntegrations();@@@ -3035,31 -3035,31 +3238,45 @@@);}if (refreshWasSuperseded('after-integration-reload')) return false;-- scheduleReplacementIntegrationReloadRetries(currentUser.id);++ scheduleReplacementIntegrationReloadRetries(nextUser.id);}scheduleCanaryFlagSync({token: data.accessToken,expectedAuthEpoch: refreshEpoch,-- expectedUserId: currentUser.id,++ expectedUserId: nextUser.id,});scheduleRefresh(data.accessToken);notifyRenderer();-- if (previousUserId !== currentUser.id || authRealmChanged) {++ if (previousUserId !== nextUser.id || authRealmChanged) {notifyAuthListeners();}return true;}-- if (authRealmChanged) {-- activateClientEndpointRealm(refreshRealm);-- activeAuthRealm = refreshRealm;-- }-- accessToken = data.accessToken;-- currentUser = mergeMembershipWithExisting(data.membership, currentUser);-- commitActiveAppSession('cloud', currentUser.id);++ const nextUser = mergeMembershipWithExisting(data.membership, currentUser);++ await withCloudOwnerCommit({++ previousOwnerId: getActiveAppSession().dataOwnerId,++ nextOwnerId: nextUser.id,++ prepareTransition: async () => {++ if (!accountSwitchTeardown) {++ throw new Error('runtime cloud owner transition requires a teardown hook');++ }++ await accountSwitchTeardown({++ previousUserId: getActiveAppSession().dataOwnerId ?? getActiveAppSession().mode,++ nextUserId: nextUser.id,++ });++ },++ commit: () => {++ if (authRealmChanged) {++ activateClientEndpointRealm(refreshRealm);++ activeAuthRealm = refreshRealm;++ }++ accessToken = data.accessToken;++ currentUser = nextUser;++ commitCloudAppSession(currentUser.id);++ },++ });persistedRefreshTokenNeedsIdentityCheck = false;-- writePersistedAuthSession(data.refreshToken);-- lastAcceptedRefreshToken = data.refreshToken;scheduleRefresh(data.accessToken);notifyRenderer();if (authRealmChanged) {@@@ -3086,16 -3086,16 +3303,9 @@@export async function logout(): Promise<void> {const currentAccessToken = accessToken;const currentAuthBaseUrl = authServerUrl(activeAuthRealm);-- // 注意:真实登出入口(bootstrap auth:logout handler)在调用本函数**之前**已-- // dispose DbClient 并释放 device-link 持有权(releaseDeviceLinkOwnershipBeforeLogout);-- // 需要在 DB 关闭前收尾写入的逻辑应挂在那条链路上,而不是本函数内(此时已太晚)。-- // chat-data-localization: drop the per-user db connection so the next-- // login (potentially a different user) opens a fresh file via ensureReady.-- try {-- closeLocalDb();-- } catch (err) {-- log.error('closeLocalDb on logout failed', err);-- }++ // The shared projection state machine owns the full teardown and only then++ // publishes the signed-out owner. The bootstrap IPC handler must not wrap a++ // second independent boundary around this transition.// Ordinary logout abandons an unconfirmed challenge. Confirmed deletion uses// clearLocalSessionAfterAccountDeletion() and intentionally preserves receipt.//@@@ -3108,7 -3108,7 +3318,16 @@@} else {clearAccountDeletionReceipt();}-- clearAuth();++ let localTransitionError: unknown = null;++ try {++ await withAccountFreeOwnerCommit({++ reason: 'logout',++ nextMode: 'signed-out',++ clearOnFailure: true,++ });++ } catch (error) {++ localTransitionError = error;++ }// passive 共享实例跳过服务端登出:refresh token 按 (user, device) 一对一存,而它与// primary 共用同一 deviceId——调这一发会把 primary 的那份一起作废,即使本地文件留着,@@@ -3121,6 -3121,6 +3340,7 @@@baseUrl: currentAuthBaseUrl,}).catch(() => {});}++ if (localTransitionError) throw localTransitionError;}/**diff --cc apps/desktop/src/main/authStartupGate.tsindex 6e4c5cbc26,6e4c5cbc26..86876fe2a6--- a/apps/desktop/src/main/authStartupGate.ts+++ b/apps/desktop/src/main/authStartupGate.ts@@@ -18,7 -18,7 +18,7 @@@ export interface StartupTimeoutOpts<T>/** 超时毫秒数;<= 0 表示不设限(退化为直接 await flow)。 */timeoutMs: number;/** 超时触发时生成兜底返回值(典型:未登录 AuthState)。 */-- onTimeout: () => T;++ onTimeout: () => T | PromiseLike<T>;/** 超时后原 flow 迟到 resolve 时回调(不会在未超时时调用)。 */onLateResult?: (result: T) => void;/** 超时后原 flow 迟到 reject 时回调;不注册也会消化 rejection。 */@@@ -40,10 -40,10 +40,16 @@@ export async function awaitWithStartupTlet timedOut = false;let timer: ReturnType<typeof setTimeout> | undefined;-- const timeout = new Promise<T>((resolve) => {++ const timeout = new Promise<T>((resolve, reject) => {timer = setTimeout(() => {timedOut = true;-- resolve(opts.onTimeout());++ try {++ // Promise resolution assimilates an async recovery fallback while++ // keeping synchronous fallback callbacks backwards-compatible.++ resolve(opts.onTimeout());++ } catch (error) {++ reject(error);++ }}, opts.timeoutMs);});diff --cc apps/desktop/src/main/bootstrap-electron.tsindex 5def450d97,55d0228aa4..d1a7f6072a--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@@ -1011,7 -1021,10 +1022,57 @@@ async function ensureLifecycleDbClient(});}++const AUTH_BOUNDARY_WAIT_TIMEOUT_MS = 10_000;++++async function withAuthBoundaryTimeout<T>(label: string, task: () => Promise<T>): Promise<T> {++ let timer: ReturnType<typeof setTimeout> | null = null;++ try {++ return await Promise.race([++ task(),++ new Promise<T>((_resolve, reject) => {++ timer = setTimeout(() => {++ reject(new Error(`${label} timed out after ${AUTH_BOUNDARY_WAIT_TIMEOUT_MS}ms`));++ }, AUTH_BOUNDARY_WAIT_TIMEOUT_MS);++ timer.unref?.();++ }),++ ]);++ } finally {++ if (timer) clearTimeout(timer);++ }++}++++async function teardownGhostProjectionBoundary(reason: string): Promise<void> {++ const failures: unknown[] = [];++ const run = async (label: string, task: () => Promise<void>): Promise<void> => {++ try {++ await task();++ } catch (error) {++ failures.push(error);++ authBoundaryLog.error(`${label} on ${reason} failed`, error);++ }++ };++++ await run('interruptGhostCallsForAccountBoundary', () =>++ withAuthBoundaryTimeout('interrupt Ghost calls', interruptGhostCallsForAccountBoundary));++ await run('waitForGhostMutations', () =>++ withAuthBoundaryTimeout('wait for Ghost mutations', waitForGhostMutations));++ await run('suspendAllGhosts', suspendAllGhosts);++++ if (failures.length > 0) {++ throw new AggregateError(failures, `Ghost projection teardown on ${reason} was incomplete`);++ }++}++async function teardownAuthAccountBoundary(reason: string): Promise<void> {++ const blockingFailures: unknown[] = [];+ // The boundary is already marked pending by every caller. New actions now+ // fail closed; drain an action that crossed the boundary before closing its DB.- await waitForTurnChangeSetActions();++ try {++ await withAuthBoundaryTimeout('wait for turn change-set actions', waitForTurnChangeSetActions);++ } catch (error) {++ blockingFailures.push(error);++ authBoundaryLog.error(`waitForTurnChangeSetActions on ${reason} failed`, error);++ }skillhubAutoSyncService.cancelInFlight();// Custom provider routes are owner-scoped but the active catalog is process-global.// Clear synchronously at the boundary; the next owner's tracked readiness reloads them@@@ -1058,9 -1071,8 +1119,11 @@@// Every Ghost sandbox can retain live OAuth, subscription, or in-memory// state. Stop them before changing owners; resident Ghosts are recreated by// the auth-change activation pass after the new boundary is committed.- await interruptGhostCallsForAccountBoundary();-- await waitForGhostMutations();- await suspendAllGhosts();- suspendAllGhosts();++ try {++ await teardownGhostProjectionBoundary(reason);++ } catch (error) {++ blockingFailures.push(error);++ }// 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.@@@ -1152,14 -1164,14 +1215,28 @@@err,);}-- await lifecycleDbClientManager.dispose(reason);-- agentIslandService?.resetRuntimeState();++ try {++ await lifecycleDbClientManager.dispose(reason);++ } finally {++ try {++ localDbCloseDb();++ } catch (error) {++ blockingFailures.push(error);++ authBoundaryLog.error(`close local DB on ${reason} failed`, error);++ }++ agentIslandService?.resetRuntimeState();++ }++++ if (blockingFailures.length > 0) {++ throw new AggregateError(blockingFailures, `account boundary teardown on ${reason} was incomplete`);++ }}authManager.setAccountSwitchTeardown(async () => {await teardownAuthAccountBoundary('runtime-replacement-account-switch');});authManager.setAuthSessionTeardown(teardownAuthAccountBoundary);++authManager.setProjectionRepairTeardown(teardownGhostProjectionBoundary);try {reapClaudeOrphansSync();@@@ -3887,13 -3904,13 +3969,7 @@@ const registerIpcHandlers = () =>});ipcMain.handle('auth:logout', async () => {-- const releaseBoundary = beginAppSessionBoundary();-- try {-- await teardownAuthAccountBoundary('logout');-- await authManager.logout();-- } finally {-- releaseBoundary();-- }++ await authManager.logout();});ipcMain.handle('auth:enter-local', async () => {@@@ -3901,26 -3918,26 +3977,14 @@@return authManager.getAuthState();}await authManager.waitForSessionInvalidation();-- const releaseBoundary = beginAppSessionBoundary();-- try {-- await teardownAuthAccountBoundary('enter-local-mode');-- return authManager.enterLocalMode();-- } finally {-- releaseBoundary();-- }++ return authManager.enterLocalMode();});ipcMain.handle('auth:exit-local', async () => {if (getActiveAppSession().mode !== 'local') {throwIpcError('PRECONDITION_FAILED', 'Local mode is not active.');}-- const releaseBoundary = beginAppSessionBoundary();-- try {-- await teardownAuthAccountBoundary('exit-local-mode');-- return authManager.exitLocalMode();-- } finally {-- releaseBoundary();-- }++ return authManager.exitLocalMode();});ipcMain.handle('auth:refresh', async () => {@@@ -3940,8 -3957,7 +4004,6 @@@clearReceipt: () => authManager.clearAccountDeletionReceipt(),consumeRestoredNotice: () => authManager.consumeAccountDeletionRestoredNotice(),isConfirmedLocalSessionCurrent: () => authManager.isConfirmedAccountDeletionSessionCurrent(),- beginAccountBoundary: beginAppSessionBoundary,-- teardownAccountBoundary: () => teardownAuthAccountBoundary('account-deletion'),clearLocalSession: () => authManager.clearLocalSessionAfterAccountDeletion(),logWarn: (message, error) => accountDeletionLog.warn(message, error),});diff --cc apps/desktop/src/main/cindy-brain/GhostManager.tsindex e21ed9a7cb,f6276bc7e5..d802f7a49d--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@@ -52,47 -36,7 +52,51 @@@ importexport 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 = GHOST_INSTALL_MANIFEST_MAX_BYTES;+const MAX_GHOST_MANIFEST_BYTES = GHOST_MANIFEST_MAX_BYTES;++async function readRegularFileStableWithLimit(+ filePath: string,+ maxBytes: number,+): Promise<Buffer> {+ // 顶层 .cindy 路径允许是用户选择的 symlink;确认前后由整包 sha256 对账,+ // 单次读取则始终绑定同一个已打开句柄,避免 stat/read 的二次解析窗口。- const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY);++ const handle = await fs.promises.open(++ filePath,++ fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0),++ );+ try {+ const opened = await handle.stat();- if (!opened.isFile() || opened.isSymbolicLink()) {++ if (!opened.isFile()) {+ 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 &&++ after.ctimeMs === opened.ctimeMs &&+ ((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 的载荷体积。+ */+const MAX_GHOST_ICON_BYTES = 512 * 1024; // 512 KB/** 解压后总大小/条目数上限;Node 包允许携带已打包 CLI,但仍有硬闸。 */export const MAX_BASIC_UNCOMPRESSED_BYTES = 32 * 1024 * 1024;export const MAX_NODE_UNCOMPRESSED_BYTES = 256 * 1024 * 1024;@@@ -100,1587 -44,63 +104,1745 @@@ export const MAX_BASIC_ZIP_ENTRIES = 25export const MAX_NODE_ZIP_ENTRIES = 2_048;/** 停用标记文件名(安装目录内;存在即停用)。 */const DISABLED_MARKER_FILE = '.disabled';--/** 安装时由主机写入的信任快照与权限 receipt;作者包不能提供。 */++/** 宿主保留的安装信任镜像文件名;插件包不得自行携带。 */const TRUST_METADATA_FILE = '.cindy-trust.json';--interface GhostInstalledHostMetadata {- trust: GhostTrustInfo;- /** Legacy receipt retained only for backward-compatible metadata reads. */- approvedAtResourceProviderTool?: string;- }-+/** 注入式日志接口 —— manager 不直接依赖 main/logger,单测零 electron。 */+export interface GhostManagerLogger {+ info(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ /** 可选:仅用于"本该收敛却失败"的状态(如撤销批准失败后转进程内隔离)。 */+ error?(message: string, meta?: Record<string, unknown>): void;+}++export interface GhostManagerOptions {+ /** 意识仓库根目录(生产:userData/cindy-brain;测试:os.tmpdir 下临时目录)。 */+ getRootDir: () => string;+ /** Host 批准状态根;必须位于插件安装根之外。 */+ getStateDir?: () => string;+ /**+ * 当前 owner 的稳定代际键。生产接线使用 activeOwnerScopeKey,使同一账号被重新+ * commit 时也能使排队中的旧 mutation 失效;测试可只依赖动态 content/state root。+ */+ getOwnerContextKey?: () => string;+ /** 装/卸成功后通知(index.ts 用它广播 ghosts:changed 到所有窗口)。 */+ onChanged?: (ghosts: InstalledGhost[]) => void;+ /** 当前宿主语言;插件未提供时由 shared 契约固定回退英文。 */+ getLocale?: () => string;+ /**+ * `approveTrustedBundledInstall` 的 builtin-only 边界:id 是否对应一颗随包种子。+ * 该入口不经用户确认就铸出批准,因此 id 与 source 都必须由生产接线明确放行。+ */+ isTrustedBundledId?: (id: string) => boolean;+ /** sourceDir 是否就是该 id 的随包只读种子目录,而非任意本机可变目录。 */+ isTrustedBundledSource?: (id: string, sourceDir: string) => boolean;+ /** Persist the user's builtin-uninstall intent before approval/content removal. */+ recordBuiltinTombstone?: (id: string) => void;+ /** Complete a user-initiated builtin restore before the install journal commits. */+ clearBuiltinTombstone?: (id: string) => void;+ /** Cindy 维护的发布者/审核公钥表;缺省为空,签名仍验完整性但不抬身份等级。 */+ trustRegistry?: GhostTrustRegistry;+ log?: GhostManagerLogger;+}++/** install / update 的失败分类 —— IPC 层据此映射错误码。 */+export type InstallRejection =+ | { code: 'source-not-found'; reason: string }+ | { code: 'file-invalid'; reason: string }+ | { code: 'already-installed'; reason: string }+ | { code: 'not-installed'; reason: string }+ | { code: 'command-conflict'; reason: string }+ | { code: 'state-changed'; reason: string }+ | {+ code: 'io';+ reason: string;+ /**+ * 更新失败后连旧版本目录都没能滚回原位(Windows 文件锁/AV 等):此时安装目录+ * 可能是新字节或缺失,调用方**不得**按"旧版本还在"重启运行时。+ */+ rollbackFailed?: boolean;+ };++export type UninstallRejection =+ | { code: 'invalid-id'; reason: string }+ | { code: 'not-installed'; reason: string }+ | { code: 'approval-required'; reason: string }+ | { code: 'io'; reason: string };++export type UninstallResult = { ok: true } | { rejection: UninstallRejection };++export interface GhostUninstallOptions {+ notify?: boolean;+ /**+ * User-initiated removal records a builtin tombstone by default. Host+ * reconciliation may explicitly skip it when removing a currently ineligible+ * seed; that is lifecycle cleanup, not a durable user uninstall decision.+ */+ recordBuiltinTombstone?: boolean;+}++interface InstalledReapprovalProjection {+ manifest: GhostManifest;trust: GhostTrustInfo;- /** Legacy receipt retained only for backward-compatible metadata reads. */- approvedAtResourceProviderTool?: string;+ localeResources: Record<string, GhostManifestLocaleResource>;+ iconDataUrl?: string;+ skillContentSha256: Record<string, string>;+}+++export interface LegacyGhostApprovalProjection {++ manifest: GhostManifest;++ enabled: boolean;++ trust: GhostTrustInfo;++ localeResources: Record<string, GhostManifestLocaleResource>;++ iconDataUrl?: string;++ skillContentSha256: Record<string, string>;++}++++export function hashLegacyGhostApprovalProjection(++ projection: LegacyGhostApprovalProjection,++): string {++ return crypto++ .createHash('sha256')++ .update(++ JSON.stringify({++ version: 1,++ manifest: projection.manifest,++ enabled: projection.enabled,++ trust: projection.trust,++ localeResources: projection.localeResources,++ iconDataUrl: projection.iconDataUrl ?? null,++ skillContentSha256: projection.skillContentSha256,++ }),++ )++ .digest('hex');++}++++function sameLegacyApprovalDirectoryIdentity(expected: fs.Stats, current: fs.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 sameLegacyApprovalCanonicalPath(left: string, right: string): boolean {++ const fold = (value: string): string =>++ process.platform === 'win32' ? value.toLowerCase() : value;++ return fold(path.resolve(left)) === fold(path.resolve(right));++}++++function assertStableLegacyApprovalDirectory(++ dir: string,++ expectedStats: fs.Stats,++ expectedRealPath: string,++): void {++ const currentStats = fs.lstatSync(dir);++ const currentRealPath = fs.realpathSync(dir);++ if (++ !sameLegacyApprovalDirectoryIdentity(expectedStats, currentStats) ||++ !sameLegacyApprovalCanonicalPath(expectedRealPath, currentRealPath)++ ) {++ throw new Error('legacy approval directory changed while reading');++ }++}++++function readLegacyDisabledMarkerForApproval(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;++ }++}++++function readLegacyLocaleResourcesForApproval(++ dir: string,++ realDir: string,++ manifest: GhostManifest,++): Record<string, GhostManifestLocaleResource> {++ const resources: Record<string, GhostManifestLocaleResource> = {};++ for (const localePath of Object.values(manifest.locales ?? {})) {++ if (!localePath) continue;++ const absPath = resolveGhostContentPathSync(dir, localePath, {++ expect: 'file',++ label: 'legacy locale',++ });++ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {++ containWithin: realDir,++ });++ if (bytes === null) throw new Error(`legacy locale missing or oversized: ${localePath}`);++ let raw: unknown;++ try {++ raw = JSON.parse(bytes.toString('utf8'));++ } catch (error) {++ throw new Error(++ `legacy locale is not valid JSON: ${localePath}: ${++ error instanceof Error ? error.message : String(error)++ }`,++ );++ }++ const validated = validateGhostManifestLocaleResource(raw, manifest);++ if (!validated.ok) throw new Error(`legacy locale invalid: ${localePath}`);++ resources[localePath] = validated.resource;++ }++ return resources;++}++++function readLegacyIconDataUrlForApproval(++ dir: string,++ realDir: string,++ manifest: GhostManifest,++): string | undefined {++ if (manifest.icon === undefined) return undefined;++ const iconPath = resolveGhostContentPathSync(dir, manifest.icon, {++ expect: 'file',++ label: 'legacy icon',++ });++ const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {++ containWithin: realDir,++ });++ if (bytes === null) {++ throw new Error(`legacy icon missing or oversized: ${manifest.icon}`);++ }++ const iconDataUrl = buildIconDataUrl(manifest.icon, bytes);++ if (iconDataUrl === null) {++ throw new Error(`legacy icon has unsupported mime type: ${manifest.icon}`);++ }++ return iconDataUrl;++}++++/**++ * Read the complete legacy approval fact once. Recovery freezes only its digest,++ * then both the pre-rename gate and receipt backfill re-read this same projection.++ */++export async function readLegacyGhostApprovalProjection(++ dir: string,++ id: string,++): Promise<{ projection: LegacyGhostApprovalProjection; sha256: string }> {++ const dirStats = fs.lstatSync(dir);++ if (!dirStats.isDirectory() || dirStats.isSymbolicLink()) {++ throw new Error('legacy approval source is not a real directory');++ }++ const realDir = fs.realpathSync(dir);++ assertStableLegacyApprovalDirectory(dir, dirStats, realDir);++ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {++ expect: 'file',++ label: 'legacy manifest',++ });++ const rawBytes = readBoundedFileNoFollowSync(manifestPath, GHOST_MANIFEST_MAX_BYTES, {++ containWithin: realDir,++ });++ if (rawBytes === null) throw new Error('legacy manifest is missing or oversized');++ let raw: unknown;++ try {++ raw = JSON.parse(rawBytes.toString('utf8'));++ } catch (error) {++ throw new Error(`invalid manifest JSON: ${error instanceof Error ? error.message : String(error)}`);++ }++ const validated = validateGhostManifest(raw);++ if (!validated.ok) throw new Error(`invalid manifest: ${validated.reason}`);++ if (validated.manifest.id !== id) throw new Error('manifest id != install dir name');++++ const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {++ level: 'unverified',++ publisherSigned: false,++ publisherVerified: false,++ reviewed: false,++ };++ const projection: LegacyGhostApprovalProjection = {++ manifest: validated.manifest,++ enabled: !readLegacyDisabledMarkerForApproval(dir),++ trust,++ localeResources: readLegacyLocaleResourcesForApproval(dir, realDir, validated.manifest),++ skillContentSha256: await hashApprovedSkillContent(validated.manifest, dir),++ };++ const iconDataUrl = readLegacyIconDataUrlForApproval(dir, realDir, validated.manifest);++ if (iconDataUrl !== undefined) projection.iconDataUrl = iconDataUrl;++ assertStableLegacyApprovalDirectory(dir, dirStats, realDir);++ return { projection, sha256: hashLegacyGhostApprovalProjection(projection) };++}+++function hashInstalledReapprovalProjection(+ projection: InstalledReapprovalProjection,+): string {+ return crypto+ .createHash('sha256')+ .update(+ JSON.stringify({+ version: 1,+ manifest: projection.manifest,+ trust: projection.trust,+ localeResources: projection.localeResources,+ iconDataUrl: projection.iconDataUrl ?? null,+ skillContentSha256: projection.skillContentSha256,+ }),+ )+ .digest('hex');+}++/**+ * `runExclusiveMutation` 回调内唯一可用的嵌套 mutation capability。+ * capability 在回调结束后立即失效,避免调用者绕过串行 lane 或复用旧 owner 上下文。+ */+export interface GhostExclusiveMutation {+ writeDisabledMarker(id: string): void;+ publishTrustedBundledSeed(+ id: string,+ sourceDir: string,+ options: { disabled: boolean },+ ): Promise<void>;+ approveTrustedBundledInstall(+ manifest: GhostManifest,+ markerEnabled: boolean,+ options: { sourceDir: string },+ ): Promise<boolean>;+ removeInstallApproval(id: string): Promise<boolean>;+ uninstall(id: string, options?: GhostUninstallOptions): Promise<UninstallResult>;}-/** 注入式日志接口 —— manager 不直接依赖 main/logger,单测零 electron。 */-export interface GhostManagerLogger {- info(message: string, meta?: Record<string, unknown>): void;- warn(message: string, meta?: Record<string, unknown>): void;-}+/**+ * 插件仓库的 main 端管理者:一个插件一个内容目录(rootDir/<id>/),Host+ * receipt 才是 manifest / trust / enabled / revision 的授权事实。+ *+ * 设计要点:+ * - **目录只证明在装**:list() 实扫内容目录,但批准状态来自安装根之外的+ * receipt;旧安装没有 receipt 时保持不可运行,更新需完整重新确认;+ * - **装载先落 staging 再切正式**(对齐 skillhub/installService 的做法):+ * 解压全程发生在 `.cindy-installing-*` 临时目录,校验全过才 rename 到+ * rootDir/<id>,任何一步失败都不会留下半截安装;+ * - **防 zip 三件套**:条目数 / 解压总量上限防 zip bomb,路径归一化 ++ * 越界检查防 zip-slip(压缩包里的 ../ 路径跳不出 staging);+ * - **卸载防御**:id 先过格式校验(shared/ghost 同一份规则),再确认+ * 目标是 rootDir 的直接子目录,杜绝借 id 删任意路径。+ */+export class GhostManager {+ private readonly receiptStore: GhostInstallReceiptStore;+ private ownerContextKey: string;+ private mutationTail: Promise<void> = Promise.resolve();+ private activeMutationContext: {+ ownerContextKey: string;+ contentRoot: string;+ stateRoot: string;+ } | null = null;+ /**+ * 本进程内被判定"批准状态不可信"的插件 id。+ *+ * 用途只有一个:撤销陈旧批准**失败**时的兜底。撤销失败的成因(状态根不可写)与+ * 写批准失败的成因是同一个,所以不能再指望往状态根写任何东西来表达"已失效" ——+ * 内存标记是此时唯一还能用的机制。下次启动重新对账,成功即自愈;仍然失败就仍然+ * 隔离,始终 fail closed。+ */+ private readonly untrustedApprovals = new Set<string>();+ /** Owner namespaces whose mutation journal could not be authoritatively scanned. */+ private readonly recoveryBlockedApprovalNamespaces = new Set<string>();++ /**+ * 进程内隔离集合的键:以**当前 owner 的状态根**为命名空间。集合是 manager 级+ * 单例、owner 切换不重建 —— 裸用 id 会让 A 账号的隔离污染 B 账号的同 id 插件+ * (B 无辜被投影成 invalid);而切换边界时清空集合又是反方向的 fail open+ * (切回 A 时隔离丢失,盘上陈旧 receipt 复活)。按状态根命名空间两头都对:+ * B 的键不命中,切回 A 键重新命中、隔离持续到自愈。+ */+ private isolationKey(id: string): string {+ return `${this.receiptStore.rootDir()}\u0000${id}`;+ }++ constructor(private readonly options: GhostManagerOptions) {+ this.receiptStore = new GhostInstallReceiptStore(() => this.stateRootDir());+ const contentRoot = this.resolveContentRoot();+ const stateRoot = this.resolveStateRoot();+ this.assertDisjointRoots(contentRoot, stateRoot);+ this.ownerContextKey = this.currentOwnerContextKey();+ this.recoverInterruptedMutationsSync();+ }++ private resolveContentRoot(): string {+ return path.resolve(this.options.getRootDir());+ }++ private resolveStateRoot(): string {+ if (this.options.getStateDir) return path.resolve(this.options.getStateDir());+ const root = this.resolveContentRoot();+ return path.join(path.dirname(root), `${path.basename(root)}-install-state`);+ }++ private contentRootDir(): string {+ return this.activeMutationContext?.contentRoot ?? this.resolveContentRoot();+ }++ private stateRootDir(): string {+ return this.activeMutationContext?.stateRoot ?? this.resolveStateRoot();+ }++ private assertDisjointRoots(contentRoot: string, stateRoot: string): void {+ const physicalContentRoot = this.assertManagedRootPath(contentRoot, 'ghost content root');+ const physicalStateRoot = this.assertManagedRootPath(stateRoot, 'ghost approval state root');+ if (+ isPathInsideDir(physicalContentRoot, physicalStateRoot) ||+ isPathInsideDir(physicalStateRoot, physicalContentRoot)+ ) {+ throw new Error('ghost install content and approval state roots must be disjoint');+ }+ }++ /**+ * Managed roots themselves must be real directories (or not exist yet), but their ancestors may+ * be links: relocated Home/AppData is a supported OS layout. Return a physical identity by+ * resolving the nearest existing ancestor so lexical aliases cannot bypass the disjointness gate.+ */+ private assertManagedRootPath(absPath: string, label: string): string {+ const resolved = path.resolve(absPath);+ try {+ const kind = classifyGhostDirEntrySync(resolved);+ if (kind !== 'directory') throw new Error(`${label} is not a real directory`);+ return fs.realpathSync.native(resolved);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }++ const missingSegments: string[] = [];+ let ancestor = resolved;+ while (true) {+ const parent = path.dirname(ancestor);+ if (parent === ancestor) throw new Error(`${label} has no existing directory ancestor`);+ missingSegments.unshift(path.basename(ancestor));+ ancestor = parent;+ try {+ const realAncestor = fs.realpathSync.native(ancestor);+ if (!fs.statSync(realAncestor).isDirectory()) {+ throw new Error(`${label} ancestor is not a directory`);+ }+ return path.join(realAncestor, ...missingSegments);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw error;+ }+ }+ }++ /**+ * The manager is retained by IPC closures, while owner-scoped roots are resolved+ * dynamically by the host. Re-run synchronous recovery whenever that namespace+ * changes before any list/mutation can consume the new owner's files.+ */+ private ensureCurrentOwnerContextSync(): void {+ if (this.activeMutationContext) return;+ const next = this.currentOwnerContextKey();+ if (next === this.ownerContextKey) return;+ this.assertDisjointRoots(this.resolveContentRoot(), this.resolveStateRoot());+ this.ownerContextKey = next;+ this.recoverInterruptedMutationsSync();+ }++ private currentOwnerContextKey(): string {+ return `${this.options.getOwnerContextKey?.() ?? ''}\u0000${this.resolveContentRoot()}\u0000${this.resolveStateRoot()}`;+ }++ private approvalNamespaceKey(): string {+ return this.activeMutationContext?.ownerContextKey ?? this.ownerContextKey;+ }++ /**+ * A journal scan failure cannot identify which installed id may be between+ * content publication and receipt commit. Quarantine every real installed id+ * for this owner until a later manager instance can complete recovery.+ */+ private quarantineAllInstalledApprovalsSync(): void {+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(this.contentRootDir(), { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (entry.name.startsWith('.') || !isValidGhostId(entry.name)) continue;+ try {+ if (classifyGhostDirEntrySync(path.join(this.contentRootDir(), entry.name)) !== 'directory') {+ continue;+ }+ } catch {+ continue;+ }+ this.untrustedApprovals.add(this.isolationKey(entry.name));+ }+ }++ /**+ * 启动一次性:恢复装入/更新的"目录已 rename、receipt 还没写"崩溃现场。构造期同步跑+ * (目录极小,与 resolveGhostRepoRoot 的启动期迁移同一先例)。+ *+ * **事务标记(状态根内)是权威判据**:装入/更新在 rename 动盘前落标记、写完 receipt+ * 清标记,标记带本次 `packageSha256`。恢复时同步读 receipt,`receipt.packageSha256 ===+ * marker.packageSha256` 即"已提交":+ * - install 未提交 → finalDir 是不完整安装,删掉(否则迁移会把它当 legacy 收编,而+ * 崩溃窗口内 manifest 可能已被同权限进程改写 = 用户确认 A 却授权 B);已提交 → 保留;+ * - update 未提交 → 回滚到 backup(旧字节+旧 receipt 自洽);已提交 → 回收陈旧 backup。+ * 这修掉了"final 在位就删 backup"把"新字节+旧 receipt"固化成"按旧批准跑新代码"的洞。+ *+ * 无标记的孤儿 `.cindy-updating-*`(journal 之前的崩溃残留)沿用原启发式兜底:final+ * 缺位且唯一 backup → 搬回(§5 插件不得凭空消失);final 在位 → 陈旧 backup 回收。+ * `.cindy-installing-*` staging 残留一律回收(从未发布)。+ */+ private recoverInterruptedMutationsSync(): void {+ const root = this.contentRootDir();++ // 1) 标记驱动恢复(权威)。+ const handledBackupNames = new Set<string>();+ const blockedMutationIds = new Set<string>();+ const pendingScan = this.receiptStore.listPendingMutationIdsSync();+ if (pendingScan.state === 'unreadable') {+ this.recoveryBlockedApprovalNamespaces.add(this.approvalNamespaceKey());+ this.quarantineAllInstalledApprovalsSync();+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost mutation journal root unreadable; skipped all recovery heuristics',+ { error: pendingScan.reason },+ );+ return;+ }+ let recoveryHeuristicsBlocked = false;+ if (pendingScan.blocked) {+ this.recoveryBlockedApprovalNamespaces.add(this.approvalNamespaceKey());+ this.quarantineAllInstalledApprovalsSync();+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'invalid ghost mutation journal marker blocks orphan-backup heuristics',+ );+ } else {+ // The journal namespace is authoritative again. Known pending ids still+ // receive per-id isolation below if their individual recovery fails.+ this.recoveryBlockedApprovalNamespaces.delete(this.approvalNamespaceKey());+ }+ for (const id of pendingScan.ids) {+ const markerResult = this.receiptStore.readPendingMutationSync(id);+ const finalDir = path.join(root, id);+ if (markerResult.state === 'missing') continue;+ // A pending transaction means the receipt cannot authorize finalDir until+ // recovery proves commit/rollback and clears the marker.+ this.untrustedApprovals.add(this.isolationKey(id));+ if (markerResult.state !== 'valid') {+ blockedMutationIds.add(id);+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost mutation journal unavailable; left for manual/next-launch recovery',+ { id, state: markerResult.state, reason: markerResult.reason },+ );+ continue;+ }+ const marker = markerResult.mutation;+ try {+ if (marker.kind === 'uninstall') {+ // 卸载崩在半途:把批准与内容目录都删净(幂等,顺序无关)。撤批准已在卸载时+ // 先行,这里兜住"receipt 或目录仍残留"的任意组合 —— 收尾后该 id 干净消失。+ this.untrustedApprovals.add(this.isolationKey(id));+ if (marker.builtinTombstone) {+ if (!this.options.recordBuiltinTombstone) {+ throw new Error('builtin uninstall recovery has no tombstone writer');+ }+ this.options.recordBuiltinTombstone(id);+ }+ this.receiptStore.removeSync(id);+ if (this.recoveryEntryKind(finalDir) === 'directory') {+ fs.rmSync(finalDir, { recursive: true, force: true });+ }+ } else {+ const approval = this.receiptStore.readForRecovery(id);+ if (approval.state === 'unreadable') {+ blockedMutationIds.add(id);+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost approval receipt unreadable during recovery; journal retained',+ { id, kind: marker.kind, reason: approval.reason },+ );+ continue;+ }+ if (marker.kind === 'install') {+ // 未提交装入(无已批准 receipt)= 不完整安装,删 finalDir;有已批准 receipt = 完整+ // 安装,保留(绝不删有有效批准的插件)。只删真目录,junction/链接跳过(避免穿透)。+ const finalKind = this.recoveryEntryKind(finalDir);+ const receiptCommitted =+ approval.state === 'approved' &&+ (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 && 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' &&+ 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) {+ if (backupKind === 'directory') {+ fs.rmSync(backupPath, { recursive: true, force: true }); // 陈旧旧字节+ } else if (backupKind !== 'missing') {+ throw new Error('managed update backup is not a real directory');+ }+ } else {+ // 回滚:finalDir 可能是未提交新字节,删;backup 若在则搬回(旧字节+旧 receipt)。+ 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.+ if (backupKind === 'missing' && finalKind === 'directory') {+ if (marker.phase === 'prepared') {+ this.receiptStore.clearPendingMutationSync(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ continue;+ }+ // A legacy v1 marker has no phase information. Preserve the+ // marker and block heuristics rather than guessing whether the+ // final bytes are old or newly published.+ throw new Error('managed update final present without backup at an unknown phase');+ }+ if (finalKind === 'directory') {+ fs.rmSync(finalDir, { recursive: true, force: true });+ } else if (finalKind !== 'missing') {+ throw new Error('managed update final is not a real directory');+ }+ if (backupKind === 'directory') {+ fs.renameSync(backupPath, finalDir);+ } else if (backupKind === 'missing') {+ // Neither side is available; keep the journal and receipt for a+ // later retry rather than deleting authorization state.+ throw new Error('managed update final and backup are both missing');+ } else {+ throw new Error('managed update backup is not a real directory');+ }+ }+ }+ }+ this.receiptStore.clearPendingMutationSync(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ } catch (err) {+ // 动盘失败:留着标记,下次启动幂等重试。+ blockedMutationIds.add(id);+ recoveryHeuristicsBlocked = true;+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'interrupted ghost mutation recovery failed; left for next launch',+ {+ id,+ kind: marker?.kind,+ error: err instanceof Error ? err.message : String(err),+ },+ );+ }+ }++ // Any unreadable/invalid journal means the state-root view is not authoritative.+ // Do not run unjournaled backup/staging heuristics in that condition.+ if (recoveryHeuristicsBlocked) return;++ // 2) 无标记的孤儿 backup + staging 残留。+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(root, { withFileTypes: true });+ } catch {+ return; // 根目录还不存在 = 没装过任何插件+ }+ const backups = entries.filter(+ (entry) => entry.name.startsWith('.cindy-updating-') && !handledBackupNames.has(entry.name),+ );+ for (const entry of backups) {+ const match = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(entry.name);+ if (!match || !isValidGhostId(match[1])) continue;+ const id = match[1];+ if (blockedMutationIds.has(id)) continue;+ const backupPath = path.join(root, entry.name);+ try {+ if (classifyGhostDirEntrySync(backupPath) !== 'directory') continue;+ } catch {+ continue;+ }+ const finalDir = path.join(root, id);+ // 按解析后的 id 精确比对,不能用前缀 startsWith:合法 id 允许带 `-`,+ // `.cindy-updating-foo-<hex>` 是 `.cindy-updating-foo-bar-<hex>` 的前缀,+ // 若用前缀匹配,foo 与 foo-bar 同时留有 backup 时,foo 的唯一 backup 会被+ // 误统计成多个而判为"多备份,留待人工",崩溃后 foo 持续消失(评审 P1)。+ const siblings = backups.filter((other) => {+ const otherMatch = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(other.name);+ return otherMatch !== null && otherMatch[1] === id;+ });+ let finalKind: GhostDirEntryKind | 'missing';+ try {+ finalKind = classifyGhostDirEntrySync(finalDir);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ finalKind = 'missing';+ } else {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'interrupted-update final path unreadable; backup left untouched',+ { id, backup: entry.name, error: err instanceof Error ? err.message : String(err) },+ );+ continue;+ }+ }+ if (finalKind === 'directory') {+ try {+ fs.rmSync(backupPath, { recursive: true, force: true });+ } catch (err) {+ this.options.log?.warn('stale ghost update backup cleanup failed', {+ id,+ backup: entry.name,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ continue;+ }+ if (finalKind !== 'missing') {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'interrupted-update final path is not a directory; backup left untouched',+ { id, backup: entry.name, finalKind },+ );+ continue;+ }+ if (siblings.length !== 1) {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'multiple interrupted-update backups for one ghost; left untouched for manual recovery',+ {+ id,+ backups: siblings.map((other) => other.name),+ },+ );+ continue;+ }+ try {+ fs.renameSync(backupPath, finalDir);+ this.options.log?.info('ghost restored from interrupted update backup', { id });+ } catch (err) {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost interrupted-update recovery failed; plugin stays missing until manual recovery',+ {+ id,+ backup: entry.name,+ error: err instanceof Error ? err.message : String(err),+ },+ );+ }+ }+ for (const entry of entries) {+ if (!entry.name.startsWith('.cindy-installing-')) continue;+ try {+ fs.rmSync(path.join(root, entry.name), { recursive: true, force: true });+ } catch {+ // staging 残留清不掉只占磁盘,不影响正确性;下次启动再试。+ }+ }+ }++ /** `<root>/<id>` 是否真目录(非链接/junction;判据同 ghostContentTree,避免穿透删除)。 */+ private isRealDirChild(root: string, id: string): boolean {+ try {+ return classifyGhostDirEntrySync(path.join(root, id)) === 'directory';+ } catch {+ return false;+ }+ }++ /** Recovery distinguishes a missing path from transiently unreadable state. */+ private recoveryEntryKind(absPath: string): GhostDirEntryKind | 'missing' {+ try {+ return classifyGhostDirEntrySync(absPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ throw error;+ }+ }++ /**+ * 从 `.cindy` 包的内存投影算技能字节指纹(P0-8)。+ *+ * 批准基线必须取自**用户确认过、且不可再被本机进程改写**的来源。旧写法在+ * staging→final 发布之后才从 finalDir 首读 —— publish 与首次 hash 之间被换掉的+ * SKILL.md 正文/辅助文件会同时成为 receipt 指纹与快照,后续校验全自洽,篡改被+ * 洗成批准事实。包投影(JSZip 内存条目)在 inspect 时已被 packageSha256 钉住、+ * 与用户确认的是同一份字节;据它算指纹后,发布后的目录漂移会在快照落盘对账时+ * 如实 fail closed(拒装),而不是被钉进批准。+ */+ private async hashSkillContentFromPackage(+ manifest: GhostManifest,+ allEntries: JSZip.JSZipObject[],+ prefix: string,+ ): Promise<Record<string, string>> {+ const items = manifest.skill?.items ?? [];+ if (items.length === 0) return {};+ const result: Record<string, string> = {};+ for (const item of items) {+ const itemPrefix = `${item.dir}/`;+ const files: { path: string; bytes: Buffer }[] = [];+ for (const entry of allEntries) {+ if (entry.dir) continue;+ const rel = entry.name.slice(prefix.length);+ if (!rel.startsWith(itemPrefix)) continue;+ files.push({ path: rel.slice(itemPrefix.length), bytes: await entry.async('nodebuffer') });+ }+ result[item.dir] = hashGhostContentBuffers(files);+ }+ return result;+ }++ /** Forge 等 Host 能力必须排除的受管根(内容根 + 批准状态根)。 */+ managedRootDirs(): string[] {+ return [this.contentRootDir(), this.receiptStore.rootDir()];+ }++ approvalStateRoot(): string {+ return this.receiptStore.rootDir();+ }++ /**+ * 启停投影:receipt 为主,安装目录 `.disabled` 镜像**只往停用方向覆盖**(读时合并)。+ *+ * 为什么在读侧合并而不是只信 receipt:停用必须永远能成功(规则 §3 收敛方向不对称)。+ * 状态根不可写时 `setEnabled(false)` 仍能写镜像;若 list() 只读 receipt,那次停用会在+ * 重启后静默复活 —— fail open。镜像只能把启停态往下拉,不能往上翻(重新启用只有+ * setEnabled(true) 成功写 receipt 一条路),与随包对账的合并规则同向。+ */+ private effectiveEnabled(dir: string, receiptEnabled: boolean): boolean {+ return receiptEnabled && !this.isDisabledMarkerPresentSync(dir);+ }++ /** Compatibility marker reads fail closed and never follow a link/non-regular entry. */+ private isDisabledMarkerPresentSync(dir: string): boolean {+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ try {+ // A regular marker means disabled; any non-regular entry also fails closed.+ classifyGhostDirEntrySync(marker);+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ return true;+ }+ }+- /** 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');+ }+ 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;+ }+ fs.writeFileSync(marker, '');+ }++ /**+ * 读批准状态的**唯一入口**:进程内隔离优先于磁盘上的 receipt。+ *+ * 所有消费方(list / setEnabled / update 的 token 比对)都必须走这里 —— 各自直接+ * 调 receiptStore.read() 会让隔离在某条路径上失效,那类"同一判定散落多处"的分叉+ * 正是本 PR 前几轮反复出问题的原因。+ */+ private readApproval(id: string): GhostInstallReceiptReadResult {+ if (this.recoveryBlockedApprovalNamespaces.has(this.approvalNamespaceKey())) {+ return { state: 'invalid', reason: 'ghost mutation journal namespace is unreadable' };+ }+ if (this.untrustedApprovals.has(this.isolationKey(id))) {+ return { state: 'invalid', reason: '批准状态已被判定不可信(撤销失败)' };+ }+ return this.receiptStore.read(id);+ }++ /**+ * 技能链接对账前重新核验批准快照。+ *+ * `list()` 是首帧同步 API,不能在里面流式重算目录摘要;因此由异步 reconciler+ * 对每个准备挂链的插件调用本入口。receipt revision 若已变化、快照缺失/不可读、+ * 含非普通条目或字节不符一律 false,让对账器撤掉已有链接并拒绝新建。+ */+ async verifyApprovedSkillSnapshot(ghost: InstalledGhost): Promise<boolean> {+ this.ensureCurrentOwnerContextSync();+ if (+ ghost.approval.state !== 'approved' ||+ !ghost.manifest.skill?.items.length ||+ !ghost.approvedSkillRoot+ ) {+ return false;+ }+ const current = this.readApproval(ghost.manifest.id);+ if (current.state !== 'approved' || current.receipt.revision !== ghost.approval.revision) {+ return false;+ }+ const expectedRoot = this.receiptStore.skillSnapshotRoot(+ current.receipt.id,+ current.receipt.revision,+ );+ if (path.resolve(ghost.approvedSkillRoot) !== path.resolve(expectedRoot)) {+ return false;+ }+ return this.receiptStore.skillSnapshotMatchesReceipt(current.receipt, expectedRoot);+ }++ /**+ * Serialize content-directory and approval-receipt mutations as one Host transaction lane.+ * The owner generation and both roots are captured after queue wait and remain fixed for the+ * whole callback, so a concurrent session commit cannot redirect later awaits into another+ * owner's namespace.+ */+ async runExclusiveMutation<T>(+ operation: (mutation: GhostExclusiveMutation) => Promise<T>,+ ): Promise<T> {+ this.ensureCurrentOwnerContextSync();+ const queuedOwnerContextKey = this.ownerContextKey;+ const previous = this.mutationTail;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ this.mutationTail = previous.then(() => gate);+ await previous;+ let capabilityActive = true;+ try {+ const currentOwnerContextKey = this.currentOwnerContextKey();+ if (+ this.ownerContextKey !== queuedOwnerContextKey ||+ currentOwnerContextKey !== queuedOwnerContextKey+ ) {+ throw new Error('ghost owner context changed while mutation was queued');+ }+ const contentRoot = this.resolveContentRoot();+ const stateRoot = this.resolveStateRoot();+ this.assertDisjointRoots(contentRoot, stateRoot);+ this.activeMutationContext = {+ ownerContextKey: currentOwnerContextKey,+ contentRoot,+ stateRoot,+ };+ const assertCapabilityActive = (): void => {+ if (+ !capabilityActive ||+ this.activeMutationContext?.ownerContextKey !== currentOwnerContextKey+ ) {+ throw new Error('ghost exclusive mutation capability is no longer active');+ }+ };+ const mutation: GhostExclusiveMutation = {+ writeDisabledMarker: (id) => {+ assertCapabilityActive();+ if (!isValidGhostId(id) || !this.isRealDirChild(this.contentRootDir(), id)) {+ throw new Error('ghost disabled marker target is not a managed plugin directory');+ }+ this.writeDisabledMarkerSync(path.join(this.contentRootDir(), id));+ },+ publishTrustedBundledSeed: async (id, sourceDir, options) => {+ assertCapabilityActive();+ await this.publishTrustedBundledSeedUnlocked(id, sourceDir, options);+ },+ approveTrustedBundledInstall: async (manifest, markerEnabled, options) => {+ assertCapabilityActive();+ return this.approveTrustedBundledInstallUnlocked(manifest, markerEnabled, options);+ },+ removeInstallApproval: async (id) => {+ assertCapabilityActive();+ return this.removeInstallApprovalUnlocked(id);+ },+ uninstall: async (id, options = {}) => {+ assertCapabilityActive();+ return this.uninstallUnlocked(id, options);+ },+ };+ return await operation(mutation);+ } finally {+ capabilityActive = false;+ this.activeMutationContext = null;+ release();+ }+ }++ /**+ * 一次性 legacy backfill 迁移(docs/dev-rules/plugin-security-and-authoring.md 第 5 节+ * 红线的落地)。#1080 把授权事实从可变安装目录搬到 Host receipt,升级前装的插件没有+ * receipt —— 若不迁移,它们会一律落到 `legacy-unapproved`、被列停用、要用户逐个重新+ * 确认(这正是 #1080 被回滚的原因)。这里从旧的三份事实源(`ghost.json` /+ * `.cindy-trust.json` / `.disabled`)重建等价 receipt,让存量插件升级后**无感可用**。+ *+ * 三条不变量:+ * - **全局一次性**:状态根有迁移 ledger 即视为已迁过,此后缺 receipt 一律 fail closed,+ * 不再迁。理由见 `GhostLegacyMigrationLedger` 头注释(否则删 receipt 就能骗一次+ * "从可变安装目录重建授权")。+ * - **不扩权、不等于新确认**:receipt 权限集 = 当前 `ghost.json` 声明,等价于旧模型+ * 无条件授权的那一组;此后任何 manifest/权限变化照旧走完整确认(update 流程不变)。+ * - **只写状态根、绝不动安装目录**:三份旧文件原样保留,因此回滚到旧客户端时它照旧+ * 从安装目录判定启停,不会错位(§5 兜底第 4 条 回滚余地)。+ *+ * 随包种子 id 跳过 —— 它们走 provisioning 的 `approveTrustedBundledInstall`(有权威+ * 字节可比,是更强的迁移形态)。+ */+ async migrateLegacyApprovalsOnce(): Promise<{+ migrated: string[];+ skipped: string[];+ failed: string[];+ retryPending: string[];+ }> {+ return this.runExclusiveMutation(() => this.migrateLegacyApprovalsUnlocked());+ }++ private async migrateLegacyApprovalsUnlocked(): Promise<{+ migrated: string[];+ skipped: string[];+ failed: string[];+ retryPending: string[];+ }> {+ const result = {+ migrated: [] as string[],+ skipped: [] as string[],+ failed: [] as string[],+ retryPending: [] as string[],+ };+ // 一次性门(状态机见 GhostLegacyMigrationLedger 头注释),判据缺一不可:+ // 1) 台账 completed(或存在但读不出)= 迁过,不再迁;in-progress = 上一轮中途+ // 崩溃,按钉死的 pendingIds 续跑 —— receipt 首写自动落台账的守卫(见+ // receiptStore.write)只在"完全没有台账"时动笔,不会把 in-progress 焊死。+ // 2) 首轮必须先扫描完整安装根,不能因**任意一个**有效 receipt 提前关门。#1080+ // 曾经写出 receipt 却没有 migration ledger;那类历史 mixed 状态里 A 已批准、B+ // 仍是 legacy,提前 completed 会让 B 永久失效。新代码通过 receipt 提交前先写+ // ledger 保证不再自然产生这种状态;能删 ledger 的状态根写者本就能伪造 receipt,+ // 不属于安装根可变这一条威胁模型新增的能力。+ // 之所以"安装根为空/未诞生时不落台账":为 owner 命名空间的 legacy 恢复流程留门+ // (它会在之后才把旧目录搬进来);这个留门被"装一个插件→删 receipt"利用的路由+ // 第 2 道判据 + receipt 首写自动落台账挡住。+ if (this.receiptStore.migrationDoorClosed()) {+ if (this.receiptStore.hasMigrationLedger() && !this.receiptStore.readMigrationLedger()) {+ // 台账存在但读不出:门保守关死(成因与保守方向见 migrationDoorClosed 注释),+ // 但这必须可观测 —— 它意味着状态根被外力改写过。+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'legacy migration ledger unreadable; migration door kept closed',+ { path: this.receiptStore.rootDir() },+ );+ }+ return result;+ }+ const resumeLedger = this.receiptStore.readMigrationLedger();+ const resumePending =+ resumeLedger?.state === 'in-progress' ? new Set(resumeLedger.pendingIds ?? []) : null;++ const root = this.contentRootDir();+ let entries: fs.Dirent[] = [];+ try {+ entries = fs.readdirSync(root, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ // 安装根未诞生:全新用户,或 legacy 恢复流程还没把旧目录搬进来。没有可迁+ // 对象,也**不写台账** —— 门要给随后搬入的旧目录留着(见头注释)。+ // (in-progress 续跑轮走不到这里出 ENOENT 的话,门保持 in-progress,下轮再试。)+ return result;+ }+ // EACCES/EIO 等真实故障:本轮放弃且不改台账,下次启动重试。吞掉错误照写+ // 台账会把迁移永久封死在一次环境抖动上。+ throw err;+ }++ // 先收候选、后动笔:in-progress 台账必须在**首个 backfill 之前**原子落盘,+ // 否则第一份 receipt 的自动落账守卫就会把门写成 completed,中途崩溃即焊死。+ const candidates: string[] = [];+ const blockedByPendingJournal: string[] = [];+ const unreadableReceiptIds: string[] = [];+ const preMigrated: string[] = [];+ let sawApprovedNonBundledInstall = false;+ // 续跑只对白名单内、且本轮仍可观察到的对象建重试队列;已消失的目录视为+ // 已被卸载/清理,不应把全局迁移门永久卡在一个不存在的 id 上。+ const pendingForRetry = new Set<string>();+ for (const entry of entries) {+ const id = entry.name;+ if (id.startsWith('.') || !isValidGhostId(id)) continue;+ // 判据走 ghostContentTree(lstat 分类),不信 Dirent 类型位:根子项是 junction/+ // 链接时一律不进迁移,也与 §3「只有真目录才算安装」同向。+ if (classifyGhostDirEntrySync(path.join(root, id)) !== 'directory') continue;+ // 随包种子交给 provisioning,不在迁移范围。+ if (this.options.isTrustedBundledId?.(id)) {+ result.skipped.push(id);+ continue;+ }+ // 续跑轮只认动笔前钉死的清单:清单外的 id(迁移窗口期间新装再删 receipt 的)+ // 骗不到续跑重铸,保持 fail closed。+ if (resumePending && !resumePending.has(id)) {+ result.skipped.push(id);+ continue;+ }+ const approval = this.receiptStore.readForRecovery(id);+ if (approval.state === 'approved') {+ sawApprovedNonBundledInstall = true;+ // 首轮:迁移前不该有,防御性跳过。续跑轮:上一轮崩溃前已写出的 receipt,+ // 计入 migrated 让最终台账如实反映"这些是迁移铸出的"。+ (resumePending ? preMigrated : result.skipped).push(id);+ pendingForRetry.delete(id);+ continue;+ }+ if (approval.state === 'unreadable') {+ // 暂时读不动批准事实不等于 legacy/损坏。把它从可变安装目录重铸会覆盖一份+ // 可能完全有效的批准;保持 fail closed 并把 id 钉进持久重试队列。+ result.retryPending.push(id);+ pendingForRetry.add(id);+ unreadableReceiptIds.push(id);+ this.options.log?.warn('legacy migration found an unreadable receipt; will retry', {+ id,+ reason: approval.reason,+ });+ continue;+ }+ // 有未清的事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净(通常恢复已在+ // 构造期把它清掉,这里兜住"恢复删 finalDir 失败"的残留)。绝不迁移这种目录 ——+ // 它的字节来源不是"用户确认过的旧安装",而是一次未完成事务的中间态。+ if (this.hasPendingMutationJournal(id)) {+ result.skipped.push(id);+ blockedByPendingJournal.push(id);+ continue;+ }+ candidates.push(id);+ }++ if (+ candidates.length === 0 &&+ !resumePending &&+ blockedByPendingJournal.length === 0 &&+ unreadableReceiptIds.length === 0+ ) {+ // 历史 mixed 状态若只剩有效的非随包 receipt,补写 completed 收口;空目录或+ // 只有随包目录仍不落台账,给 owner legacy 恢复流程留门。+ if (sawApprovedNonBundledInstall) {+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'completed',+ });+ }+ return result;+ }+ if (+ !resumePending &&+ (candidates.length > 0 ||+ blockedByPendingJournal.length > 0 ||+ unreadableReceiptIds.length > 0)+ ) {+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'in-progress',+ pendingIds: [+ ...new Set([...candidates, ...blockedByPendingJournal, ...unreadableReceiptIds]),+ ].sort(),+ });+ }++ for (const id of candidates) {+ try {+ const migrated = await this.backfillLegacyApproval(path.join(root, id), id);+ (migrated ? result.migrated : result.skipped).push(id);+ pendingForRetry.delete(id);+ } catch (err) {+ // 错误分类决定这个 id 的余生,不能一锅端:+ // - 带 errno 的环境错(EACCES/ENOSPC/EBUSY…,状态根写不动、文件被占等)是+ // **瞬时**故障,不属于 §5 的"旧事实读不出/自相矛盾" —— 记 retryPending,+ // 台账停在 in-progress,下次启动自动续跑;写进 completed 的 failedIds 会把+ // 一次环境抖动永久封成"需要人工重新确认"。+ // - 无 errno 的校验错(manifest 不合法、技能目录含链接、locale 装入后损坏)+ // 与 ENOENT(声明的文件缺失 = 内容状态,不是抖动)是**确定性**内容无效,+ // 记 failed、fail closed,走每插件恢复 UI。+ const transient = isTransientBackfillError(err);+ if (transient) {+ result.retryPending.push(id);+ pendingForRetry.add(id);+ this.options.log?.warn(+ 'legacy ghost approval migration hit transient IO; will retry next launch',+ {+ id,+ code: (err as NodeJS.ErrnoException | null)?.code,+ error: err instanceof Error ? err.message : String(err),+ },+ );+ } else {+ result.failed.push(id);+ pendingForRetry.delete(id);+ this.options.log?.warn('legacy ghost approval migration failed; kept fail-closed', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ }++ // 收尾状态机(原子改写):+ // - 有瞬时失败 → 台账停在 in-progress,pendingIds = 仅剩的重试对象,下次启动+ // 自动续跑(§5 兜底第 1 条"能自动就别打扰用户");确定性 failed 不进 pendingIds,+ // 续跑白名单挡住"迁移窗口期间新装再删 receipt"的老路。+ // - 全部落定(只剩确定性 failed 或全成功)→ completed;续跑轮把上一轮已记的+ // failedIds 一并带上,台账始终如实反映全量。+ const migratedIds = [...new Set([...result.migrated, ...preMigrated])].sort();+ const failedIds = [...new Set([...result.failed, ...(resumeLedger?.failedIds ?? [])])].sort();+ for (const id of blockedByPendingJournal) pendingForRetry.add(id);+ const retryIds = [...pendingForRetry].sort();+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds,+ ...(retryIds.length > 0+ ? { state: 'in-progress' as const, pendingIds: retryIds }+ : { state: 'completed' as const }),+ ...(failedIds.length > 0 ? { failedIds } : {}),+ });+ if (result.migrated.length > 0) this.options.onChanged?.(this.list());+ return result;+ }++ /**+ * legacy 恢复流程(owner 命名空间认领旧布局目录)专用的 backfill 旁路。+ *+ * 为什么允许绕过一次性 ledger 门:`ids` 来自恢复流程**刚从旧布局根搬进安装根**的+ * 目录 —— 这个来源本身就是旧世界的授权事实(与首轮迁移同一信任级),不是可变安装+ * 目录里凭空冒出来的目录。调用方只传本次恢复实际搬动/新增的 id;逐 id 仍然只在+ * 没有有效 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[],- options: { includePending?: boolean } = {},++ options: {++ includePending?: boolean;++ expectedApprovalProjectionSha256ById: Readonly<Record<string, string>>;++ },+ ): 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 =>+ isValidGhostId(id) && this.options.isTrustedBundledId?.(id) !== true,+ );+ // Persist the complete recovery work queue before the first backfill. If the+ // 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,+ migratedAt: prev?.migratedAt ?? new Date().toISOString(),+ migratedIds: prev?.migratedIds ?? [],+ ...(prev?.failedIds?.length ? { failedIds: prev.failedIds } : {}),+ state: 'in-progress',+ pendingIds: queuedIds,+ });+ for (const id of queuedIds) pendingForRetry.add(id);+ }+ for (const id of workIds) {+ const approval = this.receiptStore.readForRecovery(id);+ if (approval.state === 'approved') {+ pendingForRetry.delete(id);+ continue;+ }+ if (approval.state === 'unreadable') {+ retryIds.push(id);+ pendingForRetry.add(id);+ this.options.log?.warn('recovered legacy receipt unreadable; will retry', {+ id,+ reason: approval.reason,+ });+ 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)) {++ const targetDir = path.join(root, id);++ const expectedApprovalProjectionSha256 =++ options.expectedApprovalProjectionSha256ById[id];++ if (expectedApprovalProjectionSha256 === undefined) {++ throw new Error(`recovered legacy approval projection is missing or invalid: ${id}`);++ }++ if (!/^[a-f0-9]{64}$/.test(expectedApprovalProjectionSha256)) {++ throw new Error(`recovered legacy approval projection is missing or invalid: ${id}`);++ }++ if (++ await this.backfillLegacyApproval(targetDir, id, {++ expectedApprovalProjectionSha256,++ })++ ) {+ out.migrated.push(id);+ }+ pendingForRetry.delete(id);+ } catch (err) {+ // 与主迁移循环同一分类:瞬时 IO 抖动不记 failed(否则写进 completed 台账就+ // 把一次环境抖动永久封成"需要人工重新确认"),只记日志、留待下次恢复触发重试;+ // 确定性内容无效才 fail closed。+ if (isTransientBackfillError(err)) {+ retryIds.push(id);+ pendingForRetry.add(id);+ this.options.log?.warn('recovered legacy ghost backfill hit transient IO; will retry', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ } else {+ out.failed.push(id);+ pendingForRetry.delete(id);+ this.options.log?.warn('recovered legacy ghost backfill failed; kept fail-closed', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ }+ if (+ hadQueuedWork ||+ out.migrated.length > 0 ||+ out.failed.length > 0 ||+ retryIds.length > 0 ||+ pendingForRetry.size > 0+ ) {+ const failedIds = [...new Set([...(prev?.failedIds ?? []), ...out.failed])].sort();+ await this.receiptStore.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [...new Set([...(prev?.migratedIds ?? []), ...out.migrated])].sort(),+ ...(failedIds.length > 0 ? { failedIds } : {}),+ // 旁路 backfill 的瞬时失败也必须进入持久化 work queue;目录已经搬入安装根,+ // 下一轮不会再次出现在“刚恢复”清单里,不能只靠内存日志重试。+ state: pendingForRetry.size > 0 ? 'in-progress' : 'completed',+ ...(pendingForRetry.size > 0 ? { pendingIds: [...pendingForRetry].sort() } : {}),+ });+ }+ if (out.migrated.length > 0) this.options.onChanged?.(this.list());+ const pending = [...new Set(retryIds)].sort();+ return options.includePending && pending.length > 0 ? { ...out, pending } : out;+ });+ }++ /**+ * 从旧安装目录的三份事实源重建一份等价 receipt。返回是否真的写了 receipt。+ *+ * 分级 fail 策略(对齐 §5"读不出核心事实才 fail closed,展示元数据缺失则降级"):+ * - `ghost.json` 读不出/不合法 → 抛错 → 调用方计入 failed、保持 fail closed;+ * - `.disabled` 镜像 → 旧模型的启停事实(不存在=启用);+ * - `.cindy-trust.json` 缺失/损坏 → 保守 `unverified`(展示信号,能力由 slot 授予);+ * - locale 声明存在但文件损坏 → 抛错 → fail closed。装入流程本就逐个校验声明的+ * locale、不合格拒装(见 `install` 里 `locale 文件不合格` 分支),所以旧安装天然不含+ * 坏 locale;迁移时读到坏 locale 只可能是**装入后被损坏**,属 §5 的"自相矛盾即+ * fail closed",也与 receipt「localeResources 键集必须等于 manifest.locales」的+ * 不变量一致(跳过坏 locale 会写出被 validateReceipt 拒绝的 receipt);+ * - `packageSha256` **不算**(它是 audit-only、运行期不消费,见 §7);省掉它让迁移更快、+ * 更不会因安装目录里的异常条目误伤——真正的运行期判据 `skillContentSha256` 仍逐字节算,+ * 技能目录含链接等异常会在那里如实 fail closed。+ */- private async backfillLegacyApproval(dir: string, id: string): Promise<boolean> {- // 读文件与解析分开抛,且**保留 fs 错误的 errno**:迁移循环按 `err.code` 把- // EACCES/EBUSY/EIO 判为瞬时(下次启动续跑),把无 errno 的错判为确定性内容无效- // (fail closed)。若把 readFileSync 的错也包成 new Error()(丢掉 code),一次- // 读 legacy ghost.json 的瞬时 IO 抖动就会被误判成确定性 failed、写进 completed- // 台账,永久要求重新确认 —— 违反 §5 瞬时故障自动重试。ENOENT(缺 ghost.json)与- // JSON 解析失败是真的内容无效,保持确定性:前者带 ENOENT(分类器显式归确定性),- // 后者无 errno。- let rawBytes: Buffer;- try {- rawBytes = fs.readFileSync(- resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {- expect: 'file',- label: 'legacy manifest',- }),- );- } catch (err) {- throw err; // 原样抛,保留 errno(EACCES/EBUSY/EIO → 瞬时;ENOENT → 确定性)- }- let raw: unknown;- try {- raw = JSON.parse(rawBytes.toString('utf-8'));- } catch (err) {- throw new Error(`invalid manifest JSON: ${err instanceof Error ? err.message : String(err)}`);++ private async backfillLegacyApproval(++ dir: string,++ id: string,++ options: { expectedApprovalProjectionSha256?: string } = {},++ ): Promise<boolean> {++ const { projection, sha256 } = await readLegacyGhostApprovalProjection(dir, id);++ if (++ options.expectedApprovalProjectionSha256 !== undefined &&++ sha256 !== options.expectedApprovalProjectionSha256++ ) {++ throw new Error('legacy approval projection changed after recovery discovery');+ }- const validated = validateGhostManifest(raw);- 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.readLegacyDisabledMarkerForMigration(dir);- const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- };- const localeResources = this.readApprovedLocaleResources(dir, validated.manifest);- const iconDataUrl = this.readInstalledIconDataUrl(dir, validated.manifest) ?? undefined;- // skillContentSha256 是运行期判据,必须现算;技能目录异常(链接等)在此如实抛错。- const skillContentSha256 = await hashApprovedSkillContent(validated.manifest, dir);-export interface GhostManagerOptions {- /** 意识仓库根目录(生产:userData/cindy-brain;测试:os.tmpdir 下临时目录)。 */- getRootDir: () => string;- /** 装/卸成功后通知(index.ts 用它广播 ghosts:changed 到所有窗口)。 */- onChanged?: (ghosts: InstalledGhost[]) => void;- /** 当前宿主语言;插件未提供时由 shared 契约固定回退英文。 */- getLocale?: () => string;- /** Cindy 维护的发布者/审核公钥表;缺省为空,签名仍验完整性但不抬身份等级。 */- trustRegistry?: GhostTrustRegistry;- log?: GhostManagerLogger;-}+ await this.receiptStore.write(+ createGhostInstallReceipt({- manifest: validated.manifest,- localeResources,- enabled,- trust,- skillContentSha256,- ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),++ manifest: projection.manifest,++ localeResources: projection.localeResources,++ enabled: projection.enabled,++ trust: projection.trust,++ skillContentSha256: projection.skillContentSha256,++ ...(projection.iconDataUrl !== undefined ? { iconDataUrl: projection.iconDataUrl } : {}),+ }),+ { skillSourceDir: dir },+ );+ this.options.log?.info('legacy ghost approval migrated', {+ id,- enabled,- trustLevel: trust.level,++ enabled: projection.enabled,++ trustLevel: projection.trust.level,+ origin: 'legacy-migration',+ });+ return true;+ }-/** install / update 的失败分类 —— IPC 层据此映射错误码。 */-export type InstallRejection =- | { code: 'source-not-found'; reason: string }- | { code: 'file-invalid'; reason: string }- | { code: 'already-installed'; reason: string }- | { code: 'not-installed'; reason: string }- | { code: 'command-conflict'; reason: string }- | { code: 'io'; reason: string };+ /**+ * 「从已装目录重新确认」第一步:只读出确认卡需要的事实,零副作用。+ *+ * 这是本地包批准丢失(一次性迁移之后 receipt 又损坏/被删)时的第三条恢复路径 ——+ * 不用用户翻出原始 `.cindy` 文件,也不自动放行:字节从已装目录读,权限清单在确认卡+ * 上**全量**展示(无批准基线,全部按新增项列),用户逐条看过点确认才开 receipt。+ * 本地 `.cindy` 的运行字节本来就一直从这个可变目录现读(§7 登记),两条恢复路径的+ * 差别只是字节来源,授权边界同样是那张确认卡。+ *+ * `manifestSha256` 是「确认卡展示的」与「confirm 时批准的」之间的字节绑定:renderer+ * 原样回传,confirm 侧重读重算,对不上即拒 —— 与更新流程的 `expectedPackageSha256`+ * 同形,防确认间隙里 ghost.json 被换(#636 的同类窗口)。+ *+ * 随包插件一律拒:它们的批准由 provisioning 与种子逐字节对账后自动补,重启即恢复,+ * 不走人工确认(也不能走 —— 这条路的 trust 封顶在非官方档)。+ */+ async inspectInstalledReapproval(id: string): Promise<+ | {+ manifest: GhostManifest;+ trust: GhostTrustInfo;+ manifestSha256: string;+ approvalProjectionSha256: string;+ /** `.disabled` 镜像的读数:确认卡"立即开启"勾选的默认值,不重置用户停用偏好。 */+ localeResources: Record<string, GhostManifestLocaleResource>;+ iconDataUrl?: string;+ skillContentSha256: Record<string, string>;+ previouslyEnabled: boolean;+ }+ | { rejection: InstallRejection }+ > {+ this.ensureCurrentOwnerContextSync();+ if (!isValidGhostId(id) || this.options.isTrustedBundledId?.(id)) {+ return { rejection: { code: 'file-invalid', reason: '该插件不支持从安装目录重新确认' } };+ }+ 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') {+ return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };+ }+ } catch {+ return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };+ }+ let rawBytes: Buffer;+ try {- rawBytes = fs.readFileSync(- resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {- expect: 'file',- label: 'installed manifest',- }),- );++ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {++ expect: 'file',++ label: 'installed manifest',++ });++ const bytes = readBoundedFileNoFollowSync(manifestPath, GHOST_MANIFEST_MAX_BYTES, {++ containWithin: fs.realpathSync(dir),++ });++ if (bytes === null) throw new Error('manifest is missing or oversized');++ rawBytes = bytes;+ } catch (err) {+ return {+ rejection: {+ code: 'not-installed',+ reason: `安装目录里读不到清单:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBytes.toString('utf8'));+ } catch (err) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `清单不是合法 JSON:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ const validated = validateGhostManifest(parsed);+ if (!validated.ok) return { rejection: { code: 'file-invalid', reason: validated.reason } };+ if (validated.manifest.id !== id) {+ return { rejection: { code: 'file-invalid', reason: '清单 id 与安装目录不一致' } };+ }+ // tokenBroker 门控与装入侧同一条规则(XDT 授权 broker 仅第一方官方插件可用,+ // 不区分 dev/packaged):走已装目录重新确认的都不是随包插件,声明即拒。+ if (+ !isOfficialGhostId(id) &&+ (validated.manifest.network?.secrets ?? []).some((s) => s.oauth?.tokenBroker !== undefined)+ ) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `id "${id}" 声明了 oauth.tokenBroker——XDT 授权 broker 仅第一方官方插件可用`,+ },+ };+ }- const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- };+ let localeResources: Record<string, GhostManifestLocaleResource>;+ let skillContentSha256: Record<string, string>;++ let trust: GhostTrustInfo;++ try {++ trust = readLegacyInstallTrust(dir) ?? {++ level: 'unverified',++ publisherSigned: false,++ publisherVerified: false,++ reviewed: false,++ };++ } catch (err) {++ return {++ rejection: {++ code: 'file-invalid',++ reason: `安装目录信任数据不可读: ${err instanceof Error ? err.message : String(err)}`,++ },++ };++ }+ try {+ localeResources = this.readApprovedLocaleResources(dir, validated.manifest);+ skillContentSha256 = await hashApprovedSkillContent(validated.manifest, dir);+ } catch (err) {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `安装目录批准内容不可读或不一致: ${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ const iconDataUrl = this.readInstalledIconDataUrl(dir, validated.manifest) ?? undefined;+ const projection: InstalledReapprovalProjection = {+ manifest: validated.manifest,+ trust,+ localeResources,+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ skillContentSha256,+ };+ return {+ manifest: projection.manifest,+ trust: projection.trust,+ localeResources: projection.localeResources,+ ...(projection.iconDataUrl !== undefined ? { iconDataUrl: projection.iconDataUrl } : {}),+ skillContentSha256: projection.skillContentSha256,+ manifestSha256: crypto.createHash('sha256').update(rawBytes).digest('hex'),+ approvalProjectionSha256: hashInstalledReapprovalProjection(projection),+ previouslyEnabled: !this.isDisabledMarkerPresentSync(dir),+ };+ }-export type UninstallRejection =- | { code: 'invalid-id'; reason: string }- | { code: 'not-installed'; reason: string }- | { code: 'io'; reason: string };+ /**+ * 「从已装目录重新确认」第二步:用户在确认卡上点了同意,据此开 receipt。+ *+ * 与迁移(`backfillLegacyApproval`)的本质区别:**这是一次真实的用户确认**(用户+ * 刚看完全量权限清单),不受迁移 ledger 一次性门约束,来源记 `user-reapproval`。+ * 与迁移的共同点:trust 走同一个封顶读取器、技能字节现算钉指纹、只写状态根。+ */+ async reapproveInstalled(+ id: string,+ opts: {+ enable: boolean;+ expectedManifestSha256: string;+ expectedApprovalProjectionSha256: string;+ expectedInstalledApproval: string;+ },+ ): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {+ return this.runExclusiveMutation(() => this.reapproveInstalledUnlocked(id, opts));+ }-/**- * 意识仓库的 main 端管理者:一个意识一个子目录(rootDir/<id>/),目录即事实。- *- * 设计要点:- * - **目录即注册表**:没有额外的 DB / 索引文件,list() 每次实扫磁盘 ——- * 装了什么打开文件夹一目了然,坏一个目录只影响那一个意识(跳过 + warn);- * - **装载先落 staging 再切正式**(对齐 skillhub/installService 的做法):- * 解压全程发生在 `.cindy-installing-*` 临时目录,校验全过才 rename 到- * rootDir/<id>,任何一步失败都不会留下半截安装;- * - **防 zip 三件套**:条目数 / 解压总量上限防 zip bomb,路径归一化 +- * 越界检查防 zip-slip(压缩包里的 ../ 路径跳不出 staging);- * - **卸载防御**:id 先过格式校验(shared/ghost 同一份规则),再确认- * 目标是 rootDir 的直接子目录,杜绝借 id 删任意路径。- */-export class GhostManager {- constructor(private readonly options: GhostManagerOptions) {}+ private async reapproveInstalledUnlocked(+ id: string,+ opts: {+ enable: boolean;+ expectedManifestSha256: string;+ expectedApprovalProjectionSha256: string;+ expectedInstalledApproval: string;+ },+ ): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {+ // 确认期间批准状态不得变过:与更新流程同款前置条件(token 由 Main 现读比对)。+ const currentToken = ghostInstallApprovalToken(+ this.list().find((g) => g.manifest.id === id)?.approval,+ );+ if (currentToken !== opts.expectedInstalledApproval || currentToken.startsWith('approved')) {+ return {+ rejection: { code: 'state-changed', reason: '插件批准状态在确认后发生了变化,请重新确认' },+ };+ }+ // 重走只读检查(含随包拒收/清单校验),并绑定确认卡展示时的清单字节。+ const inspected = await this.inspectInstalledReapproval(id);+ if ('rejection' in inspected) return inspected;+ if (inspected.manifestSha256 !== opts.expectedManifestSha256) {+ return {+ rejection: { code: 'state-changed', reason: '插件清单在确认后发生了变化,请重新确认' },+ };+ }+ if (inspected.approvalProjectionSha256 !== opts.expectedApprovalProjectionSha256) {+ return {+ rejection: {+ code: 'state-changed',+ reason: '安装目录批准内容在确认后发生了变化,请重新确认',+ },+ };+ }+ // 指令查重与装入/更新同一条规则(豁免自己):重新确认不是给撞名指令开的后门。+ if (inspected.manifest.command !== undefined) {+ const commandFold = inspected.manifest.command.toLowerCase();+ const holder = this.list().find(+ (g) =>+ g.manifest.id !== id &&+ g.manifest.command !== undefined &&+ g.manifest.command.toLowerCase() === commandFold,+ );+ if (holder) {+ return {+ rejection: {+ code: 'command-conflict',+ reason: `指令 /${inspected.manifest.command} 已被已装意识「${holder.manifest.name}」(${holder.manifest.id})占用`,+ },+ };+ }+ }+ const contentRoot = this.contentRootDir();+ const dir = path.join(contentRoot, id);+ if (!this.isRealDirChild(contentRoot, id)) {+ return {+ rejection: { code: 'state-changed', reason: '插件安装目录在确认后发生了变化,请重新确认' },+ };+ }+ const marker = path.join(dir, DISABLED_MARKER_FILE);+ let markerExisted = false;+ try {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ markerExisted = true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ // 先提交兼容镜像,再提交权威 receipt。否则 marker 失败会留下“返回成功但实际+ // 启停态与 receipt 矛盾”的部分成功。没有状态变化时不触碰 marker。+ if (opts.enable) {+ if (markerExisted) await fs.promises.rm(marker, { force: true });+ } else if (!markerExisted) {+ await fs.promises.writeFile(marker, '', { flag: 'wx' });+ }+ } catch (err) {+ return {+ rejection: {+ code: 'io',+ reason: `启停标记写入失败:${err instanceof Error ? err.message : String(err)}`,+ },+ };+ }+ try {+ const localeResources = inspected.localeResources;+ const iconDataUrl = inspected.iconDataUrl;+ const skillContentSha256 = inspected.skillContentSha256;+ await this.receiptStore.write(+ createGhostInstallReceipt({+ manifest: inspected.manifest,+ localeResources,+ enabled: opts.enable,+ trust: inspected.trust,+ skillContentSha256,+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ }),+ { skillSourceDir: dir },+ );+ } catch (err) {+ const markerChanged = opts.enable ? markerExisted : !markerExisted;+ if (markerChanged) {+ try {+ if (!this.isRealDirChild(contentRoot, id)) {+ throw new Error('ghost install directory changed before marker rollback');+ }+ if (markerExisted) {+ try {+ if (classifyGhostDirEntrySync(marker) !== 'file') {+ throw new Error('ghost disabled marker is not a regular file');+ }+ } catch (markerError) {+ if ((markerError as NodeJS.ErrnoException).code !== 'ENOENT') throw markerError;+ await fs.promises.writeFile(marker, '', { flag: 'wx' });+ }+ } else {+ await fs.promises.rm(marker, { force: true });+ }+ } catch (rollbackErr) {+ (this.options.log?.error ?? this.options.log?.warn)?.call(+ this.options.log,+ 'ghost reapproval receipt failed and marker rollback also failed',+ {+ id,+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),+ },+ );+ }+ }+ return {+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },+ };+ }+ this.untrustedApprovals.delete(this.isolationKey(id));+ this.options.log?.info('ghost reapproved from installed dir', {+ id,+ enabled: opts.enable,+ trustLevel: inspected.trust.level,+ origin: 'user-reapproval',+ });+ const ghost = this.list().find((g) => g.manifest.id === id);+ if (!ghost) return { rejection: { code: 'io', reason: '重新确认后读不到插件清单' } };+ this.options.onChanged?.(this.list());+ return { ghost };+ }/** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */list(): InstalledGhost[] {@@@ -1770,7 -144,7 +1932,6 @@@});continue;}-- const hostMetadata = this.readInstalledHostMetadata(dir);// 历史 manifest / receipt 中可能保留已移除的资源搜索元数据;它不参与当前// 运行时入口,插件本体与已批准的其它能力仍按现有授权照常可用。const manifest = v.manifest;@@@ -1783,12 -154,9 +1944,17 @@@result.push({manifest: localizedManifest,dir,- enabled: !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE)),- ...(hostMetadata ? { trust: hostMetadata.trust } : {}),+ enabled: false,+ approval: { state: approvalResult.state },- // trust 仅作展示徽标,不授予运行权(运行仍由 enabled:false + approval 门控)。- ...(hostMetadata ? { trust: hostMetadata.trust } : {}),++ // 未批准安装目录里的 trust 镜像是可变字节,不能作为可信展示事实。++ trust: {++ level: 'unverified',++ publisherSigned: false,++ publisherVerified: false,++ reviewed: false,++ },...(iconDataUrl !== null ? { iconDataUrl } : {}),+ ...(this.options.isTrustedBundledId?.(entry.name) ? { builtin: true } : {}),});}result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));@@@ -2045,49 -256,49 +2211,6 @@@}}-- /** 读取主机安装时写下的信任快照与权限 receipt;坏文件一律 fail closed。 */-- private readInstalledHostMetadata(dir: string): GhostInstalledHostMetadata | null {-- try {-- const bytes = readBoundedFileNoFollowSync(path.join(dir, TRUST_METADATA_FILE), 64 * 1024);-- if (bytes === null) return null;-- const raw = JSON.parse(bytes.toString('utf8')) as Record<string, unknown>;-- if (-- !raw ||-- typeof raw !== 'object' ||-- typeof raw.level !== 'string' ||-- !['cindy-official', 'reviewed', 'verified-publisher', 'unverified'].includes(raw.level) ||-- typeof raw.publisherSigned !== 'boolean' ||-- typeof raw.publisherVerified !== 'boolean' ||-- typeof raw.reviewed !== 'boolean'-- ) return null;-- const trust: GhostTrustInfo = {-- level: raw.level as GhostTrustInfo['level'],-- publisherSigned: raw.publisherSigned,-- publisherVerified: raw.publisherVerified,-- reviewed: raw.reviewed,-- ...(typeof raw.publisherName === 'string' ? { publisherName: raw.publisherName } : {}),-- ...(typeof raw.publisherKeyId === 'string' ? { publisherKeyId: raw.publisherKeyId } : {}),-- ...(typeof raw.reviewerName === 'string' ? { reviewerName: raw.reviewerName } : {}),-- ...(typeof raw.unknownReviewer === 'boolean' ? { unknownReviewer: raw.unknownReviewer } : {}),-- };-- const approval = raw.approvedAtResourceProvider;-- const approvedAtResourceProviderTool =-- approval-- && typeof approval === 'object'-- && !Array.isArray(approval)-- && Object.keys(approval).length === 1-- && typeof (approval as Record<string, unknown>).tool === 'string'-- ? (approval as Record<string, string>).tool-- : undefined;-- return {-- trust,-- ...(approvedAtResourceProviderTool ? { approvedAtResourceProviderTool } : {}),-- };-- } catch {-- return null;-- }-- }--/*** 只验不装:读 .cindy → 解包 → 校验清单,返回清单(含 icon data URL),* 零副作用。「装意识前弹确认」(README 安全原则)的数据来源 —— 三个装入@@@ -2905,335 -799,8 +3028,336 @@@...(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 };+ }++ /**+ * 随包种子已经由 provisioning 层逐字节对账后,为其建立 Host 批准状态。+ * 该入口不得用于市场包或任意本地目录;它不替代用户安装确认。id 必须落在注入的+ * 随包种子清单里(`isTrustedBundledId`)。+ *+ * `markerEnabled` 是安装目录 `.disabled` 兼容镜像的读数,**只往停用方向合并,+ * 不往启用方向翻**:receipt 才是授权事实,镜像文件可被外部因素移除(AV 隔离+ * 恢复/同步冲突解析/手动清理),拿它覆写 receipt 会让用户显式停用的插件在下一轮+ * 对账被静默重新启用 —— 无确认、无审计,且带 skill 槽的插件会随之重新挂进全局+ * 技能链。反方向(镜像说停用、receipt 说启用)必须照办:停用是安全方向,而且+ * 旧客户端只会写镜像文件。重新启用只有用户显式 `setEnabled(true)` 一条路。+ */+ private async publishTrustedBundledSeedUnlocked(+ id: string,+ sourceDirInput: string,+ options: { disabled: boolean },+ ): Promise<void> {+ if (+ !isValidGhostId(id) ||+ this.options.isTrustedBundledId?.(id) !== true ||+ this.options.isTrustedBundledSource?.(id, sourceDirInput) !== true+ ) {+ throw new Error('builtin seed publish source is not trusted');+ }+ const sourceDir = path.resolve(sourceDirInput);+ if (classifyGhostDirEntrySync(sourceDir) !== 'directory') {+ throw new Error('builtin seed publish source is not a real directory');+ }+ const packageSha256 = await hashApprovedDirectory(sourceDir);+ const root = this.contentRootDir();+ const finalDir = path.join(root, id);+ const rand = crypto.randomBytes(4).toString('hex');+ const stagingDir = path.join(root, `.cindy-installing-${id}-${rand}`);+ const backupDir = path.join(root, `.cindy-updating-${id}-${rand}`);+ let finalKind: GhostDirEntryKind | 'missing';+ try {+ finalKind = classifyGhostDirEntrySync(finalDir);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ finalKind = 'missing';+ }+ if (finalKind !== 'missing' && finalKind !== 'directory') {+ throw new Error('builtin installed path is not a real directory');+ }++ try {+ await copyBundledSeedDirectory(sourceDir, stagingDir);+ if (options.disabled) {+ await fs.promises.writeFile(path.join(stagingDir, DISABLED_MARKER_FILE), '');+ }+ if (finalKind === 'missing') {+ await this.receiptStore.writePendingMutation(id, { kind: 'install', packageSha256 });+ this.untrustedApprovals.add(this.isolationKey(id));+ await fs.promises.rename(stagingDir, finalDir);+ return;+ }++ await this.receiptStore.writePendingMutation(id, {+ kind: 'update',+ packageSha256,+ 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',+ packageSha256,+ backupDirName: path.basename(backupDir),+ phase: 'backed-up',+ });+ await fs.promises.rename(stagingDir, finalDir);+ await this.receiptStore.writePendingMutation(id, {+ kind: 'update',+ packageSha256,+ backupDirName: path.basename(backupDir),+ phase: 'published',+ });+ } catch (error) {+ await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined);+ const backupKind = await classifyGhostDirEntry(backupDir).catch((entryError) => {+ if ((entryError as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw entryError;+ });+ const publishedKind = await classifyGhostDirEntry(finalDir).catch((entryError) => {+ if ((entryError as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw entryError;+ });+ if (backupKind === 'directory' && publishedKind === null) {+ 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) {+ try {+ await this.receiptStore.clearPendingMutation(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ } catch {+ // Keep the in-process quarantine while the journal remains.+ }+ }+ throw error;+ }+ }++ async approveTrustedBundledInstall(+ manifest: GhostManifest,+ markerEnabled: boolean,+ options: { sourceDir: string },+ ): Promise<boolean> {+ return this.runExclusiveMutation((mutation) =>+ mutation.approveTrustedBundledInstall(manifest, markerEnabled, options),+ );+ }++ private async approveTrustedBundledInstallUnlocked(+ manifest: GhostManifest,+ markerEnabled: boolean,+ options: { sourceDir: string },+ ): Promise<boolean> {+ if (this.options.isTrustedBundledId?.(manifest.id) !== true) {+ throw new Error(+ `approveTrustedBundledInstall 只服务随包种子插件:${manifest.id} 不在种子清单里`,+ );+ }+ const dir = path.join(this.contentRootDir(), manifest.id);+ if (!options || typeof options.sourceDir !== 'string' || options.sourceDir.trim() === '') {+ throw new Error('approveTrustedBundledInstall requires a verified bundled source directory');+ }+ const sourceDir = path.resolve(options.sourceDir);+ if (sourceDir === path.resolve(dir)) {+ throw new Error('approveTrustedBundledInstall refuses the mutable installed directory');+ }+ if (this.options.isTrustedBundledSource?.(manifest.id, sourceDir) !== true) {+ throw new Error('approveTrustedBundledInstall source is outside the trusted seed roster');+ }+ if (classifyGhostDirEntrySync(sourceDir) !== 'directory') {+ throw new Error('approveTrustedBundledInstall source is not a real directory');+ }+ const sourceManifestPath = resolveGhostContentPathSync(sourceDir, GHOST_MANIFEST_FILE, {+ expect: 'file',+ label: 'bundled manifest',+ });+ const sourceManifestRaw = JSON.parse(fs.readFileSync(sourceManifestPath, 'utf8')) as unknown;+ const sourceManifest = validateGhostManifest(sourceManifestRaw);+ const expectedManifest = validateGhostManifest(manifest);+ if (+ !sourceManifest.ok ||+ !expectedManifest.ok ||+ !isDeepStrictEqual(sourceManifest.manifest, expectedManifest.manifest)+ ) {+ throw new Error('approveTrustedBundledInstall source manifest does not match approval');+ }+ const localeResources = this.readApprovedLocaleResources(sourceDir, manifest);+ const iconDataUrl = this.readInstalledIconDataUrl(sourceDir, manifest) ?? undefined;+ const packageSha256 = await hashApprovedDirectory(sourceDir);+ const skillContentSha256 = await hashApprovedSkillContent(manifest, sourceDir);+ const pendingPublish = this.receiptStore.readPendingMutationSync(manifest.id);+ if (pendingPublish.state === 'invalid' || pendingPublish.state === 'unreadable') {+ throw new Error(`builtin seed publish journal is ${pendingPublish.state}`);+ }+ if (pendingPublish.state === 'valid' && pendingPublish.mutation.kind === 'uninstall') {+ throw new Error('builtin seed publish journal conflicts with uninstall');+ }+ if (+ pendingPublish.state === 'valid' &&+ (pendingPublish.mutation.kind === 'install' || pendingPublish.mutation.kind === 'update') &&+ pendingPublish.mutation.packageSha256 !== packageSha256+ ) {+ throw new Error('builtin seed publish journal does not match immutable source');+ }+ const trust: GhostTrustInfo = {+ level: 'cindy-official',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: true,+ };+ const current = this.readApproval(manifest.id);+ // priorEnabled 直接读盘上的 receipt 而不是 readApproval 的投影:进程内隔离态的+ // receipt 不可作授权事实,但"曾经停用"这个位只用于往下拉,是 fail closed 方向,+ // 采纳它只会更保守 —— 否则"隔离 + 镜像同时丢失"的组合会让自愈把插件带回启用。+ const persisted = current.state === 'approved' ? current : this.receiptStore.read(manifest.id);+ const priorEnabled = persisted.state === 'approved' ? persisted.receipt.enabled : undefined;+ const enabled = priorEnabled === undefined ? markerEnabled : markerEnabled && priorEnabled;+ if (enabled !== markerEnabled) {+ // receipt 钉着停用而镜像丢了:把 `.disabled` 补写回去,守住"回滚到旧客户端时+ // 按镜像判启停"的降级承诺。写不进不影响批准事实,receipt 仍是权威。+ try {+ this.writeDisabledMarkerSync(dir);+ } catch (err) {+ this.options.log?.warn('ghost disabled mirror rewrite failed', {+ id: manifest.id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ if (+ current.state === 'approved' &&+ isDeepStrictEqual(current.receipt.manifest, manifest) &&+ isDeepStrictEqual(current.receipt.localeResources, localeResources) &&+ isDeepStrictEqual(current.receipt.trust, trust) &&+ isDeepStrictEqual(current.receipt.skillContentSha256, skillContentSha256) &&+ current.receipt.packageSha256 === packageSha256 &&+ current.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,+ enabled,+ });+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ return true;+ }+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ return false;+ }+ await this.receiptStore.write(+ createGhostInstallReceipt({+ manifest,+ localeResources,+ enabled,+ trust,+ skillContentSha256,+ packageSha256,+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),+ }),+ { skillSourceDir: sourceDir },+ );+ await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ return true;+ }++ private async finishTrustedBundledPublish(+ id: string,+ pending: ReturnType<GhostInstallReceiptStore['readPendingMutationSync']>,+ ): Promise<void> {+ if (pending.state === 'missing') return;+ if (pending.state !== 'valid' || pending.mutation.kind === 'uninstall') {+ throw new Error('builtin seed publish journal cannot be committed');+ }+ await this.receiptStore.clearPendingMutation(id);+ if (pending.mutation.kind === 'update') {+ await fs.promises+ .rm(path.join(this.contentRootDir(), pending.mutation.backupDirName), {+ recursive: true,+ force: true,+ })+ .catch(() => undefined);+ }+ }++ /**+ * 撤销 Host 批准。**契约是"调用返回后该插件一定不再被授权运行"**:正常路径删掉+ * receipt 与技能快照;删不掉(状态根不可写等)时退回进程内隔离,不把失败原样抛给+ * 调用方去自己 fail closed —— 那正是上一版留下 fail-open 的地方。+ */+ async removeInstallApproval(id: string): Promise<boolean> {+ return this.runExclusiveMutation((mutation) => mutation.removeInstallApproval(id));+ }++ private async removeInstallApprovalUnlocked(id: string): Promise<boolean> {+ try {+ await this.receiptStore.remove(id);+ this.untrustedApprovals.delete(this.isolationKey(id));+ return true;+ } catch (err) {+ this.untrustedApprovals.add(this.isolationKey(id));+ // 这行是"插件已转进程内隔离"的唯一可观测信号,不能因为注入的 logger 没实现+ // error 就静默丢掉 —— 退化到 warn。+ const log = this.options.log;+ (log?.error ?? log?.warn)?.call(+ log,+ 'ghost approval could not be removed; kept untrusted in-process',+ { id, error: err instanceof Error ? err.message : String(err) },+ );+ return false;+ }+ }++ private readApprovedLocaleResources(+ dir: string,+ manifest: GhostManifest,+ ): Record<string, GhostManifestLocaleResource> {+ const resources: Record<string, GhostManifestLocaleResource> = {};++ const realDir = fs.realpathSync(dir);+ for (const localePath of Object.values(manifest.locales ?? {})) {+ if (!localePath) continue;+ // 逐段解析:只 lstat 最终段挡不住"中间段被换成链接"——那会把插件目录之外的+ // JSON 读成已批准的界面文案钉进 receipt。判据与技能目录同源。+ const absPath = resolveGhostContentPathSync(dir, localePath, {+ expect: 'file',+ label: 'bundled locale',+ });- const stat = fs.lstatSync(absPath);- if (stat.size > GHOST_LOCALE_MAX_BYTES) {- throw new Error(`bundled locale missing or oversized: ${localePath}`);- }- const raw = JSON.parse(fs.readFileSync(absPath, 'utf8')) as unknown;++ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {++ containWithin: realDir,++ });++ if (bytes === null) throw new Error(`bundled locale missing or oversized: ${localePath}`);++ const raw = JSON.parse(bytes.toString('utf8')) as unknown;+ const validated = validateGhostManifestLocaleResource(raw, manifest);+ if (!validated.ok) throw new Error(`bundled locale invalid: ${localePath}`);+ resources[localePath] = validated.resource;+ }+ return resources;}/** 解压 zip 条目到 staging 目录(install / update 共用;含 zip-slip / bomb 防御)。 */diff --cc apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 5abbc374c1,354e6f5898..cafc7f718f--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@@ -5,14 -5,8 +5,14 @@@ import path from 'node:path'import JSZip from 'jszip';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { InstalledGhost } from '../../../shared/ghost';-import { GhostManager } from '../GhostManager';+import {+ GHOST_SKILL_MD_MAX_BYTES,+ ghostInstallApprovalToken,+ validateGhostManifest,+ type InstalledGhost,+} from '../../../shared/ghost';- import { GhostManager } from '../GhostManager';++import { GhostManager, readLegacyGhostApprovalProjection } from '../GhostManager';+import { hashApprovedSkillContent } from '../ghostInstallReceipt';/** 每个用例独立的临时仓库根 + 源文件目录(规则 23:测试路径一律 os.tmpdir)。 */let workDir: string;@@@ -97,3640 -82,395 +97,3851 @@@ async function makeCindyreturn out;}+/**+ * 造一份**旧布局**安装(#1080 之前的形态):直接把文件写进 rootDir/<id>/,不经+ * manager.install() —— 因此状态根里**没有** receipt。用于「从旧状态升级」的迁移回归。+ * 三份旧事实源:ghost.json(必)、.disabled(停用镜像,可选)、.cindy-trust.json(信任镜像,可选)。+ */+async function writeLegacyInstall(+ id: string,+ manifest: Record<string, unknown>,+ opts: {+ disabled?: boolean;+ trust?: Record<string, unknown> | 'omit';+ files?: Record<string, string>;+ } = {},+): Promise<string> {+ const dir = path.join(rootDir, id);+ await fs.promises.mkdir(dir, { recursive: true });+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), JSON.stringify(manifest));+ await fs.promises.writeFile(path.join(dir, 'main.js'), 'console.log("legacy")');+ for (const [rel, content] of Object.entries(opts.files ?? {})) {+ const abs = path.join(dir, ...rel.split('/'));+ await fs.promises.mkdir(path.dirname(abs), { recursive: true });+ await fs.promises.writeFile(abs, content);+ }+ if (opts.disabled) await fs.promises.writeFile(path.join(dir, '.disabled'), '');+ if (opts.trust !== 'omit') {+ await fs.promises.writeFile(+ path.join(dir, '.cindy-trust.json'),+ JSON.stringify(+ opts.trust ?? {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ ),+ );+ }+ return dir;+}+++async function recoveredProjectionOptions(...ids: string[]): Promise<{++ expectedApprovalProjectionSha256ById: Record<string, string>;++}> {++ const expectedApprovalProjectionSha256ById: Record<string, string> = {};++ for (const id of ids) {++ expectedApprovalProjectionSha256ById[id] = (++ await readLegacyGhostApprovalProjection(path.join(rootDir, id), id)++ ).sha256;++ }++ return { expectedApprovalProjectionSha256ById };++}+++/** 迁移台账路径(默认状态根 = <workDir>/ghosts-install-state)。 */+function migrationLedgerPath(): string {+ return path.join(workDir, 'ghosts-install-state', '.legacy-migration.json');+}+async function expectRejection(- result: Awaited<ReturnType<GhostManager['install']>>,+ result: unknown,code: string,): Promise<void> {- expect('rejection' in result, JSON.stringify(result)).toBe(true);+ expect(+ typeof result === 'object' && result !== null && 'rejection' in result,+ JSON.stringify(result),+ ).toBe(true);expect((result as { rejection: { code: string } }).rejection.code).toBe(code);}-describe('GhostManager · install', () => {- it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {- const manifest = {- ...goodManifest(),- name: 'Base name',- description: 'Base description',- locales: {- en: 'locales/en.json',- 'zh-CN': 'locales/zh-CN.json',- },+async function updateGhost(+ cindyPath: string,+ id = 'hello',+): ReturnType<GhostManager['update']> {+ const installed = manager.list().find((ghost) => ghost.manifest.id === id);+ return manager.update(cindyPath, {+ expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval),+ });+}++describe('hashApprovedSkillContent · item.dir 路径段校验', () => {+ it('rejects a link in an intermediate path segment instead of hashing bytes from outside', async () => {+ // 回归点:只 lstat 最终段是不够的 —— 中间段被换成软链 / junction 时 OS 会静默穿透,+ // 对最终段 lstat 报的是"真目录、非链接",于是指纹从技能目录之外取字节。首次批准+ // 那条路径的指纹是现算的,外部内容会被钉成"批准字节"再复制成快照,而 frontmatter+ // 一致性校验只看 name/description(manifest 里公开可抄),拦不住。所以这里必须抛错,+ // 不能返回一个哈希。+ const validated = validateGhostManifest({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ });+ if (!validated.ok) throw new Error(validated.reason);++ const base = path.join(workDir, 'plugin');+ const evil = path.join(workDir, 'evil');+ await fs.promises.mkdir(path.join(base, 'skills', 'demo'), { recursive: true });+ await fs.promises.mkdir(path.join(evil, 'demo'), { recursive: true });+ await fs.promises.writeFile(+ path.join(base, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ );+ await fs.promises.writeFile(+ path.join(evil, 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 正常结构先能算出来,确认用例本身走到了目标代码。+ await expect(hashApprovedSkillContent(validated.manifest, base)).resolves.toHaveProperty(+ 'skills/demo',+ );++ // 把**中间段** skills 换成指向外部的链接。+ await fs.promises.rm(path.join(base, 'skills'), { recursive: true, force: true });+ try {+ await fs.promises.symlink(+ evil,+ path.join(base, 'skills'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。+ }++ await expect(hashApprovedSkillContent(validated.manifest, base)).rejects.toThrow(+ /path segment is a link/,+ );+ });+});++describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {+ /** 带 skill 槽的旧布局清单 + 配套 SKILL.md(frontmatter 与声明逐字一致)。 */+ const legacySkillManifest = (id = 'skilled'): Record<string, unknown> => ({+ ...goodManifest(id),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ });+ const legacySkillFiles = (): Record<string, string> => ({+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });++ it('市场/本地旧安装无感迁移:升级后仍启用、列 approved、写下迁移台账', async () => {+ await writeLegacyInstall('hello', goodManifest());+ // 迁移前:没有 receipt → 一律 fail closed(这正是 #1080 被回滚的现场)。+ expect(manager.list()[0]).toMatchObject({ enabled: false, approval: { state: 'legacy-unapproved' } });++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ // 迁移后:用户什么都没做,插件照旧可用。+ expect(manager.list()[0]).toMatchObject({+ enabled: true,+ approval: { state: 'approved' },+ });+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ });+++ it('未批准或 receipt 损坏的插件不展示可变 trust 镜像', async () => {++ const forgedTrust = {++ level: 'cindy-official' as const,++ publisherSigned: true,++ publisherVerified: true,++ reviewed: true,++ publisherName: 'Forged publisher',++ reviewerName: 'Forged reviewer',+ };- const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({- name,- description,- tools: { do_thing: { description: toolDescription } },++ await writeLegacyInstall('legacy', goodManifest('legacy'), { trust: forgedTrust });++ await writeLegacyInstall('invalid', goodManifest('invalid'), { trust: forgedTrust });++ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });++ await fs.promises.writeFile(++ path.join(workDir, 'ghosts-install-state', 'invalid.json'),++ JSON.stringify({ schemaVersion: 1, id: 'invalid' }),++ );++++ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));++ expect(byId.legacy).toMatchObject({++ approval: { state: 'legacy-unapproved' },++ trust: {++ level: 'unverified',++ publisherSigned: false,++ publisherVerified: false,++ reviewed: false,++ },+ });- const cindy = await makeCindy('localized.cindy', manifest, {- 'locales/en.json': locale('English name', 'English description', 'English tool'),- 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),++ expect(byId.invalid).toMatchObject({++ approval: { state: 'invalid' },++ trust: {++ level: 'unverified',++ publisherSigned: false,++ publisherVerified: false,++ reviewed: false,++ },+ });- const result = await manager.install(cindy);- expect(result).toMatchObject({- ghost: {- manifest: {- name: '中文名称',- description: '中文说明',- resolvedLocale: 'zh-CN',- tools: [{ name: 'do_thing', description: '中文工具' }],- },++ expect(byId.legacy.trust).not.toHaveProperty('publisherName');++ expect(byId.invalid.trust).not.toHaveProperty('reviewerName');++ });+++ it('旧安装的停用态被保留:.disabled 镜像 → receipt.enabled=false', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ await manager.migrateLegacyApprovalsOnce();+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });+ });++ it('信任镜像被保留;缺失时保守降级为 unverified 而不是让迁移失败', async () => {+ await writeLegacyInstall('trusted', goodManifest('trusted'), {+ trust: {+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: false,+ publisherName: 'Acme',},});+ await writeLegacyInstall('bare', goodManifest('bare'), { trust: 'omit' });+ await manager.migrateLegacyApprovalsOnce();+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g]));+ expect(byId.trusted.trust).toMatchObject({ level: 'verified-publisher', publisherName: 'Acme' });+ expect(byId.trusted.enabled).toBe(true);+ // 信任文件缺失不阻断迁移:插件照旧可用,只是展示为 unverified(旧模型读同一文件也如此)。+ expect(byId.bare.trust).toMatchObject({ level: 'unverified' });+ expect(byId.bare.enabled).toBe(true);+ });- hostLocale = 'ja';- expect(manager.list()[0].manifest).toMatchObject({- name: 'English name',- description: 'English description',- resolvedLocale: 'ja',- tools: [{ name: 'do_thing', description: 'English tool' }],+ it('skill 槽旧安装迁移后:快照建好、字节指纹钉住、对账认可挂链', async () => {+ await writeLegacyInstall('skilled', legacySkillManifest(), { files: legacySkillFiles() });+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['skilled']);+ const ghost = manager.list()[0];+ expect(ghost).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(ghost.approvedSkillRoot).toBeTruthy();+ // 迁移出的快照必须能被技能对账认可(字节与 receipt 指纹逐字节对上),否则技能链断。+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);+ });++ it('全局一次性:台账落地后,新出现的无 receipt 目录不再被迁移(fail closed)', async () => {+ await writeLegacyInstall('first', goodManifest('first'));+ await manager.migrateLegacyApprovalsOnce();+ expect(manager.list().find((g) => g.manifest.id === 'first')?.approval.state).toBe('approved');++ // 台账已在。此后再冒出一个没有 receipt 的目录(可能是删了 receipt 想骗迁移,或+ // 真的新拷进来的旧目录)——迁移不再触发,它保持 fail closed。删 receipt 想"从可变+ // 安装目录重建授权"这条路被这道门堵死。+ await writeLegacyInstall('second', goodManifest('second'));+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list().find((g) => g.manifest.id === 'second')?.approval.state).toBe(+ 'legacy-unapproved',+ );+ });++ it('迁移绝不改动安装目录三文件(回滚到旧客户端仍按安装目录判定,§5 兜底第 4 条)', async () => {+ const dir = await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const before = {+ manifest: await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'),+ disabled: fs.existsSync(path.join(dir, '.disabled')),+ trust: await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8'),+ };+ await manager.migrateLegacyApprovalsOnce();+ expect(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8')).toBe(before.manifest);+ expect(fs.existsSync(path.join(dir, '.disabled'))).toBe(before.disabled);+ expect(await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8')).toBe(before.trust);+ });++ it('manifest 不合法的旧目录不迁移,保持 fail closed,不写出坏 receipt', async () => {+ const dir = path.join(rootDir, 'broken');+ await fs.promises.mkdir(dir, { recursive: true });+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), '{ not valid json');+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.failed).toEqual(['broken']);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'broken.json'))).toBe(false);+ });++ it('随包种子 id 跳过迁移(交给 provisioning 的逐字节对账补批准)', async () => {+ const seededManager = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ isTrustedBundledId: (id) => id === 'hello',});- hostLocale = 'fr-FR';- expect(manager.list()[0].manifest).toMatchObject({- name: 'English name',- resolvedLocale: 'en',+ await writeLegacyInstall('hello', goodManifest());+ const outcome = await seededManager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [], retryPending: [] });+ // 没有替它写 receipt:provisioning 才是随包插件的批准入口。+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });++ it('瞬时状态根 IO 不封门:台账停在 in-progress,下次启动自动续跑治愈', async () => {+ await writeLegacyInstall('hello', goodManifest());+ // 第一轮:receipt 落盘的 rename 吃一次 EACCES(模拟杀软/句柄占用的环境抖动)。+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}hello.json`)) {+ renameSpy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);});+ const first = await manager.migrateLegacyApprovalsOnce();+ // 瞬时错不算"内容无效":不进 failed(那会写进 completed 台账永久封门),+ // 记 retryPending、台账停在 in-progress。+ expect(first.retryPending).toEqual(['hello']);+ expect(first.failed).toEqual([]);+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ pendingIds?: string[];+ };+ expect(ledger.state).toBe('in-progress');+ expect(ledger.pendingIds).toEqual(['hello']);++ // 第二轮(下次启动):环境恢复,自动续跑治愈,不需要用户操作。+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ const finalLedger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string };+ expect(finalLedger.state).toBe('completed');});- it('已安装 locale 或其父目录被替换为目录外软链时拒绝读取并回退基础清单', async () => {- hostLocale = 'en';- const manifest = {- ...goodManifest(),- name: 'Base name',- locales: { en: 'locales/en.json' },+ it('读 legacy ghost.json 的瞬时 IO(EACCES)判瞬时、不永久封门(P1 回归)', async () => {+ await writeLegacyInstall('hello', goodManifest());- const realReadFileSync = fs.readFileSync;- // 只让 <root>/hello/ghost.json 的读吃一次 EACCES(模拟杀软/句柄占用),其余照常。++ const realOpenSync = fs.openSync;++ // 只让 <root>/hello/ghost.json 的单句柄安全读取吃一次 EACCES(模拟杀软/句柄占用),++ // 其余照常。+ const spy = vi- .spyOn(fs, 'readFileSync')- .mockImplementation(((p: fs.PathOrFileDescriptor, ...rest: unknown[]) => {++ .spyOn(fs, 'openSync')++ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {+ if (typeof p === 'string' && p.endsWith(path.join('hello', 'ghost.json'))) {+ spy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }- return (realReadFileSync as (...a: unknown[]) => unknown)(p, ...rest);- }) as typeof fs.readFileSync);++ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);++ }) as typeof fs.openSync);++ const first = await manager.migrateLegacyApprovalsOnce();+ // 修复前:readFileSync 的错被包成无 code 的 new Error → 误判确定性 failed →+ // 写进 completed 台账永久封门。修复后:保留 errno → 判瞬时 → retryPending + in-progress。+ expect(first.retryPending).toEqual(['hello']);+ expect(first.failed).toEqual([]);- const ledger = JSON.parse(realReadFileSync(migrationLedgerPath(), 'utf8')) as {++ const ledger = JSON.parse(fs.readFileSync(migrationLedgerPath(), 'utf8')) as {+ state?: string;};- const locale = (name: string) => JSON.stringify({- name,- tools: { do_thing: { description: 'Localized tool' } },+ expect(ledger.state).toBe('in-progress');++ // 下轮环境恢复:自动续跑治愈,不需要用户重新确认。+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ 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 cindy = await makeCindy('localized-symlink.cindy', manifest, {- 'locales/en.json': locale('Packaged name'),++ 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'],});- await manager.install(cindy);- const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');- const outsidePath = path.join(workDir, 'outside-locale.json');- await fs.promises.writeFile(outsidePath, locale('Outside name'));- await fs.promises.rm(localePath);- try {- await fs.promises.symlink(outsidePath, localePath, 'file');- } catch {- return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。- }+ expect(manager.list()[0]).toMatchObject({ approval: { state: 'legacy-unapproved' } });- expect(manager.list()[0].manifest).toMatchObject({- name: 'Base name',- resolvedLocale: 'en',- tools: [{ name: 'do_thing', description: '做点事' }],+ 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');+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');+ // 模拟 #1080 历史状态没有 ledger;receipt 本身只是在本轮被 AV/权限瞬时锁住。+ await fs.promises.rm(migrationLedgerPath());- const realLstatSync = fs.lstatSync;- const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {++ const realOpenSync = fs.openSync;++ const openSpy = vi.spyOn(fs, 'openSync');++ openSpy.mockImplementation((target, ...args) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {- lstatSpy.mockRestore();++ openSpy.mockRestore();+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }- return realLstatSync(target, options as never);++ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);});- const localesDir = path.dirname(localePath);- const outsideLocalesDir = path.join(workDir, 'outside-locales');- await fs.promises.rm(localesDir, { recursive: true, force: true });- await fs.promises.mkdir(outsideLocalesDir);- await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));- await fs.promises.symlink(- outsideLocalesDir,- localesDir,- process.platform === 'win32' ? 'junction' : 'dir',+ const first = await manager.migrateLegacyApprovalsOnce();++ expect(first).toEqual({ migrated: [], skipped: [], failed: [], retryPending: ['hello'] });+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });++ await manager.migrateLegacyApprovalsOnce();+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })+ .state,+ ).toBe('completed');+ });++ it('首轮迁移治愈损坏/旧 schema 的 receipt(格式升级不落到用户重新确认)', async () => {+ // issue #1243 验收第 4 条的实现形态:schema/编码 bump 后的旧 receipt 判 invalid,+ // 但**首轮迁移**会把它当"已判损坏"从安装目录 backfill 重建 —— 一次内部格式变更+ // 不变成用户重新确认。v1 receipt 从未随任何构建发布,所以不需要专门的 v1 读取器;+ // 未来的 bump 走 §5 的「按旧编码核对 → 原地升级」,见规则文档。+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const stateDir = path.join(workDir, 'ghosts-install-state');+ await fs.promises.mkdir(stateDir, { recursive: true });+ // 一份 schemaVersion 过时的 receipt(读取器判 invalid)。+ await fs.promises.writeFile(+ path.join(stateDir, 'hello.json'),+ JSON.stringify({ schemaVersion: 1, id: 'hello', legacy: true }),);- expect(manager.list()[0].manifest).toMatchObject({- name: 'Base name',- resolvedLocale: 'en',+ expect(manager.list()[0].approval.state).toBe('invalid');++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ // 治愈后为有效批准;用户的停用决定(.disabled)照旧保留。+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },});});- it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {- const manifest = {- ...goodManifest(),- locales: { en: 'locales/en.json' },- };- const missing = await makeCindy('locale-missing.cindy', manifest);- await expectRejection(await manager.install(missing), 'file-invalid');+ it('修复 #1080 历史 mixed 状态:有效 receipt 不封死其余 legacy/旧 schema 插件', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest('approved')));+ const approvedReceiptPath = path.join(workDir, 'ghosts-install-state', 'approved.json');+ const approvedReceiptBefore = await fs.promises.readFile(approvedReceiptPath, 'utf8');- const invalid = await makeCindy('locale-invalid.cindy', manifest, {- 'locales/en.json': '{ nope',- });- await expectRejection(await manager.install(invalid), 'file-invalid');+ // Fixture 模拟曾短暂合入后回滚的 #1080:部分插件已有 v2 receipt,但当时没有+ // legacy migration ledger;同 owner 下其余旧安装仍无 receipt。删除 ledger 只是+ // 构造这份历史状态,不代表安装根攻击者能操作状态根。+ await fs.promises.rm(migrationLedgerPath());+ await writeLegacyInstall('legacy', goodManifest('legacy'));+ await writeLegacyInstall('old-schema', goodManifest('old-schema'), { disabled: true });+ await fs.promises.writeFile(+ path.join(workDir, 'ghosts-install-state', 'old-schema.json'),+ JSON.stringify({ schemaVersion: 1, id: 'old-schema', legacy: true }),+ );- const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {- 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),+ const outcome = await manager.migrateLegacyApprovalsOnce();++ expect(outcome.migrated).toEqual(['legacy', 'old-schema']);+ expect(await fs.promises.readFile(approvedReceiptPath, 'utf8')).toBe(approvedReceiptBefore);+ const byId = Object.fromEntries(manager.list().map((ghost) => [ghost.manifest.id, ghost]));+ expect(byId.approved.approval.state).toBe('approved');+ expect(byId.legacy).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(byId['old-schema']).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },});- await expectRejection(await manager.install(unknownTool), 'file-invalid');+ });- // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。+ it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const before = await fs.promises.readFile(+ path.join(workDir, 'ghosts-install-state', 'hello.json'),+ 'utf8',+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual([]);+ expect(await fs.promises.readFile(path.join(workDir, 'ghosts-install-state', 'hello.json'), 'utf8')).toBe(+ before,+ );+ });++ it('声明的 locale 文件损坏 → fail closed(装入天然不含坏 locale,读到即装入后损坏)', async () => {hostLocale = 'en';- const partial = await makeCindy('locale-partial.cindy', manifest, {- 'locales/en.json': JSON.stringify({ name: 'English partial' }),- });- expect(await manager.install(partial)).toMatchObject({- ghost: {- manifest: {- name: 'English partial',- resolvedLocale: 'en',- tools: [{ name: 'do_thing', description: '做点事' }],- },- },+ await writeLegacyInstall(+ 'hello',+ { ...goodManifest(), name: 'Base', locales: { en: 'locales/en.json' } },+ { files: { 'locales/en.json': '{ broken json' } },+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ // 装入流程逐个校验声明的 locale、不合格拒装,所以旧安装不会带坏 locale;迁移时+ // 读到坏 locale 只能是装入后损坏,属 §5 的"自相矛盾 → fail closed",不写坏 receipt。+ expect(outcome.failed).toEqual(['hello']);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });+});++describe('GhostManager · owner 受管根路径', () => {+ it('允许 userData 祖先通过 symlink/junction 重定位', async () => {+ const physicalUserData = path.join(workDir, 'physical-user-data');+ const linkedUserData = path.join(workDir, 'linked-user-data');+ await fs.promises.mkdir(path.join(physicalUserData, 'owners', 'owner-a'), { recursive: true });+ try {+ await fs.promises.symlink(+ physicalUserData,+ linkedUserData,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return;+ }++ const relocated = new GhostManager({+ getRootDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'cindy-brain'),+ getStateDir: () => path.join(linkedUserData, 'owners', 'owner-a', 'ghost-install-state'),});- const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {- 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),+ expect(relocated.list()).toEqual([]);+ });++ it('允许全新 owner 的多层受管根尚未创建', () => {+ const freshOwner = path.join(workDir, 'owners', 'fresh-owner');+ const fresh = new GhostManager({+ getRootDir: () => path.join(freshOwner, 'cindy-brain'),+ getStateDir: () => path.join(freshOwner, 'ghost-install-state'),});- await expectRejection(await manager.install(aliasedManifest), 'file-invalid');++ expect(fresh.list()).toEqual([]);});- it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {- const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });- const result = await manager.install(cindy);- expect('ghost' in result).toBe(true);- const { ghost } = result as { ghost: InstalledGhost };- expect(ghost.manifest.id).toBe('hello');- expect(ghost.dir).toBe(path.join(rootDir, 'hello'));- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);+ it('仍拒绝受管根本身是 symlink/junction', async () => {+ const outside = path.join(workDir, 'outside-root');+ const linkedRoot = path.join(workDir, 'linked-root');+ await fs.promises.mkdir(outside, { recursive: true });+ try {+ await fs.promises.symlink(outside, linkedRoot, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return;+ }- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0].map((c: InstalledGhost) => c.manifest.id)).toEqual(['hello']);+ expect(+ () =>+ new GhostManager({+ getRootDir: () => linkedRoot,+ getStateDir: () => path.join(workDir, 'state-root'),+ }),+ ).toThrow(/ghost content root is not a real directory/);});+});- it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {- const cindy = await makeCindy('at-resource.cindy', atResourceManifest());- const installed = await manager.install(cindy);+describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命名空间', () => {+ it('中途崩溃后按 pendingIds 续跑:已迁的跳过、剩余补迁、台账推进到 completed', async () => {+ // 复现真实崩溃现场:首轮迁移在 aaa 写完 receipt(receipt 首写自动落账被+ // in-progress 台账挡住)、bbb 还没动笔时进程死掉。+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await writeLegacyInstall('bbb', goodManifest('bbb'));+ await manager.migrateLegacyApprovalsOnce();+ // 手工把状态倒回"崩溃时刻":台账退回 in-progress、bbb 的 receipt 消失。+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['aaa', 'bbb'],+ }),+ );+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'bbb.json'));- const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');- const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;+ const outcome = await manager.migrateLegacyApprovalsOnce();+ // bbb 被续跑补迁;aaa 已有 receipt,计入 migrated(它就是迁移铸出的)。+ expect(outcome.migrated).toEqual(['bbb']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId).toEqual({ aaa: 'approved', bbb: 'approved' });+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ migratedIds: string[];+ };+ expect(ledger.state).toBe('completed');+ expect(ledger.migratedIds).toEqual(['aaa', 'bbb']);+ });- delete metadata.approvedAtResourceProvider;- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);- expect(manager.list()[0].manifest.tools).toEqual([- { name: 'do_thing', description: '做点事' },- ]);+ it('续跑只认动笔前钉死的清单:清单外的无 receipt 目录不被重铸', async () => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ // 迁移窗口期间新装再删 receipt 的插件(不在 pendingIds 里)骗不到续跑。+ await writeLegacyInstall('ccc', goodManifest('ccc'));+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['aaa'],+ }),+ );- metadata.approvedAtResourceProvider = { tool: 'other_tool' };- await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['aaa']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId.aaa).toBe('approved');+ expect(byId.ccc).toBe('legacy-unapproved');+ expect(+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })+ .state,+ ).toBe('completed');});- it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {- const cindy = await makeCindy('hello.cindy', goodManifest());- const result = await manager.install(cindy, { initiallyEnabled: false });- expect('ghost' in result).toBe(true);- expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);- // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);- // 重新启用即撕掉标记。- await manager.setEnabled('hello', true);- expect(manager.list()[0].enabled).toBe(true);+ it('receipt 首写的自动落账不覆盖 in-progress 台账(崩溃门不被焊死)', async () => {+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(+ migrationLedgerPath(),+ JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds: ['zzz'],+ }),+ );+ // 迁移窗口内经正常装入流程写 receipt(内部有"缺台账即补写 completed"的守卫)。+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ };+ expect(ledger.state).toBe('in-progress');+ });++ it('台账存在但读不出:门保守关死,不迁也不重写', async () => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });+ await fs.promises.writeFile(migrationLedgerPath(), '{ not valid json');++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{ not valid json');+ });++ it.each([+ ['empty pendingIds', []],+ ['non-string pending id', [null]],+ ['path-traversal pending id', ['../x']],+ ['mixed valid and invalid pending ids', ['aaa', '../x']],+ ])('非法 in-progress 台账(%s)保守关门且不被重写成 completed', async (_label, pendingIds) => {+ await writeLegacyInstall('aaa', goodManifest('aaa'));+ await fs.promises.mkdir(path.dirname(migrationLedgerPath()), { recursive: true });+ const raw = JSON.stringify({+ version: 1,+ migratedAt: '2026-08-01T00:00:00.000Z',+ migratedIds: [],+ state: 'in-progress',+ pendingIds,+ });+ await fs.promises.writeFile(migrationLedgerPath(), raw);++ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({+ migrated: [],+ skipped: [],+ failed: [],+ retryPending: [],+ });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe(raw);+ });++ it('启用失败的回滚按"镜像先前是否在盘上",不吞掉旧客户端的停用决定', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 旧客户端只写镜像:receipt.enabled=true + .disabled 在盘 → 读时合并 = 停用。+ const marker = path.join(rootDir, 'hello', '.disabled');+ await fs.promises.writeFile(marker, '');+ expect(manager.list()[0].enabled).toBe(false);++ // receipt 落盘的 rename 失败(状态根抖动):启用必须整体失败且镜像原样放回。+ const realRename = fs.promises.rename;+ const spy = vi+ .spyOn(fs.promises, 'rename')+ .mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');+ return realRename(from, to);+ });+ try {+ const result = await manager.setEnabled('hello', true);+ expect('rejection' in result && result.rejection.code).toBe('io');+ } finally {+ spy.mockRestore();+ }+ expect(fs.existsSync(marker)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('进程内隔离按状态根命名空间:A 账号的隔离不污染 B,切回 A 仍生效', async () => {+ let stateDir = path.join(workDir, 'owner-a-state');+ const owned = new GhostManager({+ getRootDir: () => rootDir,+ getStateDir: () => stateDir,+ getLocale: () => hostLocale,+ });+ await owned.install(await makeCindy('a.cindy', goodManifest()));+ // 撤销失败 → A 的进程内隔离。+ const realRm = fs.promises.rm;+ const spy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, opts) => {+ if (String(target).endsWith('hello.json')) throw new Error('EACCES');+ return realRm(target as never, opts as never);+ });+ try {+ await owned.removeInstallApproval('hello');+ } finally {+ spy.mockRestore();+ }+ expect(owned.list()[0].approval.state).toBe('invalid');++ // 切到 B 账号(状态根变了):同 id 不被 A 的隔离污染 —— B 没有 receipt,+ // 如实是 legacy-unapproved 而不是 invalid。+ stateDir = path.join(workDir, 'owner-b-state');+ expect(owned.list()[0].approval.state).toBe('legacy-unapproved');++ // 切回 A:隔离仍在(盘上那份陈旧 receipt 不得复活)。+ stateDir = path.join(workDir, 'owner-a-state');+ expect(owned.list()[0].approval.state).toBe('invalid');+ });++ it('安装根下的 junction 不算已装插件:迁移不迁它,list 不列它', async () => {+ await writeLegacyInstall('real', goodManifest('real'));+ const outside = path.join(workDir, 'outside-plugin');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(path.join(outside, 'ghost.json'), JSON.stringify(goodManifest('planted')));+ try {+ fs.symlinkSync(outside, path.join(rootDir, 'planted'), 'junction');+ } catch {+ return; // 环境建不了链接则跳过;判据逻辑平台无关。+ }++ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['real']);+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['real']);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'planted.json'))).toBe(false);+ });+});++describe('GhostManager · 从已装目录重新确认(本地包第三条恢复路径)', () => {+ it('批准丢失后不用原始 .cindy:inspect 出全量清单,确认后开 receipt、恢复可用', async () => {+ // 场景:迁移已跑过(ledger 在),之后 receipt 又被删 —— 一次性门不再迁移,+ // 本地包用户没有市场路线;第三条路必须能不找文件恢复。+ await writeLegacyInstall('hello', goodManifest());+ await manager.migrateLegacyApprovalsOnce();+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');++ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.manifest.id).toBe('hello');+ expect(inspected.manifestSha256).toMatch(/^[a-f0-9]{64}$/);++ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ // 启停镜像同步维护(回滚到旧客户端不错位)。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);+ });++ it('重新确认要求立即启用时,删除停用镜像失败必须拒绝且不提交批准', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const marker = path.join(rootDir, 'hello', '.disabled');+ const realRm = fs.promises.rm;+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(marker)) {+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });+ }+ return realRm(target, options);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ expect(fs.existsSync(marker)).toBe(true);+ } finally {+ rmSpy.mockRestore();+ }+ });++ it('重新确认要求立即启用时,receipt 提交失败必须恢复原停用镜像', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const marker = path.join(rootDir, 'hello', '.disabled');+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');+ return realRename(from, to);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ expect(fs.existsSync(marker)).toBe(true);+ } finally {+ renameSpy.mockRestore();+ }+ });++ it('重新确认不跟随确认后被换成 junction 的安装目录写删停用镜像', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const dir = path.join(rootDir, 'hello');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-outside-'));+ const outsideMarker = path.join(outside, '.disabled');+ await fs.promises.writeFile(outsideMarker, 'sentinel');+ const probe = path.join(workDir, 'reapprove-junction-probe');+ try {+ await fs.promises.symlink(outside, probe, process.platform === 'win32' ? 'junction' : 'dir');+ await fs.promises.rm(probe, { force: true });+ } catch {+ await fs.promises.rm(outside, { recursive: true, force: true });+ return;+ }+ const realInspect = manager.inspectInstalledReapproval.bind(manager);+ const inspectSpy = vi.spyOn(manager, 'inspectInstalledReapproval').mockImplementation(async (ghostId) => {+ const result = await realInspect(ghostId);+ await fs.promises.rm(dir, { recursive: true, force: true });+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ return result;+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(await fs.promises.readFile(outsideMarker, 'utf8')).toBe('sentinel');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ } finally {+ inspectSpy.mockRestore();+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });++ it('重新确认 receipt 失败回滚前目录被换成 junction 时不得写入外部目标', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const dir = path.join(rootDir, 'hello');+ const displaced = path.join(rootDir, 'hello-displaced');+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-rollback-'));+ let linkCreated = false;+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('hello.json')) {+ await realRename(dir, displaced);+ try {+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ linkCreated = true;+ } catch {+ await realRename(displaced, dir);+ }+ throw new Error('state root unwritable');+ }+ return realRename(from, to);+ });+ try {+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('io');+ if (linkCreated) expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);+ } finally {+ renameSpy.mockRestore();+ await fs.promises.rm(outside, { recursive: true, force: true });+ }+ });++ it('确认间隙 ghost.json 被换 → 拒(确认卡展示的与批准的必须是同一份字节)', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));++ // 攻击窗口:用户看的是权限集 A,confirm 落地前清单被换成声明更多权限的 B。+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({ ...goodManifest(), name: 'Changed after review' }),+ );+ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it.each(['skill', 'locale', 'icon', 'trust'] as const)(+ '确认间隙 %s 批准投影被换 → 拒绝重新确认',+ async (kind) => {+ const manifest = {+ ...goodManifest(),+ author: 'Original author',+ icon: 'assets/icon.png',+ locales: { en: 'locales/en.json' },+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ };+ await writeLegacyInstall('hello', manifest, {+ files: {+ 'assets/icon.png': 'ORIGINAL ICON',+ 'locales/en.json': JSON.stringify({ name: 'Original name' }),+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',+ },+ });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));++ if (kind === 'skill') {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',+ );+ } else if (kind === 'locale') {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'locales', 'en.json'),+ JSON.stringify({ name: 'Replaced name' }),+ );+ } else if (kind === 'icon') {+ await fs.promises.writeFile(path.join(rootDir, 'hello', 'assets', 'icon.png'), 'REPLACED ICON');+ } else {+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', '.cindy-trust.json'),+ JSON.stringify({+ level: 'verified-publisher',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ publisherName: 'Different publisher',+ }),+ );+ }++ const result = await manager.reapproveInstalled('hello', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('state-changed');+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ },+ );++ it('随包插件拒走人工重新确认(由启动对账自动补批准)', async () => {+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => id === 'hello',+ });+ await writeLegacyInstall('hello', goodManifest());+ const inspected = await guarded.inspectInstalledReapproval('hello');+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');+ });++ it('已是 approved 的插件拒重复确认(不给覆盖既有批准开口子)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const inspected = await manager.inspectInstalledReapproval('hello');+ expect('rejection' in inspected && inspected.rejection.code).toBe('state-changed');+ });++ it('信任镜像自称 cindy-official 一律封顶拒收(非随包目录不可能合法持有官方档)', async () => {+ await writeLegacyInstall('hello', goodManifest(), {+ trust: {+ level: 'cindy-official',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ },+ });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.trust.level).toBe('unverified');+ });+});++describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {+ it('P0-3:停用在 receipt 写失败时仍然生效,且跨实例(重启)持久', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect(manager.list()[0].enabled).toBe(true);++ // 状态根不可写(AV/权限/磁盘故障):receipt 的 rename 提交失败。+ const realRename = fs.promises.rename;+ const renameSpy = vi+ .spyOn(fs.promises, 'rename')+ .mockImplementation(async (from, to) => {+ if (String(to).includes('ghosts-install-state')) {+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ try {+ // 停用必须永远能成功:镜像已落盘,如实返回 ok,而不是 io + 回滚镜像(fail open)。+ expect(await manager.setEnabled('hello', false)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(false);+ } finally {+ renameSpy.mockRestore();+ }+ // "重启"(新实例,内存态清零):镜像在盘上,停用不复活。+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(restarted.list()[0].enabled).toBe(false);+ // 启用方向照旧要求 receipt 写成功(此时状态根已恢复可写)。+ expect(await manager.setEnabled('hello', true)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('P0-5:嵌套 skill dir(祖先包含子项)装入/快照/校验全通,不撞 COPYFILE_EXCL', async () => {+ const nested = {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },+ ],+ },+ };+ const files = {+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',+ };+ const result = await manager.install(await makeCindy('nested.cindy', nested, files));+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));+ const ghost = manager.list()[0];+ expect(ghost.approval.state).toBe('approved');+ // 两个 item 的字节指纹都能对上(嵌套项的根就在祖先拷出的快照树里)。+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);+ });++ it('P0-5:嵌套 skill dir 的旧安装迁移同样成功(存量兼容红线)', async () => {+ await writeLegacyInstall(+ 'skilled',+ {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },+ ],+ },+ },+ {+ files: {+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',+ },+ },+ );+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['skilled']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ });++ it('P0-2:安装根为空/未诞生时不落台账,legacy 恢复流程随后搬入仍可迁移', async () => {+ // 首轮:根目录还不存在(owner 命名空间刚建立,旧目录尚未被恢复流程搬入)。+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({+ migrated: [],+ skipped: [],+ failed: [],+ retryPending: [],+ });+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // 恢复流程把旧布局目录搬进来 → 门还开着,照常迁移。+ await writeLegacyInstall('hello', goodManifest());+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ });++ it('P0-2:首个 receipt 写入即自动落台账 —— "装插件→删 receipt"骗不到迁移', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 新模型首次活动(装入写 receipt)时台账已经落了,不等下一轮 reconcile。+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ // 攻击:改写安装目录 manifest 扩权,再删掉 receipt,指望迁移按新 manifest 重铸批准。+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({+ ...goodManifest(),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 's', name: 's', description: 's' }] },+ }),+ );+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ });++ it('P0-2:首次批准先提交 migration ledger,落账失败时不留下有效 receipt', async () => {+ const renameTargets: string[] = [];+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ const target = String(to);+ renameTargets.push(target);+ if (target.endsWith('.legacy-migration.json')) {+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ try {+ const result = await manager.install(await makeCindy('a.cindy', goodManifest()));+ expect('rejection' in result && result.rejection.code).toBe('io');+ } finally {+ renameSpy.mockRestore();+ }++ expect(renameTargets.some((target) => target.endsWith('.legacy-migration.json'))).toBe(true);+ expect(renameTargets.some((target) => target.endsWith(`${path.sep}hello.json`))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ // Ledger commit failed before the receipt became visible, so the install+ // transaction rolls back the final directory as well; no ghost is listed.+ expect(manager.list()).toEqual([]);+ });++ it('首次批准与目录回滚同时失败时保留 install journal,不让迁移收编未提交字节', async () => {+ const finalDir = path.join(rootDir, 'hello');+ const pendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');+ const realRename = fs.promises.rename;+ const realRm = fs.promises.rm;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith('.legacy-migration.json')) {+ throw Object.assign(new Error('EACCES: migration ledger locked'), { code: 'EACCES' });+ }+ return realRename(from as never, to as never);+ });+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EBUSY: installed directory locked'), { code: 'EBUSY' });+ }+ return realRm(target, options);+ });+ try {+ await expect(manager.install(await makeCindy('a.cindy', goodManifest()))).resolves.toMatchObject(+ { rejection: { code: 'io' } },+ );+ } finally {+ renameSpy.mockRestore();+ rmSpy.mockRestore();+ }++ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(pendingPath)).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);++ const migration = await manager.migrateLegacyApprovalsOnce();+ expect(migration.migrated).toEqual([]);+ expect(migration.skipped).toContain('hello');+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()).toEqual([]);+ expect(fs.existsSync(finalDir)).toBe(false);+ expect(fs.existsSync(pendingPath)).toBe(false);+ });++ it('P0-2:安装根读失败(EACCES 类)本轮放弃且不落台账,不把迁移永久封死', async () => {+ await writeLegacyInstall('hello', goodManifest());+ const realReaddir = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((dir: never, opts: never) => {+ if (String(dir) === rootDir) {+ throw Object.assign(new Error('EACCES: install root locked'), { code: 'EACCES' });+ }+ return realReaddir(dir, opts);+ }) as never);+ try {+ await expect(manager.migrateLegacyApprovalsOnce()).rejects.toThrow(/EACCES/);+ } finally {+ spy.mockRestore();+ }+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);+ // 环境恢复后下一轮照常迁移。+ const outcome = await manager.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual(['hello']);+ });++ it('P0-2:恢复旁路只补给定 id,台账门对其余目录照常生效', async () => {+ // 台账已落(首轮迁移空跑一个插件)。+ await writeLegacyInstall('first', goodManifest('first'));+ await manager.migrateLegacyApprovalsOnce();+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);+ // 恢复流程搬入两个目录,但只把 recovered 声明为其中一个。+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ await writeLegacyInstall('planted', goodManifest('planted'));- const out = await manager.backfillRecoveredLegacyGhosts(['recovered']);++ const out = await manager.backfillRecoveredLegacyGhosts(++ ['recovered'],++ await recoveredProjectionOptions('recovered'),++ );+ expect(out.migrated).toEqual(['recovered']);+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));+ expect(byId.recovered).toBe('approved');+ expect(byId.planted).toBe('legacy-unapproved');+ });+++ it.each(['manifest', 'disabled', 'trust', 'locale', 'icon', 'skill'] as const)(++ '恢复 backfill 在 %s 批准投影漂移时保持 fail closed',++ async (kind) => {++ const manifest = {++ ...goodManifest('recovered'),++ icon: 'assets/icon.png',++ locales: { en: 'locales/en.json' },++ slots: ['tool', 'skill'],++ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },++ };++ await writeLegacyInstall('recovered', manifest, {++ files: {++ 'assets/icon.png': 'ORIGINAL ICON',++ 'locales/en.json': JSON.stringify({ name: 'Original name' }),++ 'skills/demo/SKILL.md':++ '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',++ },++ });++ const expected = await recoveredProjectionOptions('recovered');++ const dir = path.join(rootDir, 'recovered');++ if (kind === 'manifest') {++ await fs.promises.writeFile(++ path.join(dir, 'ghost.json'),++ JSON.stringify({++ ...manifest,++ tools: [++ { name: 'do_thing', description: '做点事' },++ { name: 'new_thing', description: 'New privileged tool' },++ ],++ }),++ );++ } else if (kind === 'disabled') {++ await fs.promises.writeFile(path.join(dir, '.disabled'), '');++ } else if (kind === 'trust') {++ await fs.promises.writeFile(++ path.join(dir, '.cindy-trust.json'),++ JSON.stringify({++ level: 'verified-publisher',++ publisherSigned: true,++ publisherVerified: true,++ reviewed: false,++ }),++ );++ } else if (kind === 'locale') {++ await fs.promises.writeFile(++ path.join(dir, 'locales', 'en.json'),++ JSON.stringify({ name: 'Replaced name' }),++ );++ } else if (kind === 'icon') {++ await fs.promises.writeFile(path.join(dir, 'assets', 'icon.png'), 'REPLACED ICON');++ } else {++ await fs.promises.writeFile(++ path.join(dir, 'skills', 'demo', 'SKILL.md'),++ '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',++ );++ }++++ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);++ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });++ expect(++ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),++ ).toBe(false);++ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');++ },++ );++++ it('fails closed when the legacy icon cannot be read during approval freezing', async () => {++ await writeLegacyInstall(++ 'recovered',++ {++ ...goodManifest('recovered'),++ icon: 'assets/icon.png',++ },++ {++ files: {++ 'assets/icon.png': 'ORIGINAL ICON',++ },++ },++ );++ const realOpenSync = fs.openSync;++ const spy = vi++ .spyOn(fs, 'openSync')++ .mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {++ if (++ typeof p === 'string' &&++ p.endsWith(path.join('recovered', 'assets', 'icon.png'))++ ) {++ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;++ err.code = 'EACCES';++ throw err;++ }++ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);++ }) as typeof fs.openSync);++++ try {++ await expect(++ readLegacyGhostApprovalProjection(path.join(rootDir, 'recovered'), 'recovered'),++ ).rejects.toThrow(/EACCES: permission denied/i);++ } finally {++ spy.mockRestore();++ }++ });++++ it('恢复 backfill 不跟随被换成 junction 的插件根目录', async () => {++ await writeLegacyInstall('recovered', goodManifest('recovered'));++ const expected = await recoveredProjectionOptions('recovered');++ const installedDir = path.join(rootDir, 'recovered');++ const externalDir = path.join(workDir, 'external-recovered');++ await fs.promises.rename(installedDir, externalDir);++ await fs.promises.symlink(externalDir, installedDir, 'junction');++++ const outcome = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);++ expect(outcome).toEqual({ migrated: [], failed: ['recovered'] });++ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json'))).toBe(false);++ });+++ 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({++ await expect(++ manager.backfillRecoveredLegacyGhosts(++ ['hello'],++ { expectedApprovalProjectionSha256ById: {} },++ ),++ ).resolves.toEqual({+ migrated: [],+ failed: [],+ });+ expect(JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8'))).toMatchObject({+ state: 'completed',+ });+ });+++ it('keeps a target-only legacy recovery without a frozen projection fail closed', async () => {++ await writeLegacyInstall('recovered', goodManifest('recovered'));++++ await expect(++ manager.backfillRecoveredLegacyGhosts(++ ['recovered'],++ { expectedApprovalProjectionSha256ById: {} },++ ),++ ).resolves.toEqual({++ migrated: [],++ failed: ['recovered'],++ });++ expect(++ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'recovered.json')),++ ).toBe(false);++ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');++ });+++ it('恢复旁路遇到 unreadable receipt 同样只排队重试,不重铸批准', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const receiptBefore = await fs.promises.readFile(receiptPath, 'utf8');+ await fs.promises.rm(migrationLedgerPath());- const realLstatSync = fs.lstatSync;- const lstatSpy = vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {++ const realOpenSync = fs.openSync;++ const openSpy = vi.spyOn(fs, 'openSync');++ openSpy.mockImplementation((target, ...args) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {- lstatSpy.mockRestore();++ openSpy.mockRestore();+ throw Object.assign(new Error('EIO: receipt temporarily unreadable'), { code: 'EIO' });+ }- return realLstatSync(target, options as never);++ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);+ });+- expect(await manager.backfillRecoveredLegacyGhosts(['hello'])).toEqual({++ expect(++ await manager.backfillRecoveredLegacyGhosts(++ ['hello'],++ await recoveredProjectionOptions('hello'),++ ),++ ).toEqual({+ migrated: [],+ failed: [],+ });+ expect(await fs.promises.readFile(receiptPath, 'utf8')).toBe(receiptBefore);+ expect(+ JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')),+ ).toMatchObject({ state: 'in-progress', pendingIds: ['hello'] });+ });++ it('persists transient recovered-legacy backfill failures in the migration work queue', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}recovered.json`)) {+ renameSpy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });+- const first = await manager.backfillRecoveredLegacyGhosts(['recovered']);++ const expected = await recoveredProjectionOptions('recovered');++ const first = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(first).toEqual({ migrated: [], failed: [] });+ const pendingLedger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ pendingIds?: string[];+ };+ expect(pendingLedger.state).toBe('in-progress');+ expect(pendingLedger.pendingIds).toEqual(['recovered']);+- const second = await manager.backfillRecoveredLegacyGhosts(['recovered']);++ const second = await manager.backfillRecoveredLegacyGhosts(['recovered'], expected);+ expect(second.migrated).toEqual(['recovered']);+ const completedLedger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string; pendingIds?: string[] };+ expect(completedLedger.state).toBe('completed');+ expect(completedLedger.pendingIds).toBeUndefined();+ });++ it('persists recovered ids before the first receipt write starts', async () => {+ await writeLegacyInstall('recovered', goodManifest('recovered'));+ const realRename = fs.promises.rename;+ let queueSeenBeforeReceipt = false;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}recovered.json`)) {+ const ledger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string; pendingIds?: string[] };+ queueSeenBeforeReceipt =+ ledger.state === 'in-progress' && ledger.pendingIds?.includes('recovered') === true;+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });++ try {- await manager.backfillRecoveredLegacyGhosts(['recovered']);++ await manager.backfillRecoveredLegacyGhosts(++ ['recovered'],++ await recoveredProjectionOptions('recovered'),++ );+ } finally {+ renameSpy.mockRestore();+ }+ 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(++ await expect(++ manager.backfillRecoveredLegacyGhosts(++ ['recovered'],++ await recoveredProjectionOptions('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')),+ );+ await writeLegacyInstall('clasher', chipManifestWithCommand('clasher', 'Draw'));+ const inspected = await manager.inspectInstalledReapproval('clasher');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ const result = await manager.reapproveInstalled('clasher', {+ enable: true,+ expectedManifestSha256: inspected.manifestSha256,+ expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,+ expectedInstalledApproval: 'legacy-unapproved',+ });+ expect('rejection' in result && result.rejection.code).toBe('command-conflict');+ });++ it('P1-6:声明 tokenBroker 的目录拒走已装目录重新确认', async () => {+ await writeLegacyInstall('brokered', {+ ...goodManifest('brokered'),+ network: {+ hosts: ['api.example.com'],+ secrets: [+ {+ key: 'token',+ source: 'oauth',+ oauth: { tokenBroker: 'github' },+ },+ ],+ },+ });+ const inspected = await manager.inspectInstalledReapproval('brokered');+ expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');+ });++ it('P1-7:重新确认的启停默认值取镜像读数,不重置用户停用偏好', async () => {+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });+ const inspected = await manager.inspectInstalledReapproval('hello');+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));+ expect(inspected.previouslyEnabled).toBe(false);+ });++ it('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const realRename = fs.promises.rename;+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ // staging→final 与 backup→final 都失败(Windows 文件锁/AV 的典型形态)。+ if (path.resolve(String(to)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EPERM: dir locked'), { code: 'EPERM' });+ }+ return realRename(from as never, to as never);+ });+ try {+ const bumped = await makeCindy('b.cindy', { ...goodManifest(), version: '1.0.1' });+ const result = await updateGhost(bumped);+ expect('rejection' in result).toBe(true);+ if (!('rejection' in result)) return;+ expect(result.rejection.code).toBe('io');+ expect(result.rejection.code === 'io' && result.rejection.rollbackFailed).toBe(true);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(true);+ } finally {+ spy.mockRestore();+ }+ });+});++describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () => {+ const pendingMarkerPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `.pending-${id}.json`);+ const receiptPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `${id}.json`);+ /** 在同一组根上新建 manager —— 构造期跑一次崩溃恢复扫描。 */+ const freshManager = () =>+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });++ it('崩溃的装入(有 finalDir、无 receipt、有 install 标记)被恢复删除,不被迁移收编', async () => {+ // install 在 rename(staging→final) 之后、写 receipt 之前崩溃:finalDir 完整、无+ // receipt、无 ledger。若不处理,迁移会把它(崩溃窗口内可能被改过 manifest)当 legacy+ // 批准掉。事务标记让恢复识别它是"未完成安装"并删除。+ await writeLegacyInstall('hello', goodManifest());+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256: 'a'.repeat(64) }),+ );++ const recovered = freshManager(); // 构造期恢复:删掉未完成安装+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ const outcome = await recovered.migrateLegacyApprovalsOnce();+ expect(outcome.migrated).toEqual([]); // 目录已被删,迁移无对象+ });++ it('keeps a committed builtin restore successful and retries tombstone clearing from its journal', async () => {+ trustedBundledIds.add('hello');+ const clearBuiltinTombstone = vi+ .fn<(id: string) => void>()+ .mockImplementationOnce(() => {+ throw new Error('state root temporarily unavailable');+ })+ .mockImplementation(() => undefined);+ const restoringManager = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ clearBuiltinTombstone,+ });++ const installed = await restoringManager.install(+ await makeCindy('builtin-restore.cindy', goodManifest()),+ );++ expect('ghost' in installed).toBe(true);+ expect(restoringManager.list()[0]).toMatchObject({ approval: { state: 'approved' } });+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(JSON.parse(await fs.promises.readFile(pendingMarkerPath(), 'utf8'))).toMatchObject({+ kind: 'install',+ clearBuiltinTombstone: true,+ });++ const recoveredAfterClearFailure = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ clearBuiltinTombstone,+ });++ expect(clearBuiltinTombstone).toHaveBeenCalledTimes(2);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ expect(recoveredAfterClearFailure.list()[0]).toMatchObject({+ approval: { state: 'approved' },+ });+ });++ it('install 恢复必须用 packageSha256 证明旧 receipt 属于这次安装', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ await fs.promises.rm(finalDir, { recursive: true, force: true });+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(finalDir, 'ghost.json'),+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),+ );+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'install',+ packageSha256: 'f'.repeat(64),+ }),+ );++ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });+ expect(fs.existsSync(finalDir)).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('非法 pending marker 会阻断 orphan backup 启发式,不删除待人工恢复的 backup', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-abcdef12';+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: '..\\outside',+ }),+ );++ const recovered = freshManager();+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('invalid pending marker filename blocks orphan-backup heuristics', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ const invalidMarker = path.join(path.dirname(pendingMarkerPath()), '.pending-BAD!.json');+ await fs.promises.writeFile(invalidMarker, '{}');++ const recovered = freshManager();+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(invalidMarker)).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('pending marker JSON 为 null 时按 invalid 保留现场,不让构造期恢复崩溃', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(finalDir, { recursive: true });+ await fs.promises.writeFile(path.join(finalDir, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new');+ await fs.promises.writeFile(pendingMarkerPath(), 'null');++ const recovered = freshManager();+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('状态根 journal 扫描 EACCES 时跳过全部恢复启发式,任何现场都不动', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateRoot = path.dirname(pendingMarkerPath());+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.mkdir(stagingDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realReaddirSync = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {+ if (path.resolve(String(target)) === path.resolve(stateRoot)) {+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });+ }+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);+ }) as typeof fs.readdirSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ // 未提交 update 已先移除 final;backup 不可读时保留整笔 journal,+ // 因而此刻 final 仍缺失,等待下次可读时再由 recovery 收敛。+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(stagingDir)).toBe(true);+ });++ it('journal root unreadable blocks the whole owner even when installed ids cannot be enumerated yet', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateRoot = path.dirname(pendingMarkerPath());+ const realReaddirSync = fs.readdirSync;+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((target: fs.PathLike, options?: unknown) => {+ const resolved = path.resolve(String(target));+ if (resolved === path.resolve(stateRoot) || resolved === path.resolve(rootDir)) {+ throw Object.assign(new Error('EACCES: managed root locked'), { code: 'EACCES' });+ }+ return (realReaddirSync as (...args: unknown[]) => unknown)(target, options);+ }) as typeof fs.readdirSync);++ let recovered: GhostManager;+ try {+ recovered = freshManager();+ } finally {+ spy.mockRestore();+ }++ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('pending marker 读取 EACCES 时保留 marker/final/backup,不降级到 orphan cleanup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realReadFileSync = fs.readFileSync;+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(pendingMarkerPath())) {+ throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });+ }+ return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.readFileSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ });++ it('已提交 install 的 receipt 瞬时不可读时保留 final/receipt/journal 等待重试', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ }).packageSha256;+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'install', packageSha256 }),+ );- const realReadFileSync = fs.readFileSync;- const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {++ const realOpenSync = fs.openSync;++ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }- return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);- }) as typeof fs.readFileSync);++ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);++ }) as typeof fs.openSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('已提交 update 的 receipt lstat EACCES 时保留 final/backup/receipt/journal', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const packageSha256 = (JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ }).packageSha256;+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256,+ backupDirName: path.basename(backupDir),+ }),+ );- const realLstatSync = fs.lstatSync;- const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {++ const realOpenSync = fs.openSync;++ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });+ }- return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);- }) as typeof fs.lstatSync);++ return (realOpenSync as (...args: unknown[]) => number)(target, ...rest);++ }) as typeof fs.openSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('update backup lstat EACCES 时保留整笔 journal,不清 marker 继续猜恢复', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef12');+ await fs.promises.mkdir(backupDir, { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: path.basename(backupDir),+ }),+ );+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(backupDir)) {+ throw Object.assign(new Error('EACCES: backup locked'), { code: 'EACCES' });+ }+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.lstatSync);+ try {+ const recovered = freshManager();+ expect(recovered.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(backupDir)).toBe(true);+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('动态 owner 根切换时,首次读取会先恢复新 owner 的 pending mutation', async () => {+ const rootA = rootDir;+ const rootB = path.join(workDir, 'ghosts-b');+ const stateA = path.join(workDir, 'state-a');+ const stateB = path.join(workDir, 'state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ const backupName = '.cindy-updating-hello-abcdef12';+ const finalDir = path.join(rootB, 'hello');+ await fs.promises.mkdir(path.join(rootB, backupName), { recursive: true });+ await fs.promises.writeFile(path.join(rootB, backupName, 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(rootB, backupName, 'main.js'), 'old');+ await fs.promises.mkdir(stateB, { recursive: true });+ await fs.promises.writeFile(+ path.join(stateB, '.pending-hello.json'),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: backupName,+ }),+ );+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getLocale: () => hostLocale,+ });+ activeRoot = rootB;+ activeState = stateB;+ expect(owned.list().map((ghost) => ghost.manifest.id)).toEqual(['hello']);+ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(path.join(rootB, backupName))).toBe(false);+ });++ it('排队中的 mutation 在 owner 代际变化后拒绝执行', async () => {+ const rootA = rootDir;+ const rootB = path.join(workDir, 'ghosts-b');+ const stateA = path.join(workDir, 'state-a');+ const stateB = path.join(workDir, 'state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ let ownerGeneration = 0;+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getOwnerContextKey: () => `owner:${ownerGeneration}`,+ getLocale: () => hostLocale,+ });++ let markStarted!: () => void;+ let releaseFirst!: () => void;+ const started = new Promise<void>((resolve) => {+ markStarted = resolve;+ });+ const first = owned.runExclusiveMutation(async () => {+ markStarted();+ await new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ });+ await started;++ const second = owned.runExclusiveMutation(async () => {+ await fs.promises.mkdir(activeRoot, { recursive: true });+ await fs.promises.writeFile(path.join(activeRoot, 'queued-write'), 'must not run');+ });+ const rejected = expect(second).rejects.toThrow(/owner context changed/);+ activeRoot = rootB;+ activeState = stateB;+ ownerGeneration += 1;+ releaseFirst();++ await first;+ await rejected;+ expect(fs.existsSync(path.join(rootA, 'queued-write'))).toBe(false);+ expect(fs.existsSync(path.join(rootB, 'queued-write'))).toBe(false);+ });++ it('执行中的独占 mutation 钉住 owner 内容根与状态根,不把后半段写进新 owner', async () => {+ const rootA = path.join(workDir, 'owned-a');+ const rootB = path.join(workDir, 'owned-b');+ const stateA = path.join(workDir, 'owned-state-a');+ const stateB = path.join(workDir, 'owned-state-b');+ let activeRoot = rootA;+ let activeState = stateA;+ let ownerGeneration = 0;+ const owned = new GhostManager({+ getRootDir: () => activeRoot,+ getStateDir: () => activeState,+ getOwnerContextKey: () => `owner:${ownerGeneration}`,+ getLocale: () => hostLocale,+ });+ await owned.install(await makeCindy('owned.cindy', goodManifest()));+ await fs.promises.mkdir(path.join(rootB, 'hello'), { recursive: true });+ await fs.promises.writeFile(path.join(rootB, 'hello', 'ghost.json'), JSON.stringify(goodManifest()));+ await fs.promises.writeFile(path.join(rootB, 'hello', 'main.js'), 'owner-b');++ await owned.runExclusiveMutation(async (mutation) => {+ activeRoot = rootB;+ activeState = stateB;+ ownerGeneration += 1;+ expect(await mutation.uninstall('hello', { notify: false })).toEqual({ ok: true });+ });++ expect(fs.existsSync(path.join(rootA, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(stateA, 'hello.json'))).toBe(false);+ expect(fs.existsSync(path.join(rootB, 'hello', 'main.js'))).toBe(true);+ expect(owned.list().find((ghost) => ghost.manifest.id === 'hello')?.approval.state).toBe(+ 'legacy-unapproved',+ );+ });++ it('未提交的更新(新字节+旧 receipt+update 标记)回滚到 backup,不固化成按旧批准跑新代码', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const receiptBefore = await fs.promises.readFile(receiptPath(), 'utf8');+ const finalDir = path.join(rootDir, 'hello');+ const backupName = '.cindy-updating-hello-abcdef12';++ // 模拟 staging→final 之后、写 receipt 之前崩溃:旧字节挪到 backup,新字节在 final,+ // receipt 仍是旧的。标记的 packageSha256 与旧 receipt 不同 = 未提交。+ await fs.promises.rename(finalDir, path.join(rootDir, backupName));+ await fs.promises.mkdir(finalDir);+ await fs.promises.writeFile(+ path.join(finalDir, 'ghost.json'),+ JSON.stringify({ ...goodManifest(), version: '2.0.0' }),+ );+ await fs.promises.writeFile(path.join(finalDir, 'main.js'), 'new-bytes');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: backupName,+ }),+ );++ freshManager(); // 构造期恢复:未提交 → 回滚到 backup+ const restored = JSON.parse(await fs.promises.readFile(path.join(finalDir, 'ghost.json'), 'utf8'));+ expect(restored.version).toBe('1.0.0'); // 旧字节搬回+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ // receipt 一字未动,与回滚后的旧字节自洽(不是"新字节 + 旧 receipt"的错位)。+ expect(await fs.promises.readFile(receiptPath(), 'utf8')).toBe(receiptBefore);+ });++ it('已提交的更新(标记 packageSha256 == receipt)保留新字节,只回收陈旧 backup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const committedReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256: string;+ 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');+ await fs.promises.mkdir(path.dirname(pendingMarkerPath()), { recursive: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: committedReceipt.packageSha256,+ receiptRevision: committedReceipt.revision,+ backupDirName: backupName,+ phase: 'published',+ }),+ );++ freshManager();+ expect(fs.existsSync(path.join(rootDir, backupName))).toBe(false); // 陈旧 backup 回收+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true); // 新版保留+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ 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');+ // 让内容目录的 rm 失败(模拟句柄占用),但放行 receipt/快照的 rm。+ const realRm = fs.promises.rm;+ const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation((async (p: fs.PathLike, ...rest: unknown[]) => {+ if (String(p) === path.join(rootDir, 'hello')) {+ rmSpy.mockRestore();+ const err = new Error('EBUSY: resource busy') as NodeJS.ErrnoException;+ err.code = 'EBUSY';+ throw err;+ }+ return (realRm as (...a: unknown[]) => Promise<void>)(p, ...rest);+ }) as typeof fs.promises.rm);++ const res = await manager.uninstall('hello');+ await expectRejection(res, 'io');+ // 关键:撤批准在删目录之前 —— receipt 已没了,目录还在但 fail closed(list 报+ // legacy-unapproved),不会被这份 receipt 授权。孤立标记留给启动恢复收尾。+ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');+ expect(fs.existsSync(pendingMarkerPath())).toBe(true);+ });++ it('卸载崩在撤批准之后、删目录之前:恢复据 uninstall 标记删净残留目录', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 模拟崩溃现场:receipt 已撤(revoke 先行),目录还在,uninstall 标记在。+ await fs.promises.rm(receiptPath(), { force: true });+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),+ );+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);++ freshManager(); // 构造期恢复+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('卸载崩在撤批准之前:恢复据 uninstall 标记把 receipt 与目录都删净', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 崩在写标记之后、撤批准之前:receipt 与目录都还在。+ await fs.promises.writeFile(+ pendingMarkerPath(),+ JSON.stringify({ version: 1, id: 'hello', kind: 'uninstall' }),+ );+ expect(fs.existsSync(receiptPath())).toBe(true);++ freshManager();+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(fs.existsSync(pendingMarkerPath())).toBe(false);+ });++ it('setEnabled 不跟随非真目录:<id> 是普通文件时按未装入拒,不越安装根写标记', async () => {+ await fs.promises.mkdir(rootDir, { recursive: true });+ await fs.promises.writeFile(path.join(rootDir, 'foo'), 'not a dir');+ const result = await manager.setEnabled('foo', false);+ await expectRejection(result, 'not-installed');+ });++ it('setEnabled 不跟随 junction:<id> 是指向外部的链接时拒,不在外部目标写/删 .disabled', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const dir = path.join(rootDir, 'hello');+ const outside = path.join(workDir, 'outside-target');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.rm(dir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 无 symlink 权限(Windows 未开发者模式):生产守卫仍由 classify 钉死。+ }+ const result = await manager.setEnabled('hello', false);+ await expectRejection(result, 'not-installed');+ // 关键:没有往 junction 目标(安装根之外)写 .disabled。+ expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);+ });+});++describe('GhostManager · update pre-rename recovery', () => {+ it('marker 落盘但尚未 rename 时保留旧 final 与 receipt', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const stagingDir = path.join(rootDir, '.cindy-installing-hello-deadbeef');+ await fs.promises.mkdir(stagingDir, { recursive: true });+ const stateReceiptPath = path.join(workDir, 'ghosts-install-state', 'hello.json');+ const statePendingPath = path.join(workDir, 'ghosts-install-state', '.pending-hello.json');+ const receipt = JSON.parse(await fs.promises.readFile(stateReceiptPath, 'utf8')) as {+ packageSha256?: string;+ };+ await fs.promises.writeFile(+ statePendingPath,+ JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'update',+ packageSha256: 'f'.repeat(64),+ backupDirName: '.cindy-updating-hello-deadbeef',+ phase: 'prepared',+ oldPackageSha256: receipt.packageSha256,+ }),+ );++ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale, onChanged });++ expect(fs.existsSync(finalDir)).toBe(true);+ expect(fs.existsSync(stateReceiptPath)).toBe(true);+ expect(fs.existsSync(statePendingPath)).toBe(false);+ expect(fs.existsSync(stagingDir)).toBe(false);+ });+});++describe('GhostManager · install', () => {+ it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {+ const manifest = {+ ...goodManifest(),+ name: 'Base name',+ description: 'Base description',+ locales: {+ en: 'locales/en.json',+ 'zh-CN': 'locales/zh-CN.json',+ },+ };+ const locale = (name: string, description: string, toolDescription: string) => JSON.stringify({+ name,+ description,+ tools: { do_thing: { description: toolDescription } },+ });+ const cindy = await makeCindy('localized.cindy', manifest, {+ 'locales/en.json': locale('English name', 'English description', 'English tool'),+ 'locales/zh-CN.json': locale('中文名称', '中文说明', '中文工具'),+ });+ const result = await manager.install(cindy);+ expect(result).toMatchObject({+ ghost: {+ manifest: {+ name: '中文名称',+ description: '中文说明',+ resolvedLocale: 'zh-CN',+ tools: [{ name: 'do_thing', description: '中文工具' }],+ },+ },+ });++ hostLocale = 'ja';+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'English name',+ description: 'English description',+ resolvedLocale: 'ja',+ tools: [{ name: 'do_thing', description: 'English tool' }],+ });+ hostLocale = 'fr-FR';+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'English name',+ resolvedLocale: 'en',+ });+ });++ it('installed locale symlinks cannot replace the Host-approved locale snapshot', async () => {+ hostLocale = 'en';+ const manifest = {+ ...goodManifest(),+ name: 'Base name',+ locales: { en: 'locales/en.json' },+ };+ const locale = (name: string) => JSON.stringify({+ name,+ tools: { do_thing: { description: 'Localized tool' } },+ });+ const cindy = await makeCindy('localized-symlink.cindy', manifest, {+ 'locales/en.json': locale('Packaged name'),+ });+ await manager.install(cindy);+ const localePath = path.join(rootDir, 'hello', 'locales', 'en.json');+ const outsidePath = path.join(workDir, 'outside-locale.json');+ await fs.promises.writeFile(outsidePath, locale('Outside name'));+ await fs.promises.rm(localePath);+ try {+ await fs.promises.symlink(outsidePath, localePath, 'file');+ } catch {+ return; // Windows 无 symlink 权限时跳过;生产守卫仍由 lstatSync 钉死。+ }++ expect(manager.list()[0].manifest).toMatchObject({+ name: 'Packaged name',+ resolvedLocale: 'en',+ tools: [{ name: 'do_thing', description: 'Localized tool' }],+ });++ const localesDir = path.dirname(localePath);+ const outsideLocalesDir = path.join(workDir, 'outside-locales');+ await fs.promises.rm(localesDir, { recursive: true, force: true });+ await fs.promises.mkdir(outsideLocalesDir);+ await fs.promises.writeFile(path.join(outsideLocalesDir, 'en.json'), locale('Outside parent name'));+ await fs.promises.symlink(+ outsideLocalesDir,+ localesDir,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ expect(manager.list()[0].manifest).toMatchObject({+ name: 'Packaged name',+ resolvedLocale: 'en',+ });+ });++ it('locale 文件缺失、非法 JSON 或翻译错位时 inspect/install 都拒绝;部分翻译回退后可装', async () => {+ const manifest = {+ ...goodManifest(),+ locales: { en: 'locales/en.json' },+ };+ const missing = await makeCindy('locale-missing.cindy', manifest);+ await expectRejection(await manager.install(missing), 'file-invalid');++ const invalid = await makeCindy('locale-invalid.cindy', manifest, {+ 'locales/en.json': '{ nope',+ });+ await expectRejection(await manager.install(invalid), 'file-invalid');++ const unknownTool = await makeCindy('locale-unknown-tool.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'English', tools: { nope: { description: 'x' } } }),+ });+ await expectRejection(await manager.install(unknownTool), 'file-invalid');++ // 部分翻译(只给 name,工具不翻)不再拒装:缺失条目回退原 manifest 文案。+ hostLocale = 'en';+ const partial = await makeCindy('locale-partial.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'English partial' }),+ });+ expect(await manager.install(partial)).toMatchObject({+ ghost: {+ manifest: {+ name: 'English partial',+ resolvedLocale: 'en',+ tools: [{ name: 'do_thing', description: '做点事' }],+ },+ },+ });++ const aliasedManifest = await makeCindy('locale-manifest-alias.cindy', goodManifest(), {+ 'GHOST.JSON': JSON.stringify({ name: 'Alias locale' }),+ });+ await expectRejection(await manager.install(aliasedManifest), 'file-invalid');+ });++ it('装入合法 .cindy:目录落地、ghost.json 在位、list 可见、onChanged 收到全量清单', async () => {+ const cindy = await makeCindy('hello.cindy', goodManifest(), { 'assets/readme.txt': 'hi' });+ const result = await manager.install(cindy);+ expect('ghost' in result).toBe(true);+ const { ghost } = result as { ghost: InstalledGhost };+ expect(ghost.manifest.id).toBe('hello');+ expect(ghost.dir).toBe(path.join(rootDir, 'hello'));+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'readme.txt'))).toBe(true);++ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ expect(onChanged).toHaveBeenCalledTimes(1);+ 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('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {+ const cindy = await makeCindy('at-resource.cindy', atResourceManifest());+ const installed = await manager.install(cindy);++ const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');+ const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;++ delete metadata.approvedAtResourceProvider;+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ expect(manager.list()[0].manifest.tools).toEqual([+ { name: 'do_thing', description: '做点事' },+ ]);++ metadata.approvedAtResourceProvider = { tool: 'other_tool' };+ await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);+ });++ it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {+ const cindy = await makeCindy('hello.cindy', goodManifest());+ const result = await manager.install(cindy, { initiallyEnabled: false });+ expect('ghost' in result).toBe(true);+ expect((result as { ghost: InstalledGhost }).ghost.enabled).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);+ // 首个 onChanged 广播里就是沉睡态(不存在"先启用一帧再熄灯"的跳变)。+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0][0].enabled).toBe(false);+ // 重新启用即撕掉标记。+ await manager.setEnabled('hello', true);+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {+ const zip = new JSZip();+ zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));+ zip.file('hello-pack/assets/a.txt', 'a');+ const out = path.join(workDir, 'wrapped.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));++ const result = await manager.install(out);+ expect('ghost' in result).toBe(true);+ // 包裹层被剥掉:内容直接落在 <root>/hello/ 下+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);+ });++ it('源文件不存在 → source-not-found', async () => {+ await expectRejection(await manager.install(path.join(workDir, 'nope.cindy')), 'source-not-found');+ });++ it('不是 zip 的文件 → file-invalid', async () => {+ const bad = path.join(workDir, 'bad.cindy');+ await fs.promises.writeFile(bad, 'this is not a zip');+ await expectRejection(await manager.install(bad), 'file-invalid');+ });++ it('缺 ghost.json → file-invalid', async () => {+ const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('ghost.json 不是合法 JSON → file-invalid', async () => {+ const zip = new JSZip();+ zip.file('ghost.json', '{ not json');+ const out = path.join(workDir, 'badjson.cindy');+ await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ await expectRejection(await manager.install(out), 'file-invalid');+ });++ it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {+ const cindy = await makeCindy('decl.cindy', {+ schemaVersion: 1,+ id: 'legacy',+ name: '老声明型',+ version: '1.0.0',+ kind: 'declaration',+ panel: { title: '静态面板', body: '一段文字' },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {+ const manifest = {+ ...goodManifest(),+ slots: ['node'],+ tools: undefined,+ node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },+ };+ const cindy = await makeCindy('missing-node.cindy', manifest);+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(+ '包不能自带主机保留文件 %s',+ async (reservedFile) => {+ const cindy = await makeCindy('reserved.cindy', goodManifest(), {+ [reservedFile]: '{}',+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: {+ code: 'file-invalid',+ reason: expect.stringContaining('主机保留文件'),+ },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ },+ );++ it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {+ const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装+ expect(onChanged).not.toHaveBeenCalled();+ });++ // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。+ it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(+ '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',+ async (entryName) => {+ // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字+ // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。+ const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });+ const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {+ [entryName]: evilManifest,+ });+ expect(await manager.inspect(cindy)).toMatchObject({+ rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(onChanged).not.toHaveBeenCalled();+ },+ );++ it('重复装入同 id → already-installed,原安装不受影响', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();+ await expectRejection(await manager.install(await makeCindy('b.cindy', goodManifest())), 'already-installed');+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {+ await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));+ await expectRejection(+ await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),+ 'command-conflict',+ );+ expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘+ const ok = await manager.install(await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')));+ expect('ghost' in ok).toBe(true);+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ });+});++describe('GhostManager · uninstall', () => {+ it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello');+ expect('ok' in result).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(onChanged).toHaveBeenCalledTimes(1);+ expect(onChanged.mock.calls[0][0]).toEqual([]);+ });++ it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ onChanged.mockClear();++ const result = await manager.uninstall('hello', { notify: false });++ expect('ok' in result).toBe(true);+ expect(manager.list()).toEqual([]);+ expect(onChanged).not.toHaveBeenCalled();+ });++ it('persists builtin tombstone intent before removing approval or installed bytes', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).toHaveBeenCalledWith('hello');+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ });++ it('does not turn Host reconciliation cleanup into a user builtin tombstone', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');++ await expect(+ manager.uninstall('hello', { notify: false, recordBuiltinTombstone: false }),+ ).resolves.toEqual({ ok: true });++ expect(recordBuiltinTombstone).not.toHaveBeenCalled();+ expect(manager.list()).toEqual([]);+ });++ it('keeps builtin uninstall journal and bytes quarantined when tombstone persistence fails', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ trustedBundledIds.add('hello');+ recordBuiltinTombstone.mockImplementationOnce(() => {+ const error = new Error('access denied') as NodeJS.ErrnoException;+ error.code = 'EACCES';+ throw error;+ });++ await expect(manager.uninstall('hello', { notify: false })).resolves.toMatchObject({+ rejection: { code: 'io' },+ });++ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ manifest: { id: 'hello' },+ enabled: false,+ approval: { state: 'invalid' },+ });+ expect(+ JSON.parse(+ await fs.promises.readFile(+ path.join(workDir, 'ghosts-install-state', '.pending-hello.json'),+ 'utf8',+ ),+ ),+ ).toMatchObject({ kind: 'uninstall', builtinTombstone: true });+ });++ it('recovers a crashed builtin uninstall by persisting its tombstone before deletion', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const stateDir = path.join(workDir, 'ghosts-install-state');+ await fs.promises.mkdir(stateDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(stateDir, '.pending-hello.json'),+ `${JSON.stringify({+ version: 1,+ id: 'hello',+ kind: 'uninstall',+ builtinTombstone: true,+ })}\n`,+ );+ const recoveredTombstone = vi.fn(() => {+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(true);+ });++ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => id === 'hello',+ recordBuiltinTombstone: recoveredTombstone,+ });++ expect(recoveredTombstone).toHaveBeenCalledWith('hello');+ expect(recovered.list()).toEqual([]);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);+ expect(fs.existsSync(path.join(stateDir, '.pending-hello.json'))).toBe(false);+ });++ it('卸未装的 id → not-installed', async () => {+ const result = await manager.uninstall('ghost');+ expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ });++ it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {+ await fs.promises.mkdir(rootDir, { recursive: true });+ const sibling = path.join(workDir, 'victim');+ await fs.promises.mkdir(sibling);+ for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {+ const result = await manager.uninstall(id);+ expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');+ }+ expect(fs.existsSync(sibling)).toBe(true);+ });++ it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {+ const cindy = await makeCindy('a.cindy', goodManifest());+ await manager.install(cindy);+ await manager.uninstall('hello');+ const result = await manager.install(cindy);+ expect('ghost' in result).toBe(true);+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });+});++describe('GhostManager · list', () => {+ it('根目录不存在 → 空清单(不报错)', () => {+ expect(manager.list()).toEqual([]);+ });++ it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 手工捏三个坏目录+ await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));+ await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));+ await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');+ await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));+ await fs.promises.writeFile(+ path.join(rootDir, 'wrong-name', 'ghost.json'),+ JSON.stringify(goodManifest('other-id')),+ );+ // 隐藏目录(staging 残留形态)也不进清单+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));++ expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ });++ it('多意识按 id 排序', async () => {+ await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));+ await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));+ expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);+ });+});++describe('GhostManager · Host approval receipt', () => {+ /** 真实 copyFile 引用:mock 复制行为的用例要靠它放行非目标文件。 */+ const realCopyFile = fs.promises.copyFile;+ const receiptPath = (id = 'hello') =>+ path.join(workDir, 'ghosts-install-state', `${id}.json`);+ const writeBundledSource = async (+ manifest: InstalledGhost['manifest'],+ files: Record<string, string> = { 'main.js': '// bundled seed' },+ ): Promise<{ sourceDir: string }> => {+ const sourceDir = path.join(workDir, 'bundled-seeds', manifest.id);+ await fs.promises.rm(sourceDir, { recursive: true, force: true });+ await fs.promises.mkdir(sourceDir, { recursive: true });+ trustedBundledIds.add(manifest.id);+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(manifest));+ for (const [relativePath, content] of Object.entries(files)) {+ const target = path.join(sourceDir, relativePath);+ await fs.promises.mkdir(path.dirname(target), { recursive: true });+ await fs.promises.writeFile(target, content);+ }+ return { sourceDir };+ };++ /** 带 skill 槽的清单 + 配套包内文件(技能快照相关用例共用)。 */+ const skillManifest = (): Record<string, unknown> => ({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ });+ const skillFiles = (): Record<string, string> => ({+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });++ it('keeps manifest, enabled state, and trust independent from mutable install files', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const before = manager.list()[0];+ expect(fs.existsSync(receiptPath())).toBe(true);+ expect(path.dirname(receiptPath())).not.toBe(rootDir);++ await fs.promises.writeFile(+ path.join(rootDir, 'hello', 'ghost.json'),+ JSON.stringify({+ ...goodManifest(),+ version: '99.0.0',+ slots: ['node'],+ node: { entry: 'evil.cjs', protocol: 'json-rpc-stdio' },+ }),+ );+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ await fs.promises.writeFile(+ path.join(rootDir, 'hello', '.cindy-trust.json'),+ JSON.stringify({+ level: 'cindy-official',+ publisherSigned: true,+ publisherVerified: true,+ reviewed: true,+ }),+ );++ const after = manager.list()[0];+ expect(after.manifest).toEqual(before.manifest);+ // 启停是**非对称**的例外:`.disabled` 镜像允许把启停态往下拉(停用必须永远能+ // 成功,状态根不可写时镜像是唯一落点),但 manifest/trust/批准态不受安装目录+ // 影响,镜像也不能把插件往"启用"方向翻。+ expect(after.enabled).toBe(false);+ expect(after.trust).toEqual(before.trust);+ expect(after.approval.state).toBe('approved');++ // 移除镜像 → 回到 receipt 的授权事实(enabled=true 是用户确认装入时的决定)。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));+ expect(manager.list()[0].enabled).toBe(true);+ });++ it('fails legacy and corrupt receipts closed until a fully reviewed update replaces them', async () => {+ const legacyDir = path.join(rootDir, 'hello');+ await fs.promises.mkdir(legacyDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(legacyDir, 'ghost.json'),+ JSON.stringify(goodManifest()),+ );+ await fs.promises.writeFile(path.join(legacyDir, 'main.js'), '// legacy');++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ const reviewed = await updateGhost(+ await makeCindy('reviewed.cindy', { ...goodManifest(), version: '2.0.0' }),+ );+ expect(reviewed).toMatchObject({+ ghost: {+ manifest: { version: '2.0.0' },+ approval: { state: 'approved' },+ },+ });++ await fs.promises.writeFile(receiptPath(), '{ broken');+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('rejects an update when the approved revision changed after review', async () => {+ await manager.install(await makeCindy('v1.cindy', goodManifest()));+ const staleApproval = ghostInstallApprovalToken(manager.list()[0].approval);+ const v2 = await makeCindy('v2.cindy', {+ ...goodManifest(),+ version: '2.0.0',+ });+ const first = await manager.update(v2, {+ expectedInstalledApproval: staleApproval,+ });+ expect(first).toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });++ const v3 = await makeCindy('v3.cindy', {+ ...goodManifest(),+ version: '3.0.0',+ });+ await expectRejection(+ await manager.update(v3, {+ expectedInstalledApproval: staleApproval,+ }),+ 'state-changed',+ );+ 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'),+ slots: ['tool', 'skill'],+ skill: {+ items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }],+ },+ };+ const cindy = await makeCindy('skill.cindy', manifest, {+ 'skills/demo/SKILL.md':+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });+ await manager.install(cindy);+ const listed = manager.list()[0];+ expect(listed.approvedSkillRoot).toBeTruthy();+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(true);++ await manager.uninstall('skilled');+ expect(fs.existsSync(receiptPath('skilled'))).toBe(false);+ expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(false);+ });++ it('keeps an uninstall journal when receipt cleanup fails after content removal', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ await fs.promises.rm(receiptPath());+ await fs.promises.mkdir(receiptPath());+ await fs.promises.writeFile(path.join(receiptPath(), 'blocked'), 'x');++ const result = await manager.uninstall('hello');++ expect(result).toEqual({ ok: true });+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);+ expect(manager.list()).toEqual([]);+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(+ true,+ );+ await fs.promises.rm(receiptPath(), { recursive: true, force: true });+ const recovered = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ onChanged,+ });+ expect(recovered.list()).toEqual([]);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json')),+ ).toBe(false);+ });++ it('keeps disabling possible when the approved skill snapshot is gone, and rebuilds it on enable', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 外部把快照删掉:停用是安全方向,必须仍然成功,不能把插件卡在既不能用也不能关。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'approved' },+ });++ // 重新启用时从当前安装目录重建快照,不需要用户重新走一次确认。+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ const healed = manager.list()[0];+ expect(healed.enabled).toBe(true);+ expect(healed.approvedSkillRoot).toBe(snapshotRoot);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).toContain('Approved instructions');+ });++ it('refuses to rebuild an enable-time snapshot from install bytes that drifted from the approved manifest', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 安装目录里的 SKILL.md 与批准 manifest 声明的 description 不再一致,快照也没了:+ // 停用照样成功(安全方向),但重建快照必须拒——否则启用就等于批准一份用户+ // 没看过的技能指令。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Silently widened skill\n---\n\nTampered instructions\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('prunes skill snapshots left behind by superseded approval revisions', async () => {+ await manager.install(await makeCindy('skill-v1.cindy', skillManifest(), skillFiles()));+ const firstSnapshot = manager.list()[0].approvedSkillRoot!;+ const snapshotParent = path.dirname(firstSnapshot);++ await updateGhost(+ await makeCindy(+ 'skill-v2.cindy',+ { ...skillManifest(), version: '2.0.0' },+ skillFiles(),+ ),+ 'skilled',+ );+ const secondSnapshot = manager.list()[0].approvedSkillRoot!;++ expect(secondSnapshot).not.toBe(firstSnapshot);+ expect(await fs.promises.readdir(snapshotParent)).toEqual([+ path.basename(secondSnapshot),+ ]);+ });++ it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const idDir = path.join(workDir, 'ghosts-install-state', 'skill-snapshots', 'skilled');+ // 外部目录里放一个"看起来像旧 revision"的子目录 + 哨兵文件。+ const external = path.join(workDir, 'external-data');+ await fs.promises.mkdir(path.join(external, 'stale-revision'), { recursive: true });+ await fs.promises.writeFile(path.join(external, 'stale-revision', 'sentinel.txt'), 'keep');+ // 把 `<id>` 父段整个换成指向外部目录的 junction(同权限进程可做到)。+ await fs.promises.rm(idDir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(external, idDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 环境建不了链接则跳过;判定逻辑平台同源。+ }++ // 触发一次 receipt 写(启停翻转):修复前 ensureSkillSnapshot 会沿 junction 把+ // 快照发布到外部目录,prune 的 readdir + 逐项 recursive rm 更会把外部目录里的+ // "旧 revision"整个删掉(sentinel 消失)。修复后父段遏制先行:可疑父段整体跳过。+ await manager.setEnabled('skilled', false);+ expect(fs.existsSync(path.join(external, 'stale-revision', 'sentinel.txt'))).toBe(true);+ // 外部目录里也不应多出任何被"发布"进去的快照字节。+ expect(await fs.promises.readdir(external)).toEqual(['stale-revision']);+ });++ it('holds the install-time SKILL.md size ceiling when rebuilding from mutable install bytes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const installedSkillMd = path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md');+ // 快照缺失时取字节的来源是可变安装目录。这里塞的 SKILL.md frontmatter 与批准+ // manifest 完全一致(躲过一致性校验),只是正文超过装入侧上限 —— 重建必须照样拒,+ // 否则启用这条路会批准一份装入/更新永远不会接受的超大技能指令,而且要先整份+ // 读进内存。+ await fs.promises.writeFile(+ installedSkillMd,+ `---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n${'padding '.repeat(+ GHOST_SKILL_MD_MAX_BYTES / 4,+ )}`,+ );+ expect((await fs.promises.lstat(installedSkillMd)).size).toBeGreaterThan(+ GHOST_SKILL_MD_MAX_BYTES,+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when only the SKILL.md body drifted', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // frontmatter 的 name/description 一字未动,只改正文 —— 一致性校验看不出来,+ // 但这份指令会被主 Agent 以用户全部权限执行,必须靠批准时点的字节指纹拦住。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to rebuild a snapshot when a helper file was added to the skill directory', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // SKILL.md 完全没动,只往技能目录里塞一个被指令引用的辅助文件(点文件同样算)。+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', '.helper.sh'),+ '#!/bin/sh\necho injected\n',+ );+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('refuses to follow a link planted inside the skill directory when rebuilding', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const outside = path.join(workDir, 'outside-skill');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(path.join(outside, 'leak.txt'), 'bytes from outside the skill dir');+ // Windows junction 不需要管理员权限即可创建,是本平台成本最低的一条"把技能目录+ // 之外的字节拉进批准快照"的路子。判据不能建立在 Dirent 类型位的实现细节上,+ // 所以这条用例把行为钉住:planted link 一律拒,快照不落地。+ try {+ await fs.promises.symlink(+ outside,+ path.join(rootDir, 'skilled', 'skills', 'demo', 'linked'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ } catch {+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。+ }+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ // 状态根里不该出现任何来自技能目录之外的字节(含崩溃残留的 .tmp)。+ const stateRoot = manager.approvalStateRoot();+ const leaked: string[] = [];+ const walk = (dir: string): void => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const child = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(child);+ else if (entry.name === 'leak.txt') leaked.push(child);+ }+ };+ if (fs.existsSync(stateRoot)) walk(stateRoot);+ expect(leaked).toEqual([]);+ });++ it('rejects bytes swapped after the hash check but before the snapshot copy finishes', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 先停用、再删快照:停用本身会把快照重建回来(字节没动、校验放行),顺序颠倒+ // 会让后面的启用走"快照已存在"的早退路径,根本不经过复制。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 模拟同权限本机进程抢在复制这一刻换掉源字节:复制动作落到 temp 的是被改写的+ // 内容,而源目录事后看起来仍然"没问题"。所以校验必须落在**已经复制到 temp 的+ // 那份字节**上;若校验读的是源目录,这里就会放行一份没人确认过的技能指令。+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, tampered, 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ try {+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ } finally {+ spy.mockRestore();+ }+ expect(swapped).toBe(1); // 确认这一轮真的走到了复制+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('applies the SKILL.md size ceiling to the bytes that actually landed in the snapshot', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ // 源目录看起来一切正常(预检放行),复制这一刻落到 temp 的却是超大文件。上限必须+ // 作用在这份字节上,而不是只作用在预检读到的那份 —— 预检不是安全边界。+ let swapped = 0;+ const spy = vi+ .spyOn(fs.promises, 'copyFile')+ .mockImplementation((async (from: unknown, to: unknown, mode?: unknown) => {+ if (typeof from === 'string' && from.endsWith('SKILL.md') && typeof to === 'string') {+ swapped += 1;+ await fs.promises.writeFile(to, 'x'.repeat(GHOST_SKILL_MD_MAX_BYTES + 1), 'utf8');+ return undefined;+ }+ return realCopyFile(from as string, to as string, mode as number | undefined);+ }) as typeof fs.promises.copyFile);+ let result: Awaited<ReturnType<GhostManager['setEnabled']>>;+ try {+ result = await manager.setEnabled('skilled', true);+ } finally {+ spy.mockRestore();+ }+ await expectRejection(result, 'io');+ // 断言到 reason 才能区分校验顺序:上限先跑报"exceeds N bytes",指纹先跑报+ // "no longer matches..."。只比 code 的话两种顺序都是 io,用例就退化成+ // 行为钉住、测不出重排。+ expect((result as { rejection: { reason: string } }).rejection.reason).toMatch(+ /exceeds \d+ bytes/,+ );+ expect(swapped).toBe(1);+ expect(manager.list()[0].enabled).toBe(false);+ expect(fs.existsSync(snapshotRoot)).toBe(false);+ });++ it('keeps an install unusable when a stale approval cannot be revoked', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ // 撤销失败(状态根不可写等,与写批准失败同一成因)不得退回"继续拿旧批准跑":+ // removeInstallApproval 的契约是返回后一定不再被授权运行。+ const spy = vi+ .spyOn(fs.promises, 'rm')+ .mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));+ try {+ await manager.removeInstallApproval('hello');+ } finally {+ spy.mockRestore();+ }++ expect(fs.existsSync(receiptPath())).toBe(true); // receipt 还在盘上+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');+ });++ it('does not trust an already-present snapshot whose bytes were rewritten in place', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const snapshotSkillMd = path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md');+ // 快照就位后被就地改写(状态根没有写保护)。主 Agent 是顺着共享链接持续读它的,+ // 所以"快照已存在"不能当成"仍是被批准的那份字节"直接早退信任。+ await fs.promises.writeFile(+ snapshotSkillMd,+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 安装目录里的字节没动过 → 删掉坏快照后能按批准字节重建,自愈。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(await fs.promises.readFile(snapshotSkillMd, 'utf8')).toContain('Approved instructions');+ });++ it('refuses to keep a rewritten snapshot when the installed bytes drifted too', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ // 快照与安装目录都被改成同一份未批准内容:此时没有任何可信来源可重建,必须拒。+ await fs.promises.writeFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), tampered);+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ tampered,+ );++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('still heals a deleted snapshot when the installed skill bytes are untouched', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ // 字节指纹校验不能把合法的自愈场景一起堵死:外部清理误删快照、内容没动过。+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });++ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(manager.list()[0].enabled).toBe(true);+ expect(+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),+ ).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(+ await fs.promises.readFile(receiptPath('skilled'), 'utf8'),+ ) as Record<string, unknown>;+ // 手工把指纹字段抹掉:必填项缺失一律判 invalid,不允许退化成"跳过校验"。+ delete receipt.skillContentSha256;+ await fs.promises.writeFile(receiptPath('skilled'), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('invalidates a schema v1 receipt instead of trusting its legacy content digests', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ // v2 改了内容摘要 framing;旧 receipt 的摘要不能拿来继续授权,必须 fail closed。+ receipt.schemaVersion = 1;+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },+ });+ });++ it('revoking approval fails the install closed, and a later bundled approval heals it', async () => {+ await manager.install(await makeCindy('approved.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;++ // 随包对账在换入新种子字节后写批准失败时走的收敛动作:撤掉陈旧批准。+ // 撤掉之后插件必须彻底不可运行,而不是继续拿旧批准跑新代码。+ await manager.removeInstallApproval('hello');++ expect(fs.existsSync(receiptPath())).toBe(false);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'legacy-unapproved' },+ });+ await expectRejection(await manager.setEnabled('hello', true), 'approval-required');++ // 下一轮启动对账重新补批准即自愈,不需要用户介入。+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: true,+ approval: { state: 'approved' },+ });+ });++ it('uses the immutable bundled source directory when minting the approval receipt', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const sourceDir = path.join(workDir, 'bundled-seeds', approvedManifest.id);+ trustedBundledIds.add(approvedManifest.id);+ await fs.promises.mkdir(sourceDir, { recursive: true });+ await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(approvedManifest));+ await fs.promises.writeFile(path.join(sourceDir, 'main.js'), 'immutable bundled bytes');+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'mutable bytes');++ const unsafeCall = manager.approveTrustedBundledInstall as unknown as (+ manifest: InstalledGhost['manifest'],+ markerEnabled: boolean,+ ) => Promise<boolean>;+ await expect(unsafeCall.call(manager, approvedManifest, true)).rejects.toThrow(+ /verified bundled source directory/,+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: path.join(rootDir, approvedManifest.id),+ }),+ ).rejects.toThrow(/mutable installed directory/);+ const arbitrarySourceDir = path.join(workDir, 'arbitrary-source', approvedManifest.id);+ await fs.promises.mkdir(arbitrarySourceDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(arbitrarySourceDir, 'ghost.json'),+ JSON.stringify(approvedManifest),+ );+ await expect(+ manager.approveTrustedBundledInstall(approvedManifest, true, {+ sourceDir: arbitrarySourceDir,+ }),+ ).rejects.toThrow(/trusted seed roster/);++ expect(+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir }),+ ).toBe(true);+ const receipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ const sourcePackageSha256 = receipt.packageSha256;+ await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'different mutable bytes');+ await manager.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ const stableReceipt = JSON.parse(await fs.promises.readFile(receiptPath(), 'utf8')) as {+ packageSha256?: string;+ };+ expect(stableReceipt.packageSha256).toBe(sourcePackageSha256);+ });++ it('publishes bundled replacements through the pending journal and commits on receipt write', async () => {+ await manager.install(await makeCindy('old.cindy', goodManifest()));+ const approvedManifest = manager.list()[0].manifest;+ const { sourceDir } = await writeBundledSource(approvedManifest, {+ 'main.js': 'immutable replacement bytes',+ });+ const stateRoot = manager.approvalStateRoot();+ const pendingPath = path.join(stateRoot, '.pending-hello.json');++ await manager.runExclusiveMutation(async (mutation) => {+ expect(await mutation.removeInstallApproval('hello')).toBe(true);+ await mutation.publishTrustedBundledSeed('hello', sourceDir, { disabled: false });+ expect(fs.existsSync(pendingPath)).toBe(true);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(true);+ await mutation.approveTrustedBundledInstall(approvedManifest, true, { sourceDir });+ });++ expect(await fs.promises.readFile(path.join(rootDir, 'hello', 'main.js'), 'utf8')).toBe(+ 'immutable replacement bytes',+ );+ expect(fs.existsSync(pendingPath)).toBe(false);+ expect(+ (await fs.promises.readdir(rootDir)).some((name) =>+ name.startsWith('.cindy-updating-hello-'),+ ),+ ).toBe(false);+ expect(manager.list()[0].approval.state).toBe('approved');});- it('容忍"多包一层文件夹"的压缩形态(ghost.json 在唯一顶层目录下)', async () => {- const zip = new JSZip();- zip.file('hello-pack/ghost.json', JSON.stringify(goodManifest()));- zip.file('hello-pack/assets/a.txt', 'a');- const out = path.join(workDir, 'wrapped.cindy');- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));+ it('keeps a receipt-pinned disable when the .disabled mirror was lost, and rewrites the mirror', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ // 随包对账首轮把安装收编成 bundled 批准(trust 归一),后续轮次走稳态分支。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);- const result = await manager.install(out);- expect('ghost' in result).toBe(true);- // 包裹层被剥掉:内容直接落在 <root>/hello/ 下- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello', 'assets', 'a.txt'))).toBe(true);- });+ // 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));- it('源文件不存在 → source-not-found', async () => {- await expectRejection(await manager.install(path.join(workDir, 'nope.cindy')), 'source-not-found');+ // 下一轮对账把镜像读数(启用)喂进来:不得据此翻转 receipt —— 否则用户显式+ // 停用的插件被静默重新启用,无确认、无审计。重新启用只有 setEnabled 一条路。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(false);+ expect(manager.list()[0].enabled).toBe(false);+ // 镜像被补写回去:回滚到旧客户端(只认镜像文件)时仍按停用对待。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);});- it('不是 zip 的文件 → file-invalid', async () => {- const bad = path.join(workDir, 'bad.cindy');- await fs.promises.writeFile(bad, 'this is not a zip');- await expectRejection(await manager.install(bad), 'file-invalid');- });+ it('an old-client style .disabled marker still turns a bundled receipt off', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ const source = await writeBundledSource(approvedManifest);+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);- it('缺 ghost.json → file-invalid', async () => {- const cindy = await makeCindy('no-manifest.cindy', null, { 'readme.txt': 'x' });- await expectRejection(await manager.install(cindy), 'file-invalid');+ // 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——+ // 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ expect(await manager.approveTrustedBundledInstall(approvedManifest, false, source)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);});- it('ghost.json 不是合法 JSON → file-invalid', async () => {- const zip = new JSZip();- zip.file('ghost.json', '{ not json');- const out = path.join(workDir, 'badjson.cindy');- await fs.promises.writeFile(out, await zip.generateAsync({ type: 'nodebuffer' }));- await expectRejection(await manager.install(out), 'file-invalid');+ it('a bundled update keeps the receipt-pinned disable even when the marker was lost', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ expect(+ await manager.approveTrustedBundledInstall(+ approvedManifest,+ true,+ await writeBundledSource(approvedManifest),+ ),+ ).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));++ // 随包更新那一轮走的是"建全新 receipt"分支,与稳态分支共用同一条合并规则:+ // 只堵稳态分支的话,镜像在更新 tick 之前丢失仍会静默重新启用,同一个洞换条路。+ const bumped = { ...approvedManifest, version: '1.0.1' };+ expect(+ await manager.approveTrustedBundledInstall(+ bumped,+ true,+ await writeBundledSource(bumped),+ ),+ ).toBe(true);+ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ manifest: { version: '1.0.1' },+ });+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);});- it('清单不合格(老声明型格式,已移除)→ file-invalid', async () => {- const cindy = await makeCindy('decl.cindy', {- schemaVersion: 1,- id: 'legacy',- name: '老声明型',- version: '1.0.0',- kind: 'declaration',- panel: { title: '静态面板', body: '一段文字' },+ it('refuses to mint a bundled approval for an id outside the seed roster', async () => {+ // 该入口不经用户确认就铸出批准;builtin-only 边界必须运行期强制,不能只靠+ // "唯一调用者是随包对账"这条纪律。+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: () => false,});- await expectRejection(await manager.install(cindy), 'file-invalid');+ const validated = validateGhostManifest(goodManifest());+ if (!validated.ok) throw new Error(validated.reason);+ await expect(+ guarded.approveTrustedBundledInstall(+ validated.manifest,+ true,+ await writeBundledSource(validated.manifest),+ ),+ ).rejects.toThrow(/种子清单/);});- it('Node 清单声明的 worker 不在包内 → inspect/install 都拒绝', async () => {+ it('invalidates a receipt whose locale snapshot keys no longer match the manifest', async () => {+ hostLocale = 'en';const manifest = {...goodManifest(),- slots: ['node'],- tools: undefined,- node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' },+ locales: { en: 'locales/en.json' },};- const cindy = await makeCindy('missing-node.cindy', manifest);- expect(await manager.inspect(cindy)).toMatchObject({- rejection: { code: 'file-invalid', reason: expect.stringContaining('node/worker.cjs') },+ await manager.install(+ await makeCindy('localized.cindy', manifest, {+ 'locales/en.json': JSON.stringify({ name: 'Approved English name' }),+ }),+ );+ const receipt = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as Record<string, unknown>;+ receipt.localeResources = {};+ await fs.promises.writeFile(receiptPath(), JSON.stringify(receipt));++ expect(manager.list()[0]).toMatchObject({+ enabled: false,+ approval: { state: 'invalid' },});- await expectRejection(await manager.install(cindy), 'file-invalid');});+});- it.each(['.disabled', '.cindy-trust.json', '.CINDY-TRUST.JSON'])(- '包不能自带主机保留文件 %s',- async (reservedFile) => {- const cindy = await makeCindy('reserved.cindy', goodManifest(), {- [reservedFile]: '{}',- });- expect(await manager.inspect(cindy)).toMatchObject({- rejection: {- code: 'file-invalid',- reason: expect.stringContaining('主机保留文件'),- },- });- await expectRejection(await manager.install(cindy), 'file-invalid');- },- );-- it('zip-slip(条目路径带 ../)→ file-invalid,且仓库外不落任何文件', async () => {- const cindy = await makeCindy('slip.cindy', goodManifest(), { '../evil.txt': 'pwned' });- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(workDir, 'evil.txt'))).toBe(false);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false); // staging 已清理,无半截安装- expect(onChanged).not.toHaveBeenCalled();+describe('GhostManager · 技能批准基线取自包投影(publish 后篡改必须拒装)', () => {+ it('staging→final 发布后、首次校验前换掉 SKILL.md → 拒装,篡改字节不成为批准事实', async () => {+ const cindy = await makeCindy('skill.cindy', {+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },+ }, {+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',+ });+ // 故障注入:staging→final 的 rename 真实执行后,立刻在 finalDir 里改写 SKILL.md+ // 正文 —— 模拟"发布与首次 hash 之间"的本机进程篡改窗口。+ const realRename = fs.promises.rename;+ const finalDir = path.join(rootDir, 'skilled');+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ await realRename(from, to);+ if (String(to) === finalDir) {+ spy.mockRestore();+ await fs.promises.writeFile(+ path.join(finalDir, 'skills', 'demo', 'SKILL.md'),+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );+ }+ });+ try {+ const result = await manager.install(cindy);+ // 修复前:指纹从被篡改的 finalDir 首读,篡改字节自洽地成为 receipt 指纹与+ // 快照,install 返回 ok。修复后:指纹来自包投影,快照对账发现字节不符 → 拒装。+ expect('rejection' in result, JSON.stringify(result)).toBe(true);+ } finally {+ spy.mockRestore();+ }+ // 拒装收尾:不留半截安装,也没有任何批准事实落盘。+ expect(manager.list()).toHaveLength(0);+ expect(+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'skilled.json')),+ ).toBe(false);});+});- // `a//b` 空段变体 JSZip 写入时会自行归一,构造不出夹具;守卫仍覆盖它。- it.each(['x/../ghost.json', './ghost.json', '/ghost.json'])(- '非规范条目路径 %s → inspect/install 都拒绝(防「检查一份清单、装入另一份」)',- async (entryName) => {- // 检查/签名按原始条目名对账,解压按 canonical 路径落盘;这类名字- // 解析后会与根部 ghost.json 撞同一落盘位置,必须在读清单前整包拒。- const evilManifest = JSON.stringify({ ...goodManifest(), name: '偷换的' });- const cindy = await makeCindy('noncanonical.cindy', goodManifest(), {- [entryName]: evilManifest,- });- expect(await manager.inspect(cindy)).toMatchObject({- rejection: { code: 'file-invalid', reason: expect.stringContaining('非法路径') },- });- await expectRejection(await manager.install(cindy), 'file-invalid');- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(onChanged).not.toHaveBeenCalled();- },- );-- it('重复装入同 id → already-installed,原安装不受影响', async () => {+describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {+ it('final 缺位 + 唯一 backup → 下次启动自动搬回,插件不凭空消失', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();- await expectRejection(await manager.install(await makeCindy('b.cindy', goodManifest())), 'already-installed');- expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);- expect(onChanged).not.toHaveBeenCalled();- });-- it('显式指令撞名(含大小写折叠)→ command-conflict;不撞则各装各的', async () => {- await manager.install(await makeCindy('a.cindy', chipManifestWithCommand('alpha', 'Draw')));- await expectRejection(- await manager.install(await makeCindy('b.cindy', chipManifestWithCommand('beta', 'draw'))),- 'command-conflict',+ // 模拟崩溃现场:final→backup 已发生,staging→final 没来得及。+ await fs.promises.rename(+ path.join(rootDir, 'hello'),+ path.join(rootDir, '.cindy-updating-hello-abcdef01'),);- expect(fs.existsSync(path.join(rootDir, 'beta'))).toBe(false); // 半点不落盘- const ok = await manager.install(await makeCindy('c.cindy', chipManifestWithCommand('gamma', '画图')));- expect('ghost' in ok).toBe(true);- expect(manager.list().map((g) => g.manifest.id)).toEqual(['alpha', 'gamma']);+ // 崩溃前 list() 视角:插件消失(点目录被跳过)—— 这正是要修的现场。+ expect(manager.list()).toHaveLength(0);++ // "重启":新建 manager,构造期恢复扫描搬回。receipt 从未更新过,恢复后+ // receipt 与内容完全一致,等价于那次更新从未发生。+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(restarted.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);});-});-describe('GhostManager · uninstall', () => {- it('卸下已装意识:目录消失、list 变空、onChanged 广播', async () => {+ it('final 是普通文件时不删除唯一 backup', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.writeFile(finalDir, 'unexpected file');- const result = await manager.uninstall('hello');- expect('ok' in result).toBe(true);- expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);- expect(manager.list()).toEqual([]);- expect(onChanged).toHaveBeenCalledTimes(1);- expect(onChanged.mock.calls[0][0]).toEqual([]);+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });++ expect((await fs.promises.lstat(finalDir)).isFile()).toBe(true);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);});- it('host 可延后卸载广播,先完成 tombstone 等事务后再发一致快照', async () => {+ it('final 是 junction/链接时不删除唯一 backup', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));- onChanged.mockClear();-- const result = await manager.uninstall('hello', { notify: false });+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ const outsideDir = path.join(workDir, 'outside-final-target');+ await fs.promises.rename(finalDir, backupDir);+ await fs.promises.mkdir(outsideDir, { recursive: true });+ try {+ await fs.promises.symlink(outsideDir, finalDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // Windows 环境未授予建链接权限时跳过;生产判据仍由 lstat 钉住。+ }- expect('ok' in result).toBe(true);- expect(manager.list()).toEqual([]);- expect(onChanged).not.toHaveBeenCalled();- });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });- it('卸未装的 id → not-installed', async () => {- const result = await manager.uninstall('ghost');- expect((result as { rejection: { code: string } }).rejection.code).toBe('not-installed');+ expect((await fs.promises.lstat(finalDir)).isSymbolicLink()).toBe(true);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);});- it('非法 id(路径穿越企图)→ invalid-id,不触碰文件系统', async () => {- await fs.promises.mkdir(rootDir, { recursive: true });- const sibling = path.join(workDir, 'victim');- await fs.promises.mkdir(sibling);- for (const id of ['../victim', '..\\victim', 'a/b', 'A', '']) {- const result = await manager.uninstall(id);- expect((result as { rejection: { code: string } }).rejection.code, id).toBe('invalid-id');+ it('final lstat EACCES 时不删除唯一 backup', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const finalDir = path.join(rootDir, 'hello');+ const backupDir = path.join(rootDir, '.cindy-updating-hello-abcdef01');+ await fs.promises.rename(finalDir, backupDir);+ const realLstatSync = fs.lstatSync;+ const spy = vi.spyOn(fs, 'lstatSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[]) => {+ if (path.resolve(String(target)) === path.resolve(finalDir)) {+ throw Object.assign(new Error('EACCES: final path locked'), { code: 'EACCES' });+ }+ return (realLstatSync as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.lstatSync);+ try {+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ } finally {+ spy.mockRestore();}- expect(fs.existsSync(sibling)).toBe(true);- });- it('卸下再重装同一个 .cindy → 复活(装/卸/装全链路)', async () => {- const cindy = await makeCindy('a.cindy', goodManifest());- await manager.install(cindy);- await manager.uninstall('hello');- const result = await manager.install(cindy);- expect('ghost' in result).toBe(true);- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);+ expect(fs.existsSync(finalDir)).toBe(false);});-});-describe('GhostManager · list', () => {- it('根目录不存在 → 空清单(不报错)', () => {- expect(manager.list()).toEqual([]);+ it('final 在位的陈旧 backup 与 staging 残留 → 回收;同 id 多个 backup 不猜、原样保留', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-abcdef01'), { recursive: true });+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-hello-deadbeef'), { recursive: true });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, '.cindy-installing-hello-deadbeef'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);++ // 多 backup 且 final 缺位:不猜哪份是对的,原样保留等人工处理。+ await fs.promises.rename(path.join(rootDir, 'hello'), path.join(rootDir, '.cindy-updating-hello-11111111'));+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-22222222'), { recursive: true });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-11111111'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-22222222'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);});- it('坏目录只影响自己:无 ghost.json / 清单非法 / 目录名与 id 不符的都被跳过', async () => {- await manager.install(await makeCindy('a.cindy', goodManifest()));- // 手工捏三个坏目录- await fs.promises.mkdir(path.join(rootDir, 'no-manifest'));- await fs.promises.mkdir(path.join(rootDir, 'bad-manifest'));- await fs.promises.writeFile(path.join(rootDir, 'bad-manifest', 'ghost.json'), '{ nope');- await fs.promises.mkdir(path.join(rootDir, 'wrong-name'));- await fs.promises.writeFile(- path.join(rootDir, 'wrong-name', 'ghost.json'),- JSON.stringify(goodManifest('other-id')),+ it('id 是另一个 id 的 `-` 前缀(hello / hello-x)各留唯一 backup → 两者都搬回,不因前缀误判互相拖累(P1)', async () => {+ // 回归:siblings 统计曾用 startsWith(`.cindy-updating-${id}-`) 前缀匹配,+ // `.cindy-updating-hello-<hex>` 是 `.cindy-updating-hello-x-<hex>` 的前缀,+ // 于是处理 hello 时把 hello-x 的 backup 也算进来 → siblings 变 2 → 判"多备份+ // 留待人工" → hello 崩溃后持续消失。修复后按解析 id 精确比对,两者各自恢复。+ await manager.install(await makeCindy('a.cindy', goodManifest('hello')));+ await manager.install(await makeCindy('b.cindy', goodManifest('hello-x')));+ // 两个插件都卡在"final→backup 已发生,staging→final 未完成"的崩溃现场,+ // 且各自只有唯一 backup(合法可恢复的场景)。+ await fs.promises.rename(+ path.join(rootDir, 'hello'),+ path.join(rootDir, '.cindy-updating-hello-11111111'),+ );+ await fs.promises.rename(+ path.join(rootDir, 'hello-x'),+ path.join(rootDir, '.cindy-updating-hello-x-22222222'),);- // 隐藏目录(staging 残留形态)也不进清单- await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-x-deadbeef'));- expect(manager.list().map((c) => c.manifest.id)).toEqual(['hello']);- });+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });- it('多意识按 id 排序', async () => {- await manager.install(await makeCindy('b.cindy', { ...goodManifest('zulu'), name: 'Z' }));- await manager.install(await makeCindy('a.cindy', { ...goodManifest('alpha'), name: 'A' }));- expect(manager.list().map((c) => c.manifest.id)).toEqual(['alpha', 'zulu']);+ // 两者都应搬回 final,backup 清空 —— hello 不能被 hello-x 的存在拖成"消失"。+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, 'hello-x', 'ghost.json'))).toBe(true);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-11111111'))).toBe(false);+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-x-22222222'))).toBe(false);});});@@@ -3805,24 -518,6 +4016,80 @@@ describe('GhostManager · setEnabled(�});describe('GhostManager · inspect(只验不装)', () => {++ it('opens a top-level .cindy source in non-blocking mode', async () => {++ const cindy = await makeCindy('nonblocking.cindy', goodManifest());++ const realOpen = fs.promises.open;++ const flags: number[] = [];++ const spy = vi.spyOn(fs.promises, 'open').mockImplementation((async (++ ...args: Parameters<typeof fs.promises.open>++ ) => {++ if (path.resolve(String(args[0])) === path.resolve(cindy)) {++ flags.push(Number(args[1]));++ }++ return realOpen(...args);++ }) as typeof fs.promises.open);++++ try {++ await manager.inspect(cindy);++ } finally {++ spy.mockRestore();++ }++++ expect(flags).toHaveLength(1);++ const nonBlockingFlag = fs.constants.O_NONBLOCK ?? 0;++ expect(flags[0] & nonBlockingFlag).toBe(nonBlockingFlag);++ });++++ it('rejects a top-level .cindy source whose ctime changes during the read', async () => {++ const cindy = await makeCindy('ctime-change.cindy', goodManifest());++ const realOpen = fs.promises.open;++ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (++ ...args: Parameters<typeof fs.promises.open>++ ) => {++ const handle = await realOpen(...args);++ if (path.resolve(String(args[0])) !== path.resolve(cindy)) return handle;++ const originalStat = handle.stat.bind(handle);++ let statCalls = 0;++ vi.spyOn(handle, 'stat').mockImplementation(async (...statArgs) => {++ const stat = await originalStat(...statArgs);++ statCalls += 1;++ if (statCalls === 2) {++ Object.defineProperty(stat, 'ctimeMs', {++ value: Number(stat.ctimeMs) + 1,++ });++ }++ return stat;++ });++ return handle;++ }) as typeof fs.promises.open);++++ try {++ await expect(manager.inspect(cindy)).resolves.toMatchObject({++ rejection: { code: 'io' },++ });++ } finally {++ openSpy.mockRestore();++ }++ });+++ it('allows a top-level .cindy symlink and installs the inspected target bytes', async () => {+ const target = await makeCindy('symlink-target.cindy', goodManifest());+ const linked = path.join(workDir, 'symlink-source.cindy');+ try {+ await fs.promises.symlink(target, linked, 'file');+ } catch {+ return; // Windows without file-symlink capability cannot exercise this POSIX regression.+ }++ const inspected = await manager.inspect(linked);+ expect('packageSha256' in inspected).toBe(true);+ if (!('packageSha256' in inspected)) return;+ const installed = await manager.install(linked, {+ expectedPackageSha256: inspected.packageSha256,+ });+ expect('ghost' in installed).toBe(true);+ });+it('合法 .cindy → 返回清单,且零副作用(仓库目录不被创建)', async () => {const cindy = await makeCindy('a.cindy', goodManifest());const result = await manager.inspect(cindy);@@@ -4102,3 -783,3 +4369,40 @@@ describe('GhostManager · skill 槽装�await expectRejection(await manager.install(cindy), 'file-invalid');});});++describe('legacy trust mirror hardening', () => {++ it('degrades an unreadable trust mirror to unverified instead of wedging recovery', async () => {++ await writeLegacyInstall('linked-trust', goodManifest('linked-trust'), {++ trust: {++ level: 'verified-publisher',++ publisherSigned: true,++ publisherVerified: true,++ reviewed: false,++ publisherName: 'Acme',++ },++ });++ const realOpenSync = fs.openSync;++ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => {++ if (typeof p === 'string' && p.endsWith(path.join('linked-trust', '.cindy-trust.json'))) {++ const err = new Error('ELOOP: too many symbolic links encountered') as NodeJS.ErrnoException;++ err.code = 'ELOOP';++ throw err;++ }++ return (realOpenSync as (...a: unknown[]) => number)(p, ...rest);++ }) as typeof fs.openSync);++++ try {++ const frozen = await readLegacyGhostApprovalProjection(++ path.join(rootDir, 'linked-trust'),++ 'linked-trust',++ );++ expect(frozen.projection.trust).toMatchObject({++ level: 'unverified',++ publisherSigned: false,++ publisherVerified: false,++ reviewed: false,++ });++ } finally {++ spy.mockRestore();++ }++ });++});diff --cc apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.tsindex 0a20d38aea,0a20d38aea..a9c1d5d01d--- a/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts@@@ -43,6 -43,6 +43,34 @@@ function makeDispatcher(overrides: Partreturn { dispatcher: new GhostCardActionDispatcher(deps), wake, sendToGhost, reopenForAction };}++describe('cardActionDispatch owner boundary', () => {++ it('rechecks the owner after wake and never sends to a stale Ghost', async () => {++ let releaseWake!: () => void;++ let ownerValid = true;++ const onInvalidated = vi.fn();++ const wake = vi.fn(() => new Promise<void>((resolve) => { releaseWake = resolve; }));++ const { dispatcher, sendToGhost } = makeDispatcher({++ isRunning: () => false,++ wake,++ ownerScope: {++ capture: () => ({ ownerId: 'owner-a', generation: 1 }),++ isCurrent: () => ownerValid,++ isStable: () => ownerValid,++ onInvalidated,++ },++ });++++ const resultPromise = dispatcher.dispatch('call-abc', CUSTOM_ID);++ await vi.waitFor(() => expect(wake).toHaveBeenCalledOnce());++ ownerValid = false;++ releaseWake();++++ await expect(resultPromise).resolves.toEqual({ ok: false, reason: 'owner-boundary' });++ expect(sendToGhost).not.toHaveBeenCalled();++ expect(onInvalidated).toHaveBeenCalledWith('cindy-mivo');++ });++});++const CALL_ID = 'call-abc';const CUSTOM_ID = 'MJ::JOB::upsample::1::0f3a2b1c-4d5e-6f70-8a9b-0c1d2e3f4a5b';// 假时钟 1000 → 36 进制 'rs':派发器铸的衍生卡位。diff --cc apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.tsindex d22c5eddd9,0000000000..b27e084fdfmode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts@@@ -1,98 -1,0 +1,99 @@@+import fs from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++/**+ * 源码契约测试:所有会改写插件世界(内容根/状态根/运行时)的 IPC 写路径,+ * handler 体内必须持 GhostMutationCoordinator 租约。+ *+ * 背景:GhostManager 与 ReceiptStore 的根路径都是调用时现解析的+ * (ownerScopedUserDataPath),账号切换边界只等待 coordinator+ * (bootstrap-electron 的 waitForGhostMutations)。写路径不持租约,异步窗口+ * (inspect/parse/hash)里切号落定,后半段写入就会漏进新 owner 的命名空间 ——+ * A 发起的安装落进 B、A 的内容目录配上 B 的 receipt。第 7 轮 review 实锤了+ * 本地 install/update/set-enabled 三条正是这么漏的(市场路径一直有租约)。+ *+ * index.ts 拉起整张 main 进程单例图,handler 无法脱离 electron 直测,所以用+ * 源码扫描钉契约:每个列出的 handler 块里必须出现 beginGhostMutation(取租约)+ * 与 captureGhostMutationOwner(入口同步捕获 owner,防"用切换后的 owner 取租约+ * 照样通过"——租约要核对的是发起时刻的 owner)。新增写路径 handler 时把名字加进+ * 清单;想移除租约必须先改掉 owner 动态解析这个前提。+ */++const MUTATING_GHOST_CHANNELS = [+ 'ghosts:install',+ 'ghosts:update',+ 'ghosts:set-enabled',++ 'ghosts:restore-builtin',+] as const;++function handlerBlock(source: string, channel: string): string {+ const start = source.indexOf(`ipcMain.handle('${channel}'`);+ expect(start, `handler for ${channel} not found`).toBeGreaterThan(-1);+ // handler 以两空格缩进的 `});` 收尾(仓库排版惯例);取到那里足够覆盖整个闭包。+ const end = source.indexOf('\n });', start);+ expect(end, `handler block for ${channel} has no terminator`).toBeGreaterThan(start);+ return source.slice(start, end);+}++describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {+ const source = fs.readFileSync(+ path.join(__dirname, '..', 'index.ts'),+ 'utf8',+ );++ for (const channel of MUTATING_GHOST_CHANNELS) {+ it(`${channel} 持租约且入口同步捕获 owner`, () => {+ const block = handlerBlock(source, channel);+ expect(block, `${channel} 缺 beginGhostMutation`).toContain('beginGhostMutation(');+ expect(block, `${channel} 缺 captureGhostMutationOwner`).toContain(+ 'captureGhostMutationOwner()',+ );+ });+ }++ it('ghosts:reapprove-installed 持租约,owner 以 inspect 时点的一次性票据为准(更强于 handler 内 capture)', () => {+ // 第 8 轮 P0-2:owner 在 confirm 入口才 capture 绑不住"读事实那一刻"——确认卡+ // 停留期间切号,A 看的确认可以给 B 的同 id 目录铸批准。现在 inspect 发一次性+ // 票据(钉 owner + id + manifestSha256),confirm 原子消费并以**票据里的 owner**+ // 起租约:generation 不等直接拒。handler 内不该再出现 captureGhostMutationOwner+ // (那会退化回"用确认时刻的 owner",正是要消掉的形态)。+ const block = handlerBlock(source, 'ghosts:reapprove-installed');+ expect(block).toContain('reapproveTickets.consume(');+ expect(block).toContain('beginGhostMutation(ticket.owner)');+ expect(block).not.toContain('captureGhostMutationOwner()');+ // inspect 侧必须在读事实之前捕获 owner 并发票。+ const inspectBlock = handlerBlock(source, 'ghosts:reapprove-inspect');+ expect(inspectBlock).toContain('captureGhostMutationOwner()');+ expect(inspectBlock).toContain('reapproveTickets.issue(');+ });++ it('ghosts:uninstall 经 uninstallGhostAndCleanup 持租约(入口同步取,无异步窗口故无需 capture)', () => {+ const block = handlerBlock(source, 'ghosts:uninstall');+ expect(block).toContain('uninstallGhostAndCleanup(');+ // main 的 per-ghost 屏障重构后,外层委托 withGhostInstallLock,实际清理与租约在+ // ...Locked 内(lock 内取租约,包住整段清理)。契约钉在真正干活的 Locked 函数上。+ const outerStart = source.indexOf('export async function uninstallGhostAndCleanup');+ expect(outerStart).toBeGreaterThan(-1);+ const outer = source.slice(outerStart, source.indexOf('\n}', outerStart));+ expect(outer).toContain('withGhostInstallLock(');+ const start = source.indexOf('async function uninstallGhostAndCleanupLocked');+ expect(start).toBeGreaterThan(-1);+ const fn = source.slice(start, source.indexOf('\n}', start));+ expect(fn).toContain('beginGhostMutation(');+ });++ it('市场装入/更新持租约(installOrUpdateMarketGhostPackage)', () => {+ // 同上:外层委托 withGhostInstallLock,owner 捕获 + 起租约在 ...Locked 内。+ const outerStart = source.indexOf('export async function installOrUpdateMarketGhostPackage');+ expect(outerStart).toBeGreaterThan(-1);+ const outer = source.slice(outerStart, source.indexOf('\n}', outerStart));+ expect(outer).toContain('withGhostInstallLock(');+ const start = source.indexOf('async function installOrUpdateMarketGhostPackageLocked');+ expect(start).toBeGreaterThan(-1);+ const block = source.slice(start, source.indexOf('\n}', start));+ expect(block).toContain('captureGhostMutationOwner()');+ expect(block).toContain('beginGhostMutation(');+ });+});diff --cc apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.tsindex 6859cb223d,6859cb223d..32c45f4796--- a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts@@@ -69,6 -69,6 +69,33 @@@ function makeGateway(overrides: Partialreturn { gw: new GhostSubscriptionGateway(deps), sent, running, deps };}++describe('subscriptionGateway owner boundary', () => {++ it('drops buffered events when the owner changes during wake', async () => {++ let releaseWake!: () => void;++ let ownerValid = true;++ const onInvalidated = vi.fn();++ const wake = vi.fn(() => new Promise<void>((resolve) => { releaseWake = resolve; }));++ const { gw, sent } = makeGateway({++ listGhosts: () => [ghost('a', { topics: ['activity'] })],++ wake,++ ownerScope: {++ capture: () => ({ ownerId: 'owner-a', generation: 1 }),++ isCurrent: () => ownerValid,++ isStable: () => ownerValid,++ onInvalidated,++ },++ });++++ gw.publish('activity', 'did-thinking-start', { sessionId: 's1', blockId: 'b1' });++ await vi.waitFor(() => expect(wake).toHaveBeenCalledOnce());++ ownerValid = false;++ releaseWake();++++ await vi.waitFor(() => expect(onInvalidated).toHaveBeenCalledWith('a'));++ expect(sent).toHaveLength(0);++ });++});++const TURN_DATA = { sessionId: 's1', agent: 'claude-code' };describe('did- 旁听扇出', () => {diff --cc apps/desktop/src/main/cindy-brain/cardActionDispatch.tsindex 1fb56a7cbc,1fb56a7cbc..f7c922d4f7--- a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts+++ b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts@@@ -25,6 -25,6 +25,7 @@@ importtype GhostPipeEventPush,type InstalledGhost,} from '../../shared/ghost.js';++import { isGhostOwnerScopeUsable, type GhostOwnerScope } from './ghostOwnerScope.js';export interface CardActionDispatchDeps {/** 内存卡片服务:in-flight + 宽限窗内的条目(归属 + 会话;命中最快)。 */@@@ -56,6 -56,6 +57,7 @@@* (老卡无会话归属)时不上报。*/onActivityStart?(key: string, sessionId: string): void;++ ownerScope?: GhostOwnerScope;now?(): number;log?: {info: (msg: string, meta?: Record<string, unknown>) => void;@@@ -102,8 -102,8 +104,28 @@@ export class GhostCardActionDispatcher// 归属:内存优先(快),持久兜底(settle/重启后仍成立)。查无 = 拒// (不区分"卡不存在"与"不属于任何在场意识",不给探测面)。// sessionId 一并取出:重建被清扫条目、登记衍生卡位都要续会话归属。++ let capturedOwner: unknown;++ if (this.deps.ownerScope) {++ try {++ capturedOwner = this.deps.ownerScope.capture();++ } catch {++ return { ok: false, reason: 'owner-boundary' };++ }++ if (!isGhostOwnerScopeUsable(this.deps.ownerScope, capturedOwner)) {++ return { ok: false, reason: 'owner-boundary' };++ }++ }++++ const ownerUsable = (): boolean =>++ isGhostOwnerScopeUsable(this.deps.ownerScope, capturedOwner);++ const rejectStaleOwner = (ghostId?: string): CardActionResult => {++ if (ghostId) this.deps.ownerScope?.onInvalidated?.(ghostId);++ return { ok: false, reason: 'owner-boundary' };++ };++let info = this.deps.resolveLiveInfo(callId);if (!info) info = await this.deps.resolvePersistedCard(callId);++ if (!ownerUsable()) return rejectStaleOwner(info?.ghostId);if (!info) {this.deps.log?.warn('card-action rejected: unknown card', { callId });return { ok: false, reason: 'unknown-card' };@@@ -134,8 -134,8 +156,13 @@@}try {-- if (!this.deps.isRunning(ghostId)) await this.deps.wake(ghost);++ if (!ownerUsable()) return rejectStaleOwner(ghostId);++ if (!this.deps.isRunning(ghostId)) {++ await this.deps.wake(ghost);++ if (!ownerUsable()) return rejectStaleOwner(ghostId);++ }const userActionToken = this.deps.issueUserActionToken?.(ghostId, sessionId) ?? null;++ if (!ownerUsable()) return rejectStaleOwner(ghostId);this.deps.sendToGhost(ghostId, {type: 'event',name: 'card-action',diff --cc apps/desktop/src/main/cindy-brain/ghostContentTree.tsindex cdb33f1c57,0000000000..c0db71bd7emode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts+++ b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts@@@ -1,470 -1,0 +1,473 @@@+import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';++/**+ * ghostContentTree —— 「插件内容目录怎么读」的**唯一判据**。+ *+ * 为什么存在这个模块:插件链路上有六处各自 readdir + 判类型的实现(技能指纹、+ * 技能快照拷贝、安装目录漂移指纹、随包种子指纹、种子复制、Forge 打包收集),+ * 还有五处各自 `path.join(dir, ...rel.split('/'))` 之后再判一次类型。它们本该+ * 是同一条判据,却分别用 Dirent 类型位 / `lstat` / `stat` / realpath 钳制写过,+ * 于是每一轮审查都能在其中一处找到没覆盖的角落 —— 补一处、下一轮换另一处。+ *+ * 所以类型判定与相对路径解析在本模块各只有一份实现,差异只允许以**显式策略+ * 参数**表达(点开头条目算不算内容、非普通条目是拒还是只记状态位)。新增读插件+ * 内容的代码一律从这里取判据,不要再就地 readdir + isDirectory()。+ */++/**+ * 目录条目类型。`link` 与 `other` 都属于"非普通条目",单独区分只为错误信息+ * 能说清是链接还是别的(FIFO / 设备节点等)。+ */+export type GhostDirEntryKind = 'file' | 'directory' | 'link' | 'other';++/**+ * 类型判据的唯一实现:一律看 `lstat`,**不信 Dirent 的类型位**。+ *+ * Dirent 的类型位来自 readdir 的批量结果,当前 libuv 把 reparse point(软链与+ * Windows junction)都报成 link,但那是实现细节、Node 公开契约没保证;判据自己+ * 拿 lstat 说话,哪天类型位把 junction 报成 directory 也不会跟进去。+ */+function kindOfStat(stat: fs.Stats): GhostDirEntryKind {+ if (stat.isSymbolicLink()) return 'link';+ if (stat.isDirectory()) return 'directory';+ if (stat.isFile()) return 'file';+ return 'other';+}++export async function classifyGhostDirEntry(absPath: string): Promise<GhostDirEntryKind> {+ return kindOfStat(await fs.promises.lstat(absPath));+}++export function classifyGhostDirEntrySync(absPath: string): GhostDirEntryKind {+ return kindOfStat(fs.lstatSync(absPath));+}++/** 普通条目 = 真目录或普通文件;其余(链接等)一律非普通。 */+export function isRegularGhostDirEntry(kind: GhostDirEntryKind): boolean {+ return kind === 'file' || kind === 'directory';+}++export interface ResolveGhostContentPathOptions {+ /** 最终段期望的类型。 */+ expect: 'directory' | 'file';+ /** 错误信息前缀(如 `approved skill` / `bundled locale`)。 */+ label: string;+}++/**+ * 解析清单声明的相对路径,**逐段**确认每一段都是真目录 / 最终段是期望类型。+ *+ * 只 lstat 最终段是不够的:中间段被换成软链 / Windows junction 时 OS 会静默穿透+ * —— 对最终段 lstat 报的是"真目录、非链接"(已实测),于是字节从插件目录之外取。+ * 首次批准那条路径尤其致命:技能指纹是现算的,外部内容会被钉成"批准字节"再复制+ * 成快照,而 `checkSkillMdConsistency` 只校验 frontmatter 的 name/description,+ * 这两个值在 manifest 里公开可抄,拦不住。+ *+ * `baseDir` 自身不在这里校验(它由调用方给出:安装根下的 `<id>` 若被换成链接,+ * `GhostManager.list()` 的 `entry.isDirectory()` 已经把它整条跳过;状态根下的+ * temp / 快照目录是宿主自己创建的)。相对路径的结构安全由清单校验保证+ * (`isSafeGhostRelativePath` / skill dir 正则:无盘符、无反斜杠、无 `.`/`..` 段)。+ */+export async function resolveGhostContentPath(+ baseDir: string,+ relPath: string,+ options: ResolveGhostContentPathOptions,+): Promise<string> {+ const segments = relPath.split('/').filter((segment) => segment.length > 0);+ let current = baseDir;+ for (const [index, segment] of segments.entries()) {+ current = path.join(current, segment);+ assertSegment(+ await classifyGhostDirEntry(current),+ index === segments.length - 1 ? options.expect : 'directory',+ relPath,+ options.label,+ );+ }+ return current;+}++export function resolveGhostContentPathSync(+ baseDir: string,+ relPath: string,+ options: ResolveGhostContentPathOptions,+): string {+ const segments = relPath.split('/').filter((segment) => segment.length > 0);+ let current = baseDir;+ for (const [index, segment] of segments.entries()) {+ current = path.join(current, segment);+ assertSegment(+ classifyGhostDirEntrySync(current),+ index === segments.length - 1 ? options.expect : 'directory',+ relPath,+ options.label,+ );+ }+ return current;+}++function assertSegment(+ kind: GhostDirEntryKind,+ expect: 'directory' | 'file',+ relPath: string,+ label: string,+): void {+ if (kind === 'link') {+ throw new Error(`${label} path segment is a link: ${relPath}`);+ }+ if (kind !== expect) {+ throw new Error(+ `${label} path segment is not a ${expect === 'directory' ? 'directory' : 'regular file'}: ${relPath}`,+ );+ }+}++export interface CollectGhostContentOptions {+ /**+ * 点开头条目:`include` = 算内容(技能目录 —— 技能指令可以引用目录里的任意+ * 文件,漏掉一类就是漏掉一条改写通道);`skip` = 不算内容(安装目录 / 随包种子+ * —— `.disabled`、`.cindy-trust.json` 是用户与宿主状态,不是插件内容)。+ *+ * `skip` 下点开头条目仍然**要过类型判定**:名为 `.x` 的链接不进内容指纹,但+ * 会按 `nonRegular` 策略处理。点开头**目录**整条跳过(不递归、不进指纹):清单+ * 声明的相对路径首字符必须是 `[a-zA-Z0-9_]`,任何声明都不可能指向点开头目录里+ * 的文件,所以它们既不会被当代码加载、也不会被当技能读取。+ */+ dotEntries: 'include' | 'skip';+ /**+ * 非普通条目(链接 / FIFO 等):`throw` = 立即拒(授权判据路径);`flag` = 只翻+ * `hasNonRegularEntry`,不进内容指纹(对账判据路径 —— 需要"判不一致"而不是抛错,+ * 才能走重新播种把目录换回随包字节)。+ *+ * `flag` 下**不能拿 sentinel 喂进哈希**:任何 sentinel 都能被"同路径下内容恰好+ * 等于该 sentinel 的普通文件"撞上(已实测:内容为 `non-regular` 的普通文件与同名+ * junction 的摘要完全相等),于是被塞进链接的目录仍会被判成逐字节相同。所以类型+ * 状态是独立字段,不掺进字节流。+ */+ nonRegular: 'throw' | 'flag';+ /** 错误信息前缀。 */+ label: string;+}++export interface GhostContentTree {+ /** 普通文件的相对路径(正斜杠归一化保证双平台一致),已排序。 */+ files: string[];+ /** 是否遇到过非普通条目(仅 `nonRegular: 'flag'` 时可能为 true)。 */+ hasNonRegularEntry: boolean;+ /** 收集开始时钉住的规范根身份,供后续流式哈希拒绝 collect→hash 间的根替换。 */+ rootIdentity: GhostContentRootIdentity;+}++export interface GhostContentRootIdentity {+ realPath: string;+ dev: bigint;+ ino: bigint;+ mtimeNs: bigint;+ ctimeNs: bigint;+}++interface GhostContentAncestorIdentity {+ relativePath: string;+ dev: bigint;+ ino: bigint;+ mtimeNs: bigint;+ ctimeNs: bigint;+}++function sameFileIdentity(+ a: Pick<fs.BigIntStats, 'dev' | 'ino'>,+ b: Pick<fs.BigIntStats, 'dev' | 'ino'>,+): boolean {+ if (a.dev === 0n || a.ino === 0n || b.dev === 0n || b.ino === 0n) return false;+ return a.dev === b.dev && a.ino === b.ino;+}++function sameStableFileState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {+ return after.isFile() &&+ sameFileIdentity(before, after) &&+ before.size === after.size &&+ before.mtimeNs === after.mtimeNs &&+ before.ctimeNs === after.ctimeNs;+}++function sameStableDirectoryState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {+ // Filesystems may immediately reuse a deleted directory's inode. Timestamps+ // keep that replacement distinct and also expose namespace changes below it.+ return after.isDirectory() &&+ sameFileIdentity(before, after) &&+ before.mtimeNs === after.mtimeNs &&+ before.ctimeNs === after.ctimeNs;+}++async function captureGhostContentRootIdentity(rootDir: string): Promise<GhostContentRootIdentity> {+ const realPath = await fs.promises.realpath(rootDir);+ const [pathStat, realStat] = await Promise.all([+ fs.promises.stat(rootDir, { bigint: true }),+ fs.promises.stat(realPath, { bigint: true }),+ ]);+ if (!pathStat.isDirectory() || !sameStableDirectoryState(pathStat, realStat)) {+ throw new Error(`ghost content root is not a stable directory: ${rootDir}`);+ }+ return {+ realPath,+ dev: realStat.dev,+ ino: realStat.ino,+ mtimeNs: realStat.mtimeNs,+ ctimeNs: realStat.ctimeNs,+ };+}++async function assertGhostContentRootIdentity(+ rootDir: string,+ expected: GhostContentRootIdentity,+): Promise<void> {+ const current = await captureGhostContentRootIdentity(rootDir);+ if (+ current.realPath !== expected.realPath ||+ current.dev !== expected.dev ||+ current.ino !== expected.ino ||+ current.mtimeNs !== expected.mtimeNs ||+ current.ctimeNs !== expected.ctimeNs+ ) {+ throw new Error(`ghost content root changed while reading: ${rootDir}`);+ }+}++async function captureGhostContentAncestorIdentities(+ rootRealPath: string,+ relativePath: string,+): Promise<GhostContentAncestorIdentity[]> {+ const identities: GhostContentAncestorIdentity[] = [];+ const segments = relativePath.split('/').slice(0, -1);+ let absolutePath = rootRealPath;+ let currentRelativePath = '';+ for (const segment of segments) {+ absolutePath = path.join(absolutePath, segment);+ currentRelativePath = currentRelativePath ? `${currentRelativePath}/${segment}` : segment;+ const stat = await fs.promises.lstat(absolutePath, { bigint: true });+ if (stat.isSymbolicLink() || !stat.isDirectory()) {+ throw new Error(`ghost content ancestor changed into a link: ${currentRelativePath}`);+ }+ identities.push({+ relativePath: currentRelativePath,+ dev: stat.dev,+ ino: stat.ino,+ mtimeNs: stat.mtimeNs,+ ctimeNs: stat.ctimeNs,+ });+ }+ return identities;+}++function assertGhostContentAncestorIdentities(+ expected: readonly GhostContentAncestorIdentity[],+ current: readonly GhostContentAncestorIdentity[],+): void {+ if (+ current.length !== expected.length ||+ current.some(+ (identity, index) =>+ identity.relativePath !== expected[index]?.relativePath ||+ identity.dev !== expected[index]?.dev ||+ identity.ino !== expected[index]?.ino ||+ identity.mtimeNs !== expected[index]?.mtimeNs ||+ identity.ctimeNs !== expected[index]?.ctimeNs,+ )+ ) {+ throw new Error('ghost content ancestor changed while reading');+ }+}++/** 递归收集目录里的普通文件相对路径;类型判定与策略见 `CollectGhostContentOptions`。 */+export async function collectGhostContentFiles(+ rootDir: string,+ options: CollectGhostContentOptions,+): Promise<GhostContentTree> {+ const rootIdentity = await captureGhostContentRootIdentity(rootDir);+ const files: string[] = [];+ let hasNonRegularEntry = false;++ const collect = async (relativeDir: string): Promise<void> => {+ const absoluteDir = path.join(rootIdentity.realPath, ...relativeDir.split('/').filter(Boolean));+ for (const entry of await fs.promises.readdir(absoluteDir, { withFileTypes: true })) {+ const isDotEntry = entry.name.startsWith('.');+ const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;+ const kind = await classifyGhostDirEntry(path.join(absoluteDir, entry.name));+ if (!isRegularGhostDirEntry(kind)) {+ // 类型判定排在点开头过滤**之前**:名为 `.x` 的链接同样是一条改写通道,+ // 不能因为"点开头不算内容"就连它是不是链接都不看。+ if (options.nonRegular === 'throw') {+ throw new Error(+ `${options.label} rejects ${kind === 'link' ? 'link' : 'non-regular'} entry: ${relativePath}`,+ );+ }+ hasNonRegularEntry = true;+ continue;+ }+ if (isDotEntry && options.dotEntries === 'skip') continue;+ if (kind === 'directory') {+ await collect(relativePath);+ } else {+ files.push(relativePath);+ }+ }+ };++ await collect('');+ await assertGhostContentRootIdentity(rootDir, rootIdentity);+ files.sort();+ return { files, hasNonRegularEntry, rootIdentity };+}++/**+ * 内容指纹:版本前缀 + 长度前缀路径 + 每文件 SHA-256。+ *+ * 不使用 `path \0 bytes \0` 这类分隔符编码:文件内容可以合法包含 NUL,于是+ * `{ a: "x\0b\0y" }` 与 `{ a: "x", b: "y" }` 会在进入 SHA-256 前形成完全+ * 相同的字节流。路径使用 UTF-8 字节长度前缀,文件内容先流式收成固定 32 字节摘要,+ * 因此文件边界无歧义。+ *+ * 文件仍然流式读取,不整份进内存 —— 插件目录里除 SKILL.md 之外的文件没有尺寸+ * 上限,整份 readFile 会让一个塞进来的超大文件把 Host 撑爆。+ */+/**+ * `hashGhostContentFiles` 的内存版:对"路径 + 字节"的内存投影算同一 framing 的+ * 指纹(逐字节等价,有回归钉住)。用途:装入/更新时从 **.cindy 包本体**(不可变的+ * JSZip 投影)算批准基线,而不是从已公开的可变安装目录首读 —— 后者在 publish 与+ * 首次 hash 之间被换过的字节会自洽地成为批准事实(权威判据被污染源初始化)。+ */+export function hashGhostContentBuffers(files: readonly { path: string; bytes: Buffer }[]): string {+ const hash = crypto.createHash('sha256');+ hash.update('cindy-ghost-content-v2\0');+ const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ for (const file of sorted) {+ const pathBytes = Buffer.from(file.path, 'utf8');+ const pathLength = Buffer.allocUnsafe(8);+ pathLength.writeBigUInt64BE(BigInt(pathBytes.byteLength));+ hash.update(pathLength);+ hash.update(pathBytes);+ hash.update(crypto.createHash('sha256').update(file.bytes).digest());+ }+ return hash.digest('hex');+}++export async function hashGhostContentFiles(+ rootDir: string,+ files: readonly string[],+ collectedRootIdentity?: GhostContentRootIdentity,+): Promise<string> {+ const rootIdentity = collectedRootIdentity ?? (await captureGhostContentRootIdentity(rootDir));+ await assertGhostContentRootIdentity(rootDir, rootIdentity);+ const hash = crypto.createHash('sha256');+ hash.update('cindy-ghost-content-v2\0');+ for (const relativePath of files) {+ await assertGhostContentRootIdentity(rootDir, rootIdentity);+ const pathBytes = Buffer.from(relativePath, 'utf8');+ const pathLength = Buffer.allocUnsafe(8);+ pathLength.writeBigUInt64BE(BigInt(pathBytes.byteLength));+ hash.update(pathLength);+ hash.update(pathBytes);++ const fileHash = crypto.createHash('sha256');+ const filePath = path.join(rootIdentity.realPath, ...relativePath.split('/'));+ const ancestorIdentities = await captureGhostContentAncestorIdentities(+ rootIdentity.realPath,+ relativePath,+ );+ const noFollow = fs.constants.O_NOFOLLOW ?? null;- const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | (noFollow ?? 0));++ const handle = await fs.promises.open(++ filePath,++ fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0) | (noFollow ?? 0),++ );+ let handleStat: fs.BigIntStats;+ let initialRealFilePath: string | undefined;+ try {+ handleStat = await handle.stat({ bigint: true });+ if (!handleStat.isFile()) {+ throw new Error(`ghost content entry is not a regular file: ${relativePath}`);+ }+ assertGhostContentAncestorIdentities(+ ancestorIdentities,+ await captureGhostContentAncestorIdentities(rootIdentity.realPath, relativePath),+ );+ if (noFollow === null) {+ const linkStat = await fs.promises.lstat(filePath, { bigint: true });+ if (linkStat.isSymbolicLink() || !sameFileIdentity(linkStat, handleStat)) {+ throw new Error(`ghost content entry changed into a link: ${relativePath}`);+ }+ }+ const [pathStat, realFilePath] = await Promise.all([+ fs.promises.stat(filePath, { bigint: true }),+ fs.promises.realpath(filePath),+ ]);+ initialRealFilePath = realFilePath;+ const relativeRealPath = path.relative(rootIdentity.realPath, realFilePath);+ const outsideRoot =+ relativeRealPath === '..' ||+ relativeRealPath.startsWith(`..${path.sep}`) ||+ path.isAbsolute(relativeRealPath);+ if (!sameFileIdentity(pathStat, handleStat) || outsideRoot) {+ throw new Error(`ghost content entry escaped its root: ${relativePath}`);+ }++ const stream = handle.createReadStream({ autoClose: false });+ for await (const chunk of stream) fileHash.update(chunk as Buffer);+ const afterReadStat = await handle.stat({ bigint: true });+ if (!sameStableFileState(handleStat, afterReadStat)) {+ throw new Error(`ghost content entry changed while reading: ${relativePath}`);+ }+ } finally {+ await handle.close();+ }+ const fileDigest = fileHash.digest();+ // Windows 的按路径 stat/lstat 在 rename/replace 后可能继续返回旧目录元数据。+ // 重新打开同一路径,并再次流式摘要;新句柄的 stat 也可能陈旧,字节对账才是最终证据。+ const verificationHandle = await fs.promises.open(+ filePath,- fs.constants.O_RDONLY | (noFollow ?? 0),++ fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0) | (noFollow ?? 0),+ );+ try {+ const verificationStat = await verificationHandle.stat({ bigint: true });+ if (!sameStableFileState(handleStat, verificationStat)) {+ throw new Error(`ghost content entry changed while reading: ${relativePath}`);+ }+ const verificationFileHash = crypto.createHash('sha256');+ const verificationStream = verificationHandle.createReadStream({ autoClose: false });+ for await (const chunk of verificationStream) verificationFileHash.update(chunk as Buffer);+ const afterVerificationReadStat = await verificationHandle.stat({ bigint: true });+ if (!sameStableFileState(verificationStat, afterVerificationReadStat)) {+ throw new Error(`ghost content entry changed while reading: ${relativePath}`);+ }+ if (!crypto.timingSafeEqual(fileDigest, verificationFileHash.digest())) {+ throw new Error(`ghost content entry changed while reading: ${relativePath}`);+ }+ const [afterReadPathStat, afterReadRealFilePath] = await Promise.all([+ fs.promises.lstat(filePath, { bigint: true }),+ fs.promises.realpath(filePath),+ ]);+ if (+ initialRealFilePath === undefined ||+ afterReadPathStat.isSymbolicLink() ||+ !afterReadPathStat.isFile() ||+ !sameFileIdentity(afterReadPathStat, afterVerificationReadStat) ||+ afterReadRealFilePath !== initialRealFilePath+ ) {+ throw new Error(`ghost content entry path changed while reading: ${relativePath}`);+ }+ if (!sameStableFileState(afterVerificationReadStat, afterReadPathStat)) {+ throw new Error(`ghost content entry changed while reading: ${relativePath}`);+ }+ assertGhostContentAncestorIdentities(+ ancestorIdentities,+ await captureGhostContentAncestorIdentities(rootIdentity.realPath, relativePath),+ );+ } finally {+ await verificationHandle.close();+ }+ hash.update(fileDigest);+ }+ await assertGhostContentRootIdentity(rootDir, rootIdentity);+ return hash.digest('hex');+}diff --cc apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 0be8230a63,0000000000..64408e0796mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@@ -1,1156 -1,0 +1,1157 @@@+import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';++import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';++import {+ GHOST_LOCALE_MAX_BYTES,+ GHOST_SKILL_MD_MAX_BYTES,+ isValidGhostId,+ validateGhostManifest,+ validateGhostManifestLocaleResource,+ type GhostManifest,+ type GhostManifestLocaleResource,+ type GhostTrustInfo,+} from '../../shared/ghost.js';+import {+ classifyGhostDirEntry,+ classifyGhostDirEntrySync,+ collectGhostContentFiles,+ hashGhostContentFiles,+ isRegularGhostDirEntry,+ resolveGhostContentPath,+} from './ghostContentTree.js';+import { isPathInsideDir } from './dirDeposit.js';+import { checkSkillMdConsistency } from './skillSlot.js';++// v2 pairs receipts with the unambiguous ghostContentTree framing. Keeping v1+// readable would let an old ambiguous digest authorize a snapshot under the+// new verifier, so old receipts intentionally fail closed and require approval+// to be written again.+const RECEIPT_SCHEMA_VERSION = 2;+const MAX_RECEIPT_BYTES = 2 * 1024 * 1024;+const MAX_PENDING_MUTATION_BYTES = 64 * 1024;+const MAX_ICON_DATA_URL_BYTES = 768 * 1024;+/**+ * 受管 icon 快照的完整形态:声明的图片 mime + 严格 base64 载荷。载荷字符集也要+ * 校验 —— 只认前缀会让被改写的 receipt 把任意字符串塞进 renderer 的 img src。+ */+const ICON_DATA_URL_RE = /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/;++/**+ * 一次明确批准的插件安装事实;只允许 Host 写入安装目录之外的状态根。+ *+ * receipt 钉住的是**授权事实**(批准过的 manifest / trust / 启停 / revision)。+ * 它不保证安装目录里的内容字节此后一直没被改过 —— 逻辑页代码仍从可变的安装+ * 目录加载,只有技能目录因为越出沙箱而被拷成快照。+ */+export interface GhostInstallReceipt {+ schemaVersion: typeof RECEIPT_SCHEMA_VERSION;+ id: string;+ revision: string;+ manifest: GhostManifest;+ localeResources: Record<string, GhostManifestLocaleResource>;+ enabled: boolean;+ trust: GhostTrustInfo;+ /**+ * 批准时点的来源指纹,仅供审计与人工比对:市场/本地包是 `.cindy` 文件哈希,+ * 随包种子是内容目录哈希。**运行时不校验它**,不要据此认为安装内容持续完整。+ */+ packageSha256?: string;+ /**+ * 按 skill item 目录钉住的批准字节指纹(`item.dir` → sha256)。声明了 skill 槽+ * 时逐项必填,没声明时是空对象。+ *+ * 这一项**是运行期判据**,与只作审计用的 `packageSha256` 不同:快照缺失需要从+ * 可变安装目录重建时,必须先重算并逐字节对上才允许重建。少了它,改写 SKILL.md+ * 正文或往技能目录塞辅助文件就能在一次"启用"里被固化成已批准快照并全局挂链,+ * 而 frontmatter 一致性校验只看 name/description,拦不住这类漂移。+ */+ skillContentSha256: Record<string, string>;+ iconDataUrl?: string;+}++export type GhostInstallReceiptReadResult =+ | { state: 'approved'; receipt: GhostInstallReceipt }+ | { state: 'legacy-unapproved' }+ | { state: 'invalid'; reason: string };++export type GhostInstallReceiptRecoveryReadResult =+ | { state: 'approved'; receipt: GhostInstallReceipt }+ | { state: 'missing' }+ | { state: 'invalid'; reason: string }+ | { state: 'unreadable'; reason: string };++/**+ * 一次性 legacy 迁移的落地台账。存在即表示"本机已跑过一轮从旧安装布局 backfill+ * receipt 的迁移"——此后任何缺失 receipt 都按删除/损坏 fail closed,不再触发迁移。+ *+ * 它是迁移的**全局一次性门**(见 `GhostManager.migrateLegacyApprovalsOnce`):没有+ * 这道门,删掉某个 receipt 就能骗一次"从当前可变安装目录重建授权",而安装目录可被+ * 同权限进程改写。ledger 门是充分守卫——能删 ledger 的进程本就能直接往状态根写一份+ * 结构合法的伪造 receipt(§7 已登记"状态根无写保护"缺口),迁移路径严格弱于它。+ */+export interface GhostLegacyMigrationLedger {+ version: 1;+ /** 迁移完成时刻(ISO)。仅审计,不参与判定。 */+ migratedAt: string;+ /** 实际 backfill 出 receipt 的 id 清单,便于事后分辨"用户确认过"与"迁移来的"。 */+ migratedIds: string[];+ /**+ * 迁移读不出核心事实而 fail closed 的 id(坏 manifest / 技能目录含链接等)。+ * 记进台账供支持排查与 UI 提示;这些 id 走每插件的重新确认恢复入口。+ */+ failedIds?: string[];+ /**+ * 迁移状态机,缺省按 `completed` 读(与旧台账兼容)。+ *+ * `in-progress` 在**首个 backfill 动笔之前**原子落盘,记下本轮要迁的完整 id 清单+ * (`pendingIds`)。这是崩溃安全的关键:迁移中途崩溃/断电时,receipt 首写自动落+ * 台账的守卫(见 `write`)不会把门焊死 —— 下次启动看到 `in-progress` 就按+ * `pendingIds` 续跑,已写出 receipt 的 id 自然跳过,全部处理完才原子改写成+ * `completed`。清单钉死在动笔前,续跑**只认清单内的 id**:迁移窗口期间新装再删+ * receipt 的 id 不在清单里,骗不到续跑重铸。+ */+ state?: 'in-progress' | 'completed';+ /** 仅 `in-progress`:本轮待迁 id 全集(动笔前钉死)。 */+ pendingIds?: string[];+}++/**+ * 装入/更新事务的提交日志(状态根内,崩溃后仍在)。用来消除「目录已 rename、receipt+ * 还没写」这段崩溃窗口:+ * - install:崩溃留下"有 finalDir、无 receipt、无 ledger"的目录,与 legacy 安装无法+ * 区分 —— 全新 owner 首个安装崩在这里,下轮迁移会把它(含崩溃窗口内被同权限进程+ * 改写的 manifest)当存量批准掉,用户确认的是 A、被授权的是 B。+ * - update:`final→backup`、`staging→final`、写 receipt 三步;第二三步之间崩溃留下+ * "新字节 + 旧 receipt",恢复器旧逻辑(final 在位就删 backup)会把它固化成"按旧批准+ * 跑新代码"。+ *+ * 新 marker 用 `receiptRevision` 作为本次事务的提交 nonce,避免更新前后包 hash 相同+ * 时把旧 receipt 误认成本次提交。`packageSha256` 与 phase 只用于兼容旧 marker;无法+ * 区分新旧 receipt 时必须走保守恢复方向,不得删除唯一 backup。+ */+export type GhostPendingMutation =+ | {+ 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. */+ oldPackageSha256?: string;+ }+ // uninstall 不带 packageSha256:它的提交信号不是"receipt 写到某版本",而是"receipt ++ // 内容目录都已移除"。恢复见到它就把两者删干净(顺序无关,幂等)。+ | { kind: 'uninstall'; builtinTombstone?: boolean };++export type GhostPendingMutationReadResult =+ | { state: 'valid'; mutation: GhostPendingMutation }+ | { state: 'missing' }+ | { state: 'invalid'; reason: string }+ | { state: 'unreadable'; reason: string };++export type GhostPendingMutationListResult =+ { state: 'ok'; ids: string[]; blocked: boolean } | { state: 'unreadable'; reason: string };++/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */+export class GhostInstallReceiptStore {+ constructor(private readonly getRootDir: () => string) {}++ rootDir(): string {+ return path.resolve(this.getRootDir());+ }++ read(id: string): GhostInstallReceiptReadResult {+ const result = this.readForRecovery(id);+ if (result.state === 'approved') return result;+ if (result.state === 'missing') return { state: 'legacy-unapproved' };+ return { state: 'invalid', reason: result.reason };+ }++ /** Recovery must not confuse transient state-root IO with missing/corrupt approval state. */+ readForRecovery(id: string): GhostInstallReceiptRecoveryReadResult {+ const receiptPath = this.receiptPath(id);- let stat: fs.Stats;++ let bytes: Buffer | null;+ try {- stat = fs.lstatSync(receiptPath);++ bytes = readBoundedFileNoFollowSync(receiptPath, MAX_RECEIPT_BYTES, {++ containWithin: this.rootDir(),++ });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return { state: 'missing' };+ }+ return {+ state: 'unreadable',+ reason: error instanceof Error ? error.message : String(error),+ };+ }- if (!stat.isFile() || stat.size > MAX_RECEIPT_BYTES) {++ if (!bytes) {+ return { state: 'invalid', reason: 'receipt 不是普通文件或超过大小上限' };+ }- let text: string;- try {- text = fs.readFileSync(receiptPath, 'utf8');- } catch (error) {- return {- state: 'unreadable',- reason: error instanceof Error ? error.message : String(error),- };- }++ const text = bytes.toString('utf8');+ let parsed: unknown;+ try {+ parsed = JSON.parse(text) as unknown;+ } catch (error) {+ return { state: 'invalid', reason: error instanceof Error ? error.message : String(error) };+ }+ const validated = validateReceipt(parsed, id);+ return validated.ok+ ? { state: 'approved', receipt: validated.receipt }+ : { state: 'invalid', reason: validated.reason };+ }++ /**+ * 写入批准事实。`skillSourceDir` 是快照缺失时的取字节来源:装入/更新传新+ * 内容目录,纯状态改写(启停)传当前安装目录即可自愈。+ *+ * `requireSkillSnapshot: false` 用于**必须成功的收敛方向**(停用):快照+ * 已被外部删掉时不该把插件卡在"既不能用也不能关"的状态,此时按无 skill+ * 落链继续写批准事实,由对账撤掉链接。+ */+ async write(+ receipt: GhostInstallReceipt,+ options: { skillSourceDir?: string; requireSkillSnapshot?: boolean } = {},+ ): Promise<void> {+ const validated = validateReceipt(receipt, receipt.id);+ if (!validated.ok)+ throw new Error(`refusing to write invalid ghost receipt: ${validated.reason}`);++ const root = this.rootDir();+ await fs.promises.mkdir(root, { recursive: true });+ try {+ await this.ensureSkillSnapshot(receipt, options.skillSourceDir);+ } catch (error) {+ if (options.requireSkillSnapshot !== false) throw error;+ }+ // Migration ledger 是 receipt 对外生效的前置提交记录。正常装入/更新若先写+ // receipt、后 best-effort 落 ledger,会自然制造“有效 receipt + 无 ledger”的+ // mixed 状态;下一版既不能安全判断其它无 receipt 目录是 legacy 还是被删批准。+ // legacy migration/recovery 已在首个 backfill 前写好 in-progress,因此这里仅在+ // **完全没有** ledger 时先写 completed,且失败必须阻断 receipt 提交。+ if (!this.hasMigrationLedger()) {+ await this.writeMigrationLedger({+ version: 1,+ migratedAt: new Date().toISOString(),+ migratedIds: [],+ state: 'completed',+ });+ }+ const target = this.receiptPath(receipt.id);+ const temp = path.join(+ root,+ `.${receipt.id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.writeFile(temp, `${JSON.stringify(receipt, null, 2)}\n`, {+ encoding: 'utf8',+ flag: 'wx',+ mode: 0o600,+ });+ await fs.promises.rename(temp, target);+ } finally {+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);+ }+ await this.pruneStaleSkillSnapshots(receipt);+ }++ async remove(id: string): Promise<void> {+ const receiptPath = this.receiptPath(id);+ const receiptKind = await classifyCleanupEntry(receiptPath);+ if (receiptKind === 'missing') {+ // ENOENT is already-clean and must remain idempotent.+ } else if (receiptKind !== 'file') {+ throw new Error(`ghost receipt path is not a regular file: ${receiptPath}`);+ } else {+ await fs.promises.rm(receiptPath, { force: true });+ }+ // Validate both managed snapshot path segments before recursive deletion.+ // Missing segments mean cleanup is already complete; links, non-directories,+ // and transient IO failures remain observable so the caller keeps its journal.+ const snapshotPath = await this.assertManagedSnapshotParent(id, { createMissing: false });+ if (!snapshotPath) return;+ await fs.promises.rm(snapshotPath, {+ recursive: true,+ force: true,+ });+ }++ /** `remove` 的同步版:启动恢复(构造期同步)收尾未完成卸载用,判据同 `remove`。 */+ removeSync(id: string): void {+ const receiptPath = this.receiptPath(id);+ const receiptKind = classifyCleanupEntrySync(receiptPath);+ if (receiptKind === 'missing') {+ // ENOENT is already-clean and must remain idempotent.+ } else if (receiptKind !== 'file') {+ throw new Error(`ghost receipt path is not a regular file: ${receiptPath}`);+ } else {+ fs.rmSync(receiptPath, { force: true });+ }+ const snapshotPath = this.assertManagedSnapshotParentSync(id, { createMissing: false });+ if (!snapshotPath) return;+ fs.rmSync(snapshotPath, { recursive: true, force: true });+ }++ skillSnapshotRoot(id: string, revision: string): string {+ if (!isValidGhostId(id) || !isRevision(revision)) {+ throw new Error('invalid ghost skill snapshot identity');+ }+ return path.join(this.rootDir(), 'skill-snapshots', id, revision);+ }++ /**+ * 快照父路径(`<状态根>/skill-snapshots/<id>`)的逐段遏制断言。+ *+ * 任何 readdir / mkdir / rename / rm 之前都必须过这道:父段被同权限进程换成+ * junction/链接时,这些操作会**穿透**到状态根之外 —— 把 §7 登记的「状态根可写→+ * 可伪造批准」升级成「任意外部目录删除/写入」,是一次真实的权限升级(已在+ * Windows 上实测复现)。判据与 ghostContentTree 同源:逐段 lstat、链接一律拒,+ * 最后再 realpath 对账"物理路径仍在状态根内"(状态根自身的祖先允许是链接 ——+ * relocated home 场景,所以以 realpath(root) 为基准而不是词法路径)。+ *+ * `createMissing`:装入/更新路径按需补建缺失段;prune/remove 等回收路径不建,+ * 段缺失(ENOENT)返回 null 表示"没有可回收对象"。段存在但不是真目录一律抛错,+ * 由调用方决定 fail closed 还是跳过 —— 绝不带着可疑父段继续动盘。+ */+ private async assertManagedSnapshotParent(+ id: string,+ opts: { createMissing: boolean },+ ): Promise<string | null> {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for snapshot path');+ const root = this.rootDir();+ let current = root;+ for (const segment of ['skill-snapshots', id]) {+ current = path.join(current, segment);+ let kind: Awaited<ReturnType<typeof classifyGhostDirEntry>> | null;+ try {+ kind = await classifyGhostDirEntry(current);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ kind = null;+ }+ if (kind === null) {+ if (!opts.createMissing) return null;+ // 非 recursive:上一段刚验证过是真目录,逐段建才不会静默沿着链接铺路。+ await fs.promises.mkdir(current);+ continue;+ }+ if (kind !== 'directory') {+ throw new Error(+ `skill snapshot path segment is not a real directory: ${segment} (${kind})`,+ );+ }+ }+ const [realRoot, realParent] = await Promise.all([+ fs.promises.realpath(root),+ fs.promises.realpath(current),+ ]);+ if (!isPathInsideDir(realRoot, realParent)) {+ throw new Error('skill snapshot parent escaped the approval state root');+ }+ return current;+ }++ private assertManagedSnapshotParentSync(+ id: string,+ opts: { createMissing: boolean },+ ): string | null {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for snapshot path');+ const root = this.rootDir();+ let current = root;+ for (const segment of ['skill-snapshots', id]) {+ current = path.join(current, segment);+ let kind: ReturnType<typeof classifyGhostDirEntrySync> | null;+ try {+ kind = classifyGhostDirEntrySync(current);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ kind = null;+ }+ if (kind === null) {+ if (!opts.createMissing) return null;+ fs.mkdirSync(current);+ continue;+ }+ if (kind !== 'directory') {+ throw new Error(+ `skill snapshot path segment is not a real directory: ${segment} (${kind})`,+ );+ }+ }+ const realRoot = fs.realpathSync(root);+ const realParent = fs.realpathSync(current);+ if (!isPathInsideDir(realRoot, realParent)) {+ throw new Error('skill snapshot parent escaped the approval state root');+ }+ return current;+ }++ /** 迁移台账路径。点开头,不会与任何合法 ghost id 的 `<id>.json` receipt 撞名。 */+ private migrationLedgerPath(): string {+ return path.join(this.rootDir(), '.legacy-migration.json');+ }++ /** 读迁移台账(缺失/损坏返回 null;追加 id 时用,判定门只看 hasMigrationLedger)。 */+ readMigrationLedger(): GhostLegacyMigrationLedger | null {+ try {+ const raw = JSON.parse(+ fs.readFileSync(this.migrationLedgerPath(), 'utf8'),+ ) as GhostLegacyMigrationLedger;+ if (+ !raw ||+ raw.version !== 1 ||+ typeof raw.migratedAt !== 'string' ||+ !isValidUniqueGhostIdArray(raw.migratedIds)+ ) {+ return null;+ }+ if (raw.state !== undefined && raw.state !== 'in-progress' && raw.state !== 'completed') {+ return null;+ }+ if (raw.failedIds !== undefined && !isValidUniqueGhostIdArray(raw.failedIds)) return null;+ if (+ raw.state === 'in-progress' &&+ (!isValidUniqueGhostIdArray(raw.pendingIds) || raw.pendingIds.length === 0)+ ) {+ return null;+ }+ if (raw.state !== 'in-progress' && raw.pendingIds !== undefined) return null;+ return raw;+ } catch {+ return null;+ }+ }++ /**+ * 迁移门是否已关死。三种情况:+ * - 无台账 → 开(首轮迁移 / legacy 恢复流程的留门);+ * - 台账 `in-progress` → 开(上一轮中途崩溃,按 pendingIds 续跑);+ * - 台账 `completed` / 无 state(旧格式)/ **存在但读不出** → 关。+ * 损坏台账按"关"处理是刻意的保守方向:台账由原子 temp+rename 写出,自然损坏面+ * 趋近于零;能改坏它的进程与 §7「可直接伪造合法 receipt」同类,把门放开反而是+ * 给这类进程送一条重铸授权的路。调用方发现"存在但读不出"应记 error 日志。+ */+ migrationDoorClosed(): boolean {+ if (!this.hasMigrationLedger()) return false;+ const ledger = this.readMigrationLedger();+ return ledger === null || ledger.state !== 'in-progress';+ }++ /** 是否已跑过一轮 legacy 迁移(全局一次性门;读不动按"存在"处理,宁可不再迁)。 */+ hasMigrationLedger(): boolean {+ try {+ return fs.lstatSync(this.migrationLedgerPath()).isFile();+ } catch (error) {+ // ENOENT = 从未迁过,可以迁;其它错误(权限等)= 状态未知,保守当作"已迁",+ // 绝不因为读不动 ledger 就把迁移(=从可变安装目录重建授权)再放开一次。+ return (error as NodeJS.ErrnoException).code !== 'ENOENT';+ }+ }++ async writeMigrationLedger(ledger: GhostLegacyMigrationLedger): Promise<void> {+ const root = this.rootDir();+ await fs.promises.mkdir(root, { recursive: true });+ const target = this.migrationLedgerPath();+ const temp = path.join(+ root,+ `.legacy-migration-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.writeFile(temp, `${JSON.stringify(ledger, null, 2)}\n`, {+ encoding: 'utf8',+ flag: 'wx',+ mode: 0o600,+ });+ await fs.promises.rename(temp, target);+ } finally {+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);+ }+ }++ /** 事务标记路径。点开头,不与 `<id>.json` receipt 或 `.legacy-migration.json` 撞名。 */+ private pendingMutationPath(id: string): string {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for pending mutation path');+ return path.join(this.rootDir(), `.pending-${id}.json`);+ }++ /** 事务开始:装入/更新 rename 动盘**之前**落标记(原子 temp+rename;re-begin 覆盖)。 */+ async writePendingMutation(id: string, entry: GhostPendingMutation): Promise<void> {+ const root = this.rootDir();+ await fs.promises.mkdir(root, { recursive: true });+ const target = this.pendingMutationPath(id);+ const temp = path.join(+ root,+ `.pending-${id}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.writeFile(temp, `${JSON.stringify({ version: 1, id, ...entry })}\n`, {+ encoding: 'utf8',+ flag: 'wx',+ mode: 0o600,+ });+ await fs.promises.rename(temp, target);+ } finally {+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);+ }+ }++ /** 事务提交:receipt 写成功后清标记。删不动只多留一份标记,下轮恢复幂等重判。 */+ async clearPendingMutation(id: string): Promise<void> {+ await fs.promises.rm(this.pendingMutationPath(id), { force: true });+ }++ /** 同步清标记(启动恢复在构造期同步跑,不能留 fire-and-forget 的异步删除)。 */+ clearPendingMutationSync(id: string): void {+ fs.rmSync(this.pendingMutationPath(id), { force: true });+ }++ readPendingMutationSync(id: string): GhostPendingMutationReadResult {+ let raw: Record<string, unknown>;+ const markerPath = this.pendingMutationPath(id);+ try {+ const stat = fs.lstatSync(markerPath);+ if (!stat.isFile() || stat.size > MAX_PENDING_MUTATION_BYTES) {+ return { state: 'invalid', reason: 'journal is not a regular file or exceeds size limit' };+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { state: 'missing' };+ return {+ state: 'unreadable',+ reason: error instanceof Error ? error.message : String(error),+ };+ }+ let text: string;+ try {+ text = fs.readFileSync(markerPath, 'utf8');+ } catch (error) {+ return {+ state: 'unreadable',+ reason: error instanceof Error ? error.message : String(error),+ };+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(text) as unknown;+ } catch (error) {+ return { state: 'invalid', reason: error instanceof Error ? error.message : String(error) };+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return { state: 'invalid', reason: 'journal must be an object' };+ }+ raw = parsed as Record<string, unknown>;+ if (raw.version !== 1 || raw.id !== id) {+ return { state: 'invalid', reason: 'journal version/id mismatch' };+ }+ if (raw.kind === 'uninstall') {+ if (raw.builtinTombstone !== undefined && typeof raw.builtinTombstone !== 'boolean') {+ return { state: 'invalid', reason: 'journal builtinTombstone is invalid' };+ }+ return {+ state: 'valid',+ mutation: {+ kind: 'uninstall',+ ...(raw.builtinTombstone === true ? { builtinTombstone: true } : {}),+ },+ };+ }+ if (typeof raw.packageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(raw.packageSha256)) {+ 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'+ ) {+ return { state: 'invalid', reason: 'journal clearBuiltinTombstone is invalid' };+ }+ return {+ state: 'valid',+ mutation: {+ kind: 'install',+ packageSha256: raw.packageSha256,+ ...(typeof raw.receiptRevision === 'string'+ ? { receiptRevision: raw.receiptRevision }+ : {}),+ ...(raw.clearBuiltinTombstone === true ? { clearBuiltinTombstone: true } : {}),+ },+ };+ }+ if (+ raw.kind === 'update' &&+ typeof raw.backupDirName === 'string' &&+ isManagedBackupDirName(id, raw.backupDirName)+ ) {+ const phase = raw.phase === undefined ? undefined : raw.phase;+ if (+ phase !== undefined &&+ phase !== 'prepared' &&+ phase !== 'backed-up' &&+ phase !== 'published'+ ) {+ 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))+ ) {+ return { state: 'invalid', reason: 'journal oldPackageSha256 is invalid' };+ }+ return {+ state: 'valid',+ mutation: {+ kind: 'update',+ packageSha256: raw.packageSha256,+ backupDirName: raw.backupDirName,+ ...(receiptRevision !== undefined ? { receiptRevision } : {}),+ ...(phase !== undefined ? { phase } : {}),+ ...(oldPackageSha256 !== undefined ? { oldPackageSha256 } : {}),+ },+ };+ }+ return { state: 'invalid', reason: 'journal kind/backupDirName is invalid' };+ }++ /** 状态根里所有未清的事务标记 id(启动恢复用)。 */+ listPendingMutationIdsSync(): GhostPendingMutationListResult {+ let names: string[];+ try {+ names = fs.readdirSync(this.rootDir());+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return { state: 'ok', ids: [], blocked: false };+ }+ return {+ state: 'unreadable',+ reason: error instanceof Error ? error.message : String(error),+ };+ }+ const ids: string[] = [];+ let blocked = false;+ for (const name of names) {+ const match = /^\.pending-(.+)\.json$/.exec(name);+ if (!match) continue;+ if (isValidGhostId(match[1])) ids.push(match[1]);+ else blocked = true;+ }+ return { state: 'ok', ids, blocked };+ }++ private receiptPath(id: string): string {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for receipt path');+ return path.join(this.rootDir(), `${id}.json`);+ }++ private async ensureSkillSnapshot(+ receipt: GhostInstallReceipt,+ skillSourceDir: string | undefined,+ ): Promise<void> {+ const items = receipt.manifest.skill?.items ?? [];+ if (items.length === 0) return;+ const target = this.skillSnapshotRoot(receipt.id, receipt.revision);+ // 父段遏制必须先于**任何**对 target 的操作:lstat/rm/rename 都会穿透被换成+ // junction 的父段,读写到状态根之外(见 assertManagedSnapshotParent 头注释)。+ const parent = await this.assertManagedSnapshotParent(receipt.id, { createMissing: true });+ if (!parent) throw new Error('skill snapshot parent unavailable');+ let existing: fs.Stats | null;+ try {+ existing = await fs.promises.lstat(target);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ existing = null;+ }+ if (existing) {+ if (!existing.isDirectory()) {+ throw new Error('approved skill snapshot target is not a directory');+ }+ // 快照已存在**不等于**它还是被批准的那份字节:状态根里的目录同样可被同权限+ // 进程改写,而主 Agent 是顺着共享技能链接持续读它的。所以这里必须重算,+ // 不能像上一版那样直接早退信任它。+ if (await this.skillSnapshotMatchesReceipt(receipt, target)) return;+ // 对不上的快照一律不可信:删掉,退回下面的重建路径 —— 重建本身仍要过安装+ // 目录的字节校验,所以"损坏快照"能自愈,"安装字节已漂移"仍然拒。+ await fs.promises.rm(target, { recursive: true, force: true });+ }+ if (!skillSourceDir) {+ throw new Error('approved skill snapshot is missing');+ }+ const temp = path.join(+ parent,+ `.${receipt.revision}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.mkdir(temp, { recursive: false });++ // 顺序是安全要点,不要改回"先校验源目录、再复制":源目录随时可被同权限进程+ // 改写,校验和复制各读一次就有一个可换字节的窗口,复制出来的快照可能不是被+ // 校验过的那一份。因此**先复制到 temp,再对 temp 里(即将成为快照的)那份字节+ // 做全部权威校验**,校验通过才 rename 就位。+ // 清单允许嵌套的 skill dir(如 skills/foo 与 skills/foo/bar —— 校验只拒重复,+ // 不拒前缀嵌套)。祖先目录的整树复制已经带上了嵌套项的字节,再按嵌套项复制一次+ // 会撞上 COPYFILE_EXCL 直接失败 —— 那会让一份合法清单在装入/更新/迁移/重新确认+ // 四条路上全军覆没(§5 红线)。按深度排序、祖先先复制,已覆盖的嵌套项跳过复制;+ // 指纹校验仍逐 item 进行(嵌套项的根就在祖先拷出的树里)。大小写折叠比较,+ // 与清单查重同口径。+ const copiedRoots: string[] = [];+ const itemsByDepth = [...items].sort(+ (a, b) => a.dir.split('/').length - b.dir.split('/').length,+ );+ for (const item of itemsByDepth) {+ const dirFold = item.dir.toLowerCase();+ if (copiedRoots.some((root) => dirFold === root || dirFold.startsWith(`${root}/`))) {+ continue;+ }+ // 与算指纹同一个解析入口:逐段确认真目录,挡住"中间段被换成链接"这条从技能+ // 目录之外取字节的路子。两侧必须共用,否则一侧穿透、一侧不穿透,复制的和+ // 算指纹的就不是同一组字节。+ const source = await resolveGhostContentPath(skillSourceDir, item.dir, {+ expect: 'directory',+ label: 'approved skill',+ });+ // 复制前的便宜预检:只为早失败、少做无用功(避免整份拷一个超大 SKILL.md)。+ // **这不是安全边界** —— 它读的是可变源目录,结论随时可能过期,真正说话的是+ // 下面对 temp 的校验。+ const sourceSkillMdStat = await fs.promises+ .lstat(path.join(source, 'SKILL.md'))+ .catch(() => null);+ if (+ sourceSkillMdStat &&+ (!sourceSkillMdStat.isFile() || sourceSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES)+ ) {+ throw new Error(+ `approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,+ );+ }+ await copyRegularDirectory(source, path.join(temp, ...item.dir.split('/')));+ copiedRoots.push(dirFold);+ }++ // 权威校验一律针对 temp:此刻这些字节已经脱离可变安装目录,复制期间被换过也+ // 会在这里暴露。**尺寸上限必须排在算指纹之前** —— 源目录那道预检不是安全边界+ // (预检后可被换成超大文件),若先算指纹就等于上限在权威路径上一次都没生效。+ for (const item of items) {+ const copiedSkillMdPath = path.join(temp, ...item.dir.split('/'), 'SKILL.md');+ // 包一层领域错误:这一段现在排在算指纹之前,SKILL.md 缺失时若直接抛裸 ENOENT,+ // 日志里就看不出是"技能内容被动过"这件事(只有被篡改时才可达,两种写法都+ // fail closed,纯粹为可读性)。+ const copiedSkillMdStat = await fs.promises.lstat(copiedSkillMdPath).catch((error) => {+ throw new Error(+ `approved skill ${item.dir}/SKILL.md is unreadable in the snapshot: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ });+ if (!copiedSkillMdStat.isFile() || copiedSkillMdStat.size > GHOST_SKILL_MD_MAX_BYTES) {+ throw new Error(+ `approved skill ${item.dir}/SKILL.md is not a regular file or exceeds ${GHOST_SKILL_MD_MAX_BYTES} bytes`,+ );+ }+ }+ // 指纹判定走与"接受既有快照""发布后复核"同一个 helper:同一判据只有一份实现,+ // 否则三处各写一遍、日后只改其中一处,就是这条链路前几轮反复出问题的形态。+ if (!(await this.skillSnapshotMatchesReceipt(receipt, temp))) {+ throw new Error(+ `approved skill content for ${receipt.id} no longer matches the bytes approved at install time`,+ );+ }+ for (const item of items) {+ // 指纹相符已经蕴含 frontmatter 一致(批准时点那份过过这道校验),这里重跑一遍+ // 是防止钉指纹那条路径本身有 bug,并给出更具体的错误。+ const consistencyError = checkSkillMdConsistency(+ await fs.promises.readFile(path.join(temp, ...item.dir.split('/'), 'SKILL.md'), 'utf8'),+ item,+ );+ if (consistencyError) {+ throw new Error(`approved skill ${item.dir} is inconsistent: ${consistencyError}`);+ }+ }++ await fs.promises.rename(temp, target);++ // rename 之前 temp 位于状态根内、同权限进程仍可改写它,所以就位之后再核一遍:+ // 这一步把"校验通过 → rename"之间那段窗口收掉 —— 在那段里被换过的字节到这里+ // 会暴露,并且不会留在盘上。+ //+ // 残留窗口(已知、未关):这次核对之后、主 Agent 顺着共享技能链接读取之前,快照+ // 仍可被改写。要真正关掉需要给状态根写保护或在消费侧校验,都不在本函数范围内;+ // 该缺口已正式登记在 docs/dev-rules/plugin-security-and-authoring.md 第 6 节+ // (与"内容根字节可变"是两条并列的不同缺口)。+ if (!(await this.skillSnapshotMatchesReceipt(receipt, target))) {+ await fs.promises.rm(target, { recursive: true, force: true }).catch(() => undefined);+ throw new Error('approved skill snapshot changed while being published');+ }+ } finally {+ await fs.promises.rm(temp, { recursive: true, force: true }).catch(() => undefined);+ }+ }++ /**+ * 快照目录里的字节是否仍等于 receipt 钉住的批准指纹。+ *+ * 三处调用共用同一判据(接受既有快照 / 复制后发布前 / 发布后复核) —— 这类判定散落+ * 多处再各写一遍,就是本 PR 前几轮反复出问题的成因。读不动或含非普通条目一律按+ * 不匹配处理:调用方对"不匹配"的收敛动作都是删掉重建或拒绝,始终 fail closed。+ */+ async skillSnapshotMatchesReceipt(+ receipt: GhostInstallReceipt,+ snapshotDir: string,+ ): Promise<boolean> {+ const actual = await hashApprovedSkillContent(receipt.manifest, snapshotDir).catch(() => null);+ if (!actual) return false;+ return (receipt.manifest.skill?.items ?? []).every(+ (item) => actual[item.dir] === receipt.skillContentSha256[item.dir],+ );+ }++ /**+ * 回收同一插件下非当前 revision 的技能快照与崩溃残留的 `.tmp` 目录。+ *+ * 只在新 receipt 已经原子提交之后跑:此刻旧 revision 已不是批准事实,留着+ * 就是每次更新泄漏一份完整拷贝。共享技能根里指向旧 revision 的链接会因此+ * 短暂断链,直到下一轮对账重指——对越出沙箱的 skill 槽来说,短暂"技能不可+ * 用"是正确的收敛方向,留着旧批准版本继续生效不是。+ *+ * best-effort:批准事实已经落盘,回收失败只记为待清理状态,不回滚安装。+ */+ private async pruneStaleSkillSnapshots(receipt: GhostInstallReceipt): Promise<void> {+ // 父段遏制先行:`<id>` 段被换成 junction 时,readdir 会列出外部目录的条目、+ // 随后的逐项 recursive rm 就会把**外部目录的内容**删掉(Windows 实测可复现)。+ // 回收是 best-effort:父段可疑就整体跳过,绝不带着可疑父段动盘。+ let parent: string | null;+ try {+ parent = await this.assertManagedSnapshotParent(receipt.id, { createMissing: false });+ } catch {+ return;+ }+ if (!parent) return;+ let entries: fs.Dirent[];+ try {+ entries = await fs.promises.readdir(parent, { withFileTypes: true });+ } catch {+ return;+ }+ await Promise.all(+ entries+ .filter((entry) => entry.name !== receipt.revision)+ .map((entry) =>+ fs.promises+ .rm(path.join(parent, entry.name), { recursive: true, force: true })+ .catch(() => undefined),+ ),+ );+ }+}++function isValidUniqueGhostIdArray(value: unknown): value is string[] {+ return (+ Array.isArray(value) &&+ value.every((id) => isValidGhostId(id)) &&+ new Set(value).size === value.length+ );+}++function isManagedBackupDirName(id: string, name: string): boolean {+ return new RegExp(`^\\.cindy-updating-${escapeRegExp(id)}-[0-9a-f]{8}$`).test(name);+}++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++type CleanupEntryKind = 'missing' | 'file' | 'directory' | 'link' | 'other';++async function classifyCleanupEntry(absPath: string): Promise<CleanupEntryKind> {+ try {+ return await classifyGhostDirEntry(absPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ throw error;+ }+}++function classifyCleanupEntrySync(absPath: string): CleanupEntryKind {+ try {+ return classifyGhostDirEntrySync(absPath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';+ throw error;+ }+}++/**+ * 迁移专用:读旧安装目录里的 `.cindy-trust.json` 信任镜像。#1080 之前授权事实就散在+ * 安装目录三文件里,升级迁移要从它们重建等价 receipt。+ *+ * 缺失/损坏/非普通文件一律返回 `null` —— trust 只是**展示与来源信号**(能力由 manifest+ * slot 授予,不由 trust 等级授予),读不出时调用方用保守默认(`unverified`)而不是让整个+ * 迁移失败:旧模型读的也是同一个文件,缺了同样显示不出 verified,不比旧模型少展示什么。+ *+ * `cindy-official` 一律**封顶拒收**(按镜像损坏处理):官方档只该由 provisioning 在与+ * 随包种子逐字节对账后授予,而本函数的两个调用方(legacy 迁移 / 从已装目录重新确认)都+ * 只服务非随包插件 —— 非随包目录里出现官方档镜像本身就不可信,照抄会让确认卡/列表把+ * 一个可变目录里的插件展示成「Cindy 官方」。+ */+export function readLegacyInstallTrust(dir: string): GhostTrustInfo | null {+ const file = path.join(dir, '.cindy-trust.json');+ try {- const stat = fs.lstatSync(file);- if (!stat.isFile() || stat.size > MAX_RECEIPT_BYTES) return null;- const trust = validateTrust(JSON.parse(fs.readFileSync(file, 'utf8')));- if (!trust || trust.level === 'cindy-official') return null;- return trust;- } catch {++ const realDir = fs.realpathSync(dir);++ const bytes = readBoundedFileNoFollowSync(file, MAX_RECEIPT_BYTES, { containWithin: realDir });++ if (bytes === null) return null;++ try {++ const trust = validateTrust(JSON.parse(bytes.toString('utf8')));++ if (!trust || trust.level === 'cindy-official') return null;++ return trust;++ } catch {++ return null;++ }++ } catch (error) {++ if ((error as NodeJS.ErrnoException).code === 'EIO') throw error;+ return null;+ }+}++export function createGhostInstallReceipt(input: {+ manifest: GhostManifest;+ localeResources: Record<string, GhostManifestLocaleResource>;+ enabled: boolean;+ trust: GhostTrustInfo;+ /** 由 `hashApprovedSkillContent` 从**这次批准的内容目录**现算,不可沿用旧值。 */+ skillContentSha256: Record<string, string>;+ packageSha256?: string;+ revision?: string;+ iconDataUrl?: string;+}): GhostInstallReceipt {+ return {+ schemaVersion: RECEIPT_SCHEMA_VERSION,+ id: input.manifest.id,+ revision: input.revision ?? crypto.randomUUID(),+ manifest: input.manifest,+ localeResources: input.localeResources,+ enabled: input.enabled,+ trust: input.trust,+ skillContentSha256: input.skillContentSha256,+ ...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),+ ...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),+ };+}++/**+ * 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。+ *+ * 判据全部取自 `ghostContentTree`(路径逐段解析 + 条目类型判定 + 指纹格式),与+ * 快照拷贝侧 `copyRegularDirectory`、安装目录漂移指纹 `hashApprovedDirectory`、+ * 随包种子指纹 `fingerprintDirContent` 共用同一份实现。差异只有显式策略:技能+ * 目录**不跳过点开头条目**(技能指令可以引用目录里的任意文件,漏掉一类就是漏掉+ * 一条改写通道),非普通条目一律拒。+ */+export async function hashApprovedSkillContent(+ manifest: GhostManifest,+ sourceDir: string | undefined,+): Promise<Record<string, string>> {+ const items = manifest.skill?.items ?? [];+ if (items.length === 0) return {};+ if (!sourceDir) throw new Error('skill content hash requires a source directory');+ const result: Record<string, string> = {};+ for (const item of items) {+ const itemRoot = await resolveGhostContentPath(sourceDir, item.dir, {+ expect: 'directory',+ label: 'approved skill',+ });+ const tree = await collectGhostContentFiles(itemRoot, {+ dotEntries: 'include',+ nonRegular: 'throw',+ label: `approved skill ${item.dir}`,+ });+ result[item.dir] = await hashGhostContentFiles(itemRoot, tree.files, tree.rootIdentity);+ }+ return result;+}++function validateReceipt(+ raw: unknown,+ expectedId: string,+): { ok: true; receipt: GhostInstallReceipt } | { ok: false; reason: string } {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ return { ok: false, reason: 'receipt 必须是对象' };+ }+ const value = raw as Record<string, unknown>;+ if (value.schemaVersion !== RECEIPT_SCHEMA_VERSION) {+ return { ok: false, reason: 'receipt schemaVersion 不受支持' };+ }+ if (value.id !== expectedId || !isValidGhostId(expectedId)) {+ return { ok: false, reason: 'receipt id 与安装目录不一致' };+ }+ if (typeof value.revision !== 'string' || !isRevision(value.revision)) {+ return { ok: false, reason: 'receipt revision 不合法' };+ }+ const manifestResult = validateGhostManifest(value.manifest);+ if (!manifestResult.ok || manifestResult.manifest.id !== expectedId) {+ return {+ ok: false,+ reason: manifestResult.ok ? 'receipt manifest id 不一致' : manifestResult.reason,+ };+ }+ if (typeof value.enabled !== 'boolean') {+ return { ok: false, reason: 'receipt enabled 不合法' };+ }+ const trust = validateTrust(value.trust);+ if (!trust) return { ok: false, reason: 'receipt trust 不合法' };+ if (+ value.packageSha256 !== undefined &&+ (typeof value.packageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(value.packageSha256))+ ) {+ return { ok: false, reason: 'receipt packageSha256 不合法' };+ }+ // 技能字节指纹是运行期判据,必填且键集必须与清单声明严格一致 —— 留"字段缺失就+ // 跳过校验"的可选口子等于给漂移留一条绕过路径。receipt 格式尚未随任何版本发布,+ // 不存在需要兼容的旧 receipt。+ const skillContentSha256: Record<string, string> = {};+ {+ const raw = value.skillContentSha256;+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {+ return { ok: false, reason: 'receipt skillContentSha256 不合法' };+ }+ const expectedDirs = (manifestResult.manifest.skill?.items ?? [])+ .map((item) => item.dir)+ .sort();+ const actualDirs = Object.keys(raw as Record<string, unknown>).sort();+ if (+ expectedDirs.length !== actualDirs.length ||+ expectedDirs.some((dir, index) => dir !== actualDirs[index])+ ) {+ return { ok: false, reason: 'receipt skillContentSha256 与 manifest 声明不一致' };+ }+ for (const [dir, digest] of Object.entries(raw as Record<string, unknown>)) {+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)) {+ return { ok: false, reason: `receipt skillContentSha256 不合法:${dir}` };+ }+ skillContentSha256[dir] = digest;+ }+ }+ if (+ value.iconDataUrl !== undefined &&+ (typeof value.iconDataUrl !== 'string' ||+ Buffer.byteLength(value.iconDataUrl, 'utf8') > MAX_ICON_DATA_URL_BYTES ||+ !ICON_DATA_URL_RE.test(value.iconDataUrl))+ ) {+ return { ok: false, reason: 'receipt iconDataUrl 不合法' };+ }+ if (+ !value.localeResources ||+ typeof value.localeResources !== 'object' ||+ Array.isArray(value.localeResources)+ ) {+ return { ok: false, reason: 'receipt localeResources 不合法' };+ }+ const expectedLocalePaths = [+ ...new Set(Object.values(manifestResult.manifest.locales ?? {})),+ ].sort();+ const actualLocalePaths = Object.keys(value.localeResources as Record<string, unknown>).sort();+ if (+ expectedLocalePaths.length !== actualLocalePaths.length ||+ expectedLocalePaths.some((localePath, index) => localePath !== actualLocalePaths[index])+ ) {+ return { ok: false, reason: 'receipt localeResources 与 manifest 声明不一致' };+ }+ const localeResources: Record<string, GhostManifestLocaleResource> = {};+ for (const [localePath, resource] of Object.entries(+ value.localeResources as Record<string, unknown>,+ )) {+ if (Buffer.byteLength(JSON.stringify(resource), 'utf8') > GHOST_LOCALE_MAX_BYTES) {+ return { ok: false, reason: `receipt locale 超过大小上限:${localePath}` };+ }+ const validated = validateGhostManifestLocaleResource(resource, manifestResult.manifest);+ if (!validated.ok) return { ok: false, reason: `receipt locale 不合法:${localePath}` };+ localeResources[localePath] = validated.resource;+ }+ return {+ ok: true,+ receipt: {+ schemaVersion: RECEIPT_SCHEMA_VERSION,+ id: expectedId,+ revision: value.revision,+ manifest: manifestResult.manifest,+ localeResources,+ enabled: value.enabled,+ trust,+ skillContentSha256,+ ...(typeof value.packageSha256 === 'string' ? { packageSha256: value.packageSha256 } : {}),+ ...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),+ },+ };+}++function isRevision(value: string): boolean {+ return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);+}++async function copyRegularDirectory(source: string, target: string): Promise<void> {+ // 类型判据与 hashApprovedSkillContent 同源(ghostContentTree):两侧必须同形,+ // 否则指纹算的和快照拷的可能不是同一组字节。+ if ((await classifyGhostDirEntry(source)) !== 'directory') {+ throw new Error(`skill source is not a directory: ${source}`);+ }+ await fs.promises.mkdir(target, { recursive: true });+ const entries = await fs.promises.readdir(source, { withFileTypes: true });+ for (const entry of entries) {+ const from = path.join(source, entry.name);+ const to = path.join(target, entry.name);+ const kind = await classifyGhostDirEntry(from);+ if (!isRegularGhostDirEntry(kind)) {+ throw new Error(+ `skill snapshot rejects ${kind === 'link' ? 'link' : 'non-regular'} entry: ${from}`,+ );+ }+ if (kind === 'directory') {+ await copyRegularDirectory(from, to);+ } else {+ await fs.promises.copyFile(from, to, fs.constants.COPYFILE_EXCL);+ }+ }+}++function validateTrust(raw: unknown): GhostTrustInfo | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const value = raw as Record<string, unknown>;+ if (+ !['cindy-official', 'reviewed', 'verified-publisher', 'unverified'].includes(+ String(value.level),+ ) ||+ typeof value.publisherSigned !== 'boolean' ||+ typeof value.publisherVerified !== 'boolean' ||+ typeof value.reviewed !== 'boolean'+ ) {+ return null;+ }+ const optionalStrings = ['publisherName', 'publisherKeyId', 'reviewerName'] as const;+ for (const key of optionalStrings) {+ if (value[key] !== undefined && typeof value[key] !== 'string') return null;+ }+ if (value.unknownReviewer !== undefined && typeof value.unknownReviewer !== 'boolean') {+ return null;+ }+ return value as unknown as GhostTrustInfo;+}diff --cc apps/desktop/src/main/cindy-brain/ghostOwnerScope.tsindex 0000000000,0000000000..f4c1c03adbnew file mode 100644--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostOwnerScope.ts@@@ -1,0 -1,0 +1,24 @@@++/** Owner-bound checks shared by asynchronous Ghost delivery paths. */++++export interface GhostOwnerScope {++ /** Capture the owner before the first asynchronous operation. */++ capture(): unknown;++ /** Check the captured in-process owner and generation. */++ isCurrent(scope: unknown): boolean;++ /** Check the durable projection marker for the captured owner. */++ isStable(scope: unknown): boolean;++ /** Stop stale runtime work and discard owner-bound buffered work. */++ onInvalidated?(ghostId: string): void;++}++++export function isGhostOwnerScopeUsable(++ scope: GhostOwnerScope | undefined,++ captured: unknown,++): boolean {++ if (!scope) return true;++ try {++ return scope.isCurrent(captured) && scope.isStable(captured);++ } catch {++ return false;++ }++}diff --cc apps/desktop/src/main/cindy-brain/index.tsindex 05b4d6f9a1,8bb53d6390..73e433e0b4--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -39,6 -36,6 +39,10 @@@ import} from '../../shared/ghost.js';import type { PluginMarketPackageReviewFacts } from '../../shared/pluginMarket.js';import { getAppCapabilities } from '../appCapabilities.js';++import {++ isGhostSkillProjectionBoundaryStableForOwner,++ withGhostSkillProjectionReconcile,++} from '../authBoundaryQuarantine.js';import {activeOwnerScopeKey,getActiveDataOwnerPushStamp,@@@ -128,7 -110,7 +132,9 @@@ import { mapGhostOauthConnectError } frimport { 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 { assertGhostSkillProjectionStableOwner } from '../authBoundaryQuarantine.js';++import { type GhostOwnerScope } from './ghostOwnerScope.js';import {assertTrustedAppRendererEvent,isTrustedAppRendererEvent,@@@ -490,6 -461,6 +496,26 @@@ function isSameAppSession(a: ActiveAppSreturn a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;}++const ghostOwnerScope: GhostOwnerScope = {++ capture: () => captureGhostMutationOwner(),++ isCurrent: (scope) =>++ !!scope && isSameAppSession(scope as ActiveAppSession, getActiveAppSession()),++ isStable: (scope) =>++ !!scope && isGhostSkillProjectionBoundaryStableForOwner(++ (scope as ActiveAppSession).dataOwnerId,++ ),++ onInvalidated: (ghostId) => {++ try {++ getGhostRuntime().stop(ghostId);++ } catch (error) {++ log.warn('stale Ghost owner runtime stop failed', {++ ghostId,++ error: error instanceof Error ? error.message : String(error),++ });++ }++ },++};++function currentLegacyGhostMigrationSession(): {mode: ActiveAppSession['mode'];dataOwnerId: string | null;@@@ -690,31 -643,9 +716,36 @@@ async function retryLegacyGhostRecoverygetGhostNodeRuntimeBroker().stop(ghost.manifest.id);}}+ // 只有 owner recovery 在 rename 前写入并在本轮确认的 durable marker 才能进入+ // receipt backfill。不能从安装根扫描结果推断“刚搬入”,否则同一时间窗内由其他+ // 写者放入的无 receipt 目录会被当成 legacy 事实自动铸造批准。+ const recoveredLegacyIds = [...(result.recoveredIds ?? [])];+ if (recoveredLegacyIds.length > 0) {+ try {++ const expectedApprovalProjectionSha256ById =++ result.recoveredApprovalProjectionSha256ById ?? {};+ const backfill = await getGhostManager().backfillRecoveredLegacyGhosts(+ recoveredLegacyIds,- { includePending: true },++ {++ includePending: true,++ expectedApprovalProjectionSha256ById,++ },+ );+ const pending = new Set(backfill.pending ?? []);+ const failed = new Set(backfill.failed);+ await acknowledgeRecoveredLegacyGhosts(+ expectedOwner.dataOwnerId,+ recoveredLegacyIds.filter((id) => !pending.has(id) && !failed.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' &&- await scheduleBuiltinReconcile('legacy-recovery');+ (await scheduleBuiltinReconcile('legacy-recovery'));if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();const ghosts = getGhostManager().list();for (const ghost of ghosts) {@@@ -746,6 -677,6 +777,8 @@@ export function waitForGhostMutations()/** Account-managed built-ins are unavailable outside a verified cloud session. */export function isGhostAvailableForActiveSession(id: string): boolean {++ const activeOwner = getActiveAppSession().dataOwnerId;++ if (!isGhostSkillProjectionBoundaryStableForOwner(activeOwner)) return false;return !isCindyAccountGhostId(id) || getAppCapabilities().canUseCindyAccountServices;}@@@ -795,6 -717,6 +828,12 @@@ export function listAvailableGhostsForAfunction requireGhostAvailableForActiveSession(id: string): void {if (!isGhostAvailableForActiveSession(id)) {++ if (isAppSessionBoundaryPending()) {++ throwIpcError(++ 'PRECONDITION_FAILED',++ 'Ghost projection is switching owners; retry after the boundary settles.',++ );++ }throwIpcError('PERMISSION_DENIED', 'This Plugin requires a Cindy account.');}}@@@ -1520,6 -1225,6 +1559,7 @@@ export function getGhostCardActionDispaonActivityStart: (key, sessionId) =>getGhostSessionActivityTracker().begin(key, sessionId),now: () => Date.now(),++ ownerScope: ghostOwnerScope,log,});}@@@ -1569,6 -1274,6 +1609,7 @@@ export function getGhostSubscriptionGatname: ghost.manifest.name,}, isDataOwnerPushStamp(ownerStamp) ? ownerStamp : undefined);},++ ownerScope: ghostOwnerScope,log,});}@@@ -5519,10 -5022,10 +5560,19 @@@ export function registerGhostIpc(): voiif (!listBuiltinSeedIds(builtinSeedRootDirs()).includes(id)) {throwIpcError('NOT_FOUND', `意识 ${id} 不是内置种子`);}-- clearBuiltinTombstone(brainRootDir(), id, log);-- void scheduleBuiltinReconcile('restore');-- await builtinReconcileChain; // 等本轮装完再返回,renderer 拿到结果时列表已就位-- return { ok: true };++ const expectedOwner = captureGhostMutationOwner();++ const releaseMutation = beginGhostMutation(expectedOwner);++ try {++ clearBuiltinTombstone(brainRootDir(), id, log);++ void scheduleBuiltinReconcile('restore');++ await builtinReconcileChain; // 等本轮装完再返回,renderer 拿到结果时列表已就位++ if (!isSameAppSession(expectedOwner, getActiveAppSession())) {++ throw new Error('账号已切换,已取消本次 Plugin 操作');++ }++ return { ok: true };++ } finally {++ releaseMutation();++ }});// 启用 / 停用(停用 = 面板休眠,布局位置保留;详见 GhostManager.setEnabled)。@@@ -5832,6 -5322,6 +5882,19 @@@ function broadcastGhostsChanged// 永不并发两趟 fs 对账;失败仅 warn,幂等设计靠下一次广播/启动自愈。let skillReconcileInFlight = false;let skillReconcilePending = false;++let skillReconcileRetryTimer: ReturnType<typeof setTimeout> | null = null;++const SKILL_RECONCILE_RETRY_MS = 1_000;++++function scheduleGhostSkillReconcileRetry(): void {++ skillReconcilePending = true;++ if (skillReconcileRetryTimer) return;++ skillReconcileRetryTimer = setTimeout(() => {++ skillReconcileRetryTimer = null;++ scheduleGhostSkillReconcile();++ }, SKILL_RECONCILE_RETRY_MS);++ skillReconcileRetryTimer.unref?.();++}++function scheduleGhostSkillReconcile(): void {skillReconcilePending = true;if (skillReconcileInFlight) return;@@@ -5840,21 -5330,11 +5903,28 @@@try {while (skillReconcilePending) {skillReconcilePending = false;+ // 每轮 capture owner + 持租约到本轮全部校验/删/建/扇出完成:全局技能根写的是+ // owner-scoped 受管根的投影,不持租约时账号切换可以落在"A 的快照校验通过后、+ // 链接创建前",把全局 ~/.agents/skills 指向 A 的批准快照 —— B 生效后主 Agent+ // 有跨 owner 读取窗口。租约让 session teardown 的 waitForIdle 等本轮收尾;+ // 边界期开轮直接抛,pending 保留,换号完成后的 ghosts:changed 广播重跑。+ let releaseLease: (() => void) | null = null;try {- releaseLease = beginGhostMutation(captureGhostMutationOwner());-- const result = await reconcileGhostSkillLinks({-- ghosts: getGhostManager().list(),-- brainRoot: brainRootDir(),- approvalStateRoot: getGhostManager().approvalStateRoot(),- validateApprovedSkillSnapshot: (ghost) =>- getGhostManager().verifyApprovedSkillSnapshot(ghost),-- });++ const owner = captureGhostMutationOwner();++ const result = await withGhostSkillProjectionReconcile(++ owner.dataOwnerId ?? '',++ async () => {++ releaseLease = beginGhostMutation(owner);++ return reconcileGhostSkillLinks({++ ghosts: getGhostManager().list(),++ brainRoot: brainRootDir(),++ approvalStateRoot: getGhostManager().approvalStateRoot(),++ assertOwnerStable: () => assertGhostSkillProjectionStableOwner(owner.dataOwnerId ?? ''),++ validateApprovedSkillSnapshot: (ghost) =>++ getGhostManager().verifyApprovedSkillSnapshot(ghost),++ });++ },++ );if (result.warnings.length > 0) {log.warn('ghost skill reconcile warnings', { warnings: result.warnings });}@@@ -5864,16 -5344,9 +5934,22 @@@});}} catch (err) {- if (isAppSessionBoundaryPending()) {++ const message = err instanceof Error ? err.message : String(err);++ if (++ isAppSessionBoundaryPending()++ || message.includes('projection is not stable')++ || message.includes('boundary lock is busy or unavailable')++ ) {+ // 账号边界期:本轮不动盘,保留 pending 等换号完成后的广播重跑。- skillReconcilePending = true;++ scheduleGhostSkillReconcileRetry();+ break;+ }log.warn('ghost skill reconcile failed', {-- error: err instanceof Error ? err.message : String(err),++ error: message,});+ } finally {- releaseLease?.();++ const release = releaseLease as (() => void) | null;++ release?.();}}} finally {diff --cc apps/desktop/src/main/cindy-brain/skillSlot.tsindex c525b9d8ac,4673cb282e..70f6387232--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@@ -213,16 -85,6 +213,18 @@@ interface ReconcileOptionsghosts: InstalledGhost[];/** 当前 owner 的插件安装根(userData/.../cindy-brain)。 */brainRoot: string;+ /**+ * Host-owned root containing approval-revision-bound skill snapshots.+ * 必填:漏给会让指向快照的活链接被判成外来链接而永不撤链(见头注释)。+ */+ approvalStateRoot: string;+ /**+ * 在把批准快照投影成共享链接前重算其完整内容摘要。必填:只检查 SKILL.md+ * frontmatter 拦不住正文/辅助文件被改写,而已有链接目标不变时也不能直接 kept。+ */+ validateApprovedSkillSnapshot: (ghost: InstalledGhost) => Promise<boolean>;++ /** Present only for the Ghost-managed global fanout path. */++ assertOwnerStable?: () => void;/** 覆盖 home 目录(仅测试)。 */homeDir?: string;}@@@ -427,7 -211,7 +429,7 @@@ export async function reconcileGhostSkitry {const stat = await fsp.lstat(linkPath);if (!stat.isSymbolicLink()) continue; // TOCTOU 防御:再确认一次才动手-- await fsp.rm(linkPath, { recursive: true, force: true });++ await fsp.unlink(linkPath);actions.push({ linkName, op: 'removed' });changed = true;} catch (err) {@@@ -484,7 -268,7 +486,10 @@@// 缺失——canonical 正常但 .claude 侧被删或上次扇出失败);幂等、失败不阻断。try {const fanout = await prepareSharedGlobalSkillLinks(-- opts.homeDir !== undefined ? { homeDir: opts.homeDir } : {},++ {++ ...(opts.homeDir !== undefined ? { homeDir: opts.homeDir } : {}),++ ...(opts.assertOwnerStable ? { assertOwnerStable: opts.assertOwnerStable } : {}),++ },);warnings.push(...fanout.warnings);} catch (err) {diff --cc apps/desktop/src/main/cindy-brain/subscriptionGateway.tsindex 0706e4623b,0706e4623b..c060e88fd2--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts@@@ -40,6 -40,6 +40,7 @@@ importtype GhostSubscribeTopic,type InstalledGhost,} from '../../shared/ghost.js';++import { isGhostOwnerScopeUsable, type GhostOwnerScope } from './ghostOwnerScope.js';/** block 理由展示上限(超长截断,防意识用理由塞小作文)。 */const BLOCK_REASON_MAX_CHARS = 200;@@@ -88,6 -88,6 +89,7 @@@ export interface GhostSubscriptionGatewnow(): number;/** 钩子熔断回调(通知 renderer + 日志;每意识只触发一次)。 */onHookFused?(ghost: InstalledGhost, ownerStamp?: unknown): void;++ ownerScope?: GhostOwnerScope;/** hookId 生成(测试注入固定序列;缺省 randomUUID)。 */newHookId?(): string;log?: {@@@ -110,6 -110,6 +112,7 @@@ interface SubEntry/** 熔断:钩子降级为不再询问(旁听不受影响)。意识重启不自动复位,* 重新启停(disable/enable 清 entry)或重启应用后恢复。 */hookFused: boolean;++ ownerScope: unknown;}/** 待决钩子(hookId → 归属意识与 resolver)。 */@@@ -143,7 -143,7 +146,15 @@@ export class GhostSubscriptionGatewayprivate entry(ghostId: string): SubEntry {let e = this.entries.get(ghostId);if (!e) {-- e = { seq: 0, buffer: [], pendingDropped: 0, waking: false, hookFails: 0, hookFused: false };++ e = {++ seq: 0,++ buffer: [],++ pendingDropped: 0,++ waking: false,++ hookFails: 0,++ hookFused: false,++ ownerScope: undefined,++ };this.entries.set(ghostId, e);}return e;@@@ -157,6 -157,6 +168,15 @@@): void {const ghostId = ghost.manifest.id;const e = this.entry(ghostId);++ const ownerScope = this.captureOwnerScope();++ if (!this.ownerScopeUsable(ownerScope)) {++ this.invalidateOwner(ghostId, e);++ return;++ }++ if (e.ownerScope !== undefined && !this.ownerScopeUsable(e.ownerScope)) {++ this.invalidateOwner(ghostId, e);++ }++ e.ownerScope = ownerScope;const evt: GhostPipeEventPush = {type: 'event',name,@@@ -169,14 -169,14 +189,23 @@@// 直投条件:在跑 + 缓冲已清 + 无唤醒在途——三者缺一都排队,否则新事件// 会插到缓冲里旧事件前面(seq 乱序)。投递失败(刚崩窗口期)同样回落缓冲。if (this.deps.isRunning(ghostId) && e.buffer.length === 0 && !e.waking) {-- if (this.sendOne(ghostId, e, evt)) return;++ if (this.sendOne(ghostId, e, evt, ownerScope)) return;}-- this.buffer(ghost, e, evt);++ this.buffer(ghost, e, evt, ownerScope);}/** 实际投递一条 did- 事件:溢出丢弃数在此刻附着(构造期附着会被后续* 同样溢出的事件把计数吞掉),投成才清零。返回是否投成。 */-- private sendOne(ghostId: string, e: SubEntry, evt: GhostPipeEventPush): boolean {++ private sendOne(++ ghostId: string,++ e: SubEntry,++ evt: GhostPipeEventPush,++ ownerScope = e.ownerScope,++ ): boolean {++ if (!this.ownerScopeUsable(ownerScope)) {++ this.invalidateOwner(ghostId, e);++ return false;++ }const payload = e.pendingDropped > 0 ? { ...evt, dropped: e.pendingDropped } : evt;try {this.deps.sendToGhost(ghostId, payload);@@@ -187,22 -187,22 +216,37 @@@}}-- private buffer(ghost: InstalledGhost, e: SubEntry, evt: GhostPipeEventPush): void {++ private buffer(++ ghost: InstalledGhost,++ e: SubEntry,++ evt: GhostPipeEventPush,++ ownerScope: unknown,++ ): void {if (e.buffer.length >= GHOST_SUB_QUEUE_MAX) {e.buffer.shift();e.pendingDropped += 1;}e.buffer.push(evt);-- this.kickWake(ghost, e);++ this.kickWake(ghost, e, ownerScope);}/** 事件到达即按需拉起(去重:唤醒在途不重复 spawn),醒后顺序补投。 */-- private kickWake(ghost: InstalledGhost, e: SubEntry): void {++ private kickWake(ghost: InstalledGhost, e: SubEntry, ownerScope: unknown): void {if (e.waking) return;++ if (!this.ownerScopeUsable(ownerScope)) {++ this.invalidateOwner(ghost.manifest.id, e);++ return;++ }e.waking = true;void this.deps.wake(ghost)-- .then(() => this.flush(ghost.manifest.id, e))++ .then(() => {++ if (!this.ownerScopeUsable(ownerScope)) {++ this.invalidateOwner(ghost.manifest.id, e);++ return;++ }++ this.flush(ghost.manifest.id, e, ownerScope);++ }).catch((err) => {// 唤醒失败缓冲保留(封顶丢最旧),下一条事件再试。this.deps.log?.warn('ghost subscribe wake failed', {@@@ -215,7 -215,7 +259,37 @@@});}-- private flush(ghostId: string, e: SubEntry): void {++ private captureOwnerScope(): unknown {++ if (!this.deps.ownerScope) return undefined;++ try {++ return this.deps.ownerScope.capture();++ } catch {++ return Symbol('invalid-owner-scope');++ }++ }++++ private ownerScopeUsable(captured: unknown): boolean {++ return isGhostOwnerScopeUsable(this.deps.ownerScope, captured);++ }++++ private invalidateOwner(ghostId: string, e: SubEntry): void {++ e.buffer.length = 0;++ e.pendingDropped = 0;++ e.ownerScope = undefined;++ for (const [hookId, pending] of this.pendingHooks) {++ if (pending.ghostId !== ghostId) continue;++ this.pendingHooks.delete(hookId);++ pending.resolve(null);++ }++ this.deps.ownerScope?.onInvalidated?.(ghostId);++ }++++ private flush(ghostId: string, e: SubEntry, ownerScope: unknown): void {++ if (!this.ownerScopeUsable(ownerScope)) {++ this.invalidateOwner(ghostId, e);++ return;++ }++ e.ownerScope = ownerScope;while (e.buffer.length > 0 && this.deps.isRunning(ghostId)) {if (!this.sendOne(ghostId, e, e.buffer[0])) break; // 又熄灯了:留在缓冲等下次e.buffer.shift();@@@ -234,6 -234,6 +308,8 @@@input: { sessionId: string; text: string },ownerStamp?: unknown,): Promise<GhostScreenResult> {++ const ownerScope = this.captureOwnerScope();++ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };let currentText = input.text;let rewritten = false;let lastRewriteGhost: InstalledGhost | null = null;@@@ -247,7 -247,7 +323,8 @@@const verdict = await this.askOne(ghost, e, 'will-user-message', {sessionId: input.sessionId,text: currentText,-- }, ownerStamp);++ }, ownerStamp, ownerScope);++ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };if (verdict?.action === 'block') {const reason = (verdict.reason ?? '').slice(0, BLOCK_REASON_MAX_CHARS);this.deps.log?.info('ghost hook blocked user message', { ghostId, sessionId: input.sessionId });@@@ -290,6 -290,6 +367,8 @@@input: { sessionId: string; text: string },ownerStamp?: unknown,): Promise<GhostAssistantScreenResult> {++ const ownerScope = this.captureOwnerScope();++ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };let currentText = input.text;let lastRewriteGhost: InstalledGhost | null = null;let renderGhost: InstalledGhost | null = null;@@@ -305,7 -305,7 +384,8 @@@const verdict = await this.askOne(ghost, e, 'will-assistant-message', {sessionId: input.sessionId,text: currentText,-- }, ownerStamp);++ }, ownerStamp, ownerScope);++ if (!this.ownerScopeUsable(ownerScope)) return { action: 'allow' };if (verdict?.action === 'rewrite' && typeof verdict.text === 'string') {const next = verdict.text.slice(0, GHOST_HOOK_REWRITE_MAX_CHARS).trim();// 空改写(意识把正文清空)视为无意义,忽略此次 rewrite 保原文。@@@ -357,6 -357,6 +437,7 @@@hookName: 'will-user-message' | 'will-assistant-message',input: { sessionId: string; text: string },ownerStamp?: unknown,++ ownerScope?: unknown,): Promise<HookVerdict | null> {const ghostId = ghost.manifest.id;const hookId = this.deps.newHookId?.() ?? randomUUID();@@@ -376,8 -376,8 +457,23 @@@let deliverFailure: string | null = null;void (async () => {++ const capturedOwner = ownerScope ?? this.captureOwnerScope();++ if (!this.ownerScopeUsable(capturedOwner)) {++ this.invalidateOwner(ghostId, e);++ return;++ }// 常驻意识正常在跑;崩溃恢复窗口内兜底拉一次。-- if (!this.deps.isRunning(ghostId)) await this.deps.wake(ghost);++ if (!this.deps.isRunning(ghostId)) {++ await this.deps.wake(ghost);++ if (!this.ownerScopeUsable(capturedOwner)) {++ this.invalidateOwner(ghostId, e);++ return;++ }++ }++ if (!this.ownerScopeUsable(capturedOwner)) {++ this.invalidateOwner(ghostId, e);++ return;++ }this.deps.sendToGhost(ghostId, {type: 'event',name: hookName,@@@ -395,6 -395,6 +491,7 @@@const verdict = await verdictPromise;clearTimeout(timer);if (verdict === null) {++ if (!this.ownerScopeUsable(ownerScope)) return null;this.noteHookFailure(ghost, e, deliverFailure ?? 'timeout', ownerStamp);return null;}diff --cc apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.tsindex 62f6baaced,62f6baaced..81b30234a2--- a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts@@@ -12,15 -12,15 +12,27 @@@ import fs from 'node:fs'import fsp from 'node:fs/promises';import os from 'node:os';import path from 'node:path';++import { spawn } from 'node:child_process';vi.mock('../../logger', () => ({createLogger: () => ({ warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }),}));--import { withCrossProcessLock } from '../crossProcessLock';++import { __testing, withCrossProcessLock } from '../crossProcessLock';let dir: string;++function deferred<T = void>(): {++ promise: Promise<T>;++ resolve: (value: T) => void;++} {++ let resolve!: (value: T) => void;++ const promise = new Promise<T>((resolvePromise) => {++ resolve = resolvePromise;++ });++ return { promise, resolve };++}++beforeEach(() => {dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cross-process-lock-'));});@@@ -36,6 -36,6 +48,17 @@@ async function writeStaleLock(lock: strawait fsp.utimes(lock, old, old);}++async function writeStaleReclaimGate(lock: string): Promise<void> {++ const gate = `${lock}.reclaim`;++ await fsp.writeFile(++ gate,++ JSON.stringify({ pid: 0x7ffffffe, startedAt: 1, nonce: 'stale-gate' }),++ 'utf8',++ );++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(gate, old, old);++}++describe('接管陈旧锁', () => {it('删得掉 → 接管成功,task 拿到 held=true', async () => {const lock = path.join(dir, 'lock');@@@ -49,18 -49,18 +72,18 @@@it('锁文件删不掉 → 立刻降级返回,不空转到超时(更不无限循环)', async () => {const lock = path.join(dir, 'lock');await writeStaleLock(lock);-- const originalRm = fsp.rm;-- let rmAttempts = 0;-- const spy = vi.spyOn(fsp, 'rm').mockImplementation((async (-- target: unknown,-- ...rest: unknown[]++ const originalRename = fsp.rename;++ let renameAttempts = 0;++ const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (++ from: unknown,++ to: unknown,) => {-- if (typeof target === 'string' && target === lock) {-- rmAttempts += 1;++ if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {++ renameAttempts += 1;throw Object.assign(new Error('EPERM'), { code: 'EPERM' });}-- return (originalRm as (...args: unknown[]) => Promise<unknown>)(target, ...rest);-- }) as unknown as typeof fsp.rm);++ return (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);++ }) as typeof fsp.rename);try {const started = performance.now();const status = await withCrossProcessLock(@@@ -74,11 -74,11 +97,539 @@@expect(status).toEqual({ held: false, reason: 'busy' });// 不该把 waitMs 熬完,也不该反复重试删除。expect(elapsed).toBeLessThan(1_000);-- expect(rmAttempts).toBe(1);++ expect(renameAttempts).toBe(1);// 别人的锁没被动过。expect(fs.existsSync(lock)).toBe(true);++ expect(fs.existsSync(`${lock}.reclaim`)).toBe(false);++ } finally {++ spy.mockRestore();++ }++++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ });++++ it('reclaims a crashed reclaim gate before taking over the stale lock', async () => {++ const lock = path.join(dir, 'lock');++ await writeStaleLock(lock);++ await writeStaleReclaimGate(lock);++++ const status = await withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s);++++ expect(status).toEqual({ held: true });++ expect(fs.existsSync(`${lock}.reclaim`)).toBe(false);++ });++++ it.each(['', '{not-json'])('keeps a stale legacy malformed lock fail-closed: %j', async (content) => {++ const lock = path.join(dir, 'lock');++ await fsp.writeFile(lock, content, 'utf8');++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(lock, old, old);++++ await expect(++ withCrossProcessLock(++ lock,++ { label: 'test', waitMs: 100, allowMalformedStaleTakeover: false },++ async (s) => s,++ ),++ ).resolves.toEqual({ held: false, reason: 'busy' });++ });++++ it('keeps a stale legacy lock when its pid started before the lock file', async () => {++ const lock = path.join(dir, 'lock');++ await fsp.writeFile(lock, JSON.stringify({ pid: process.pid, startedAt: 1 }), 'utf8');++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(lock, old, old);++++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 100 }, async (s) => s),++ ).resolves.toEqual({ held: false, reason: 'busy' });++ });++++ it('reclaims a legacy lock when the recorded pid was reused after file creation', async () => {++ const lock = path.join(dir, 'lock');++ await fsp.writeFile(lock, '{}', 'utf8');++ await new Promise((resolve) => setTimeout(resolve, 2_100));++ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], {++ windowsHide: true,++ stdio: 'ignore',++ });++ try {++ await new Promise<void>((resolve, reject) => {++ child.once('spawn', resolve);++ child.once('error', reject);++ });++ if (!child.pid) throw new Error('child pid missing');++ await fsp.writeFile(lock, JSON.stringify({ pid: child.pid, startedAt: 1 }), 'utf8');++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(lock, old, old);++++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 1_000 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ } finally {++ child.kill();++ }++ }, 15_000);++++ it('retries a transient release deletion failure', async () => {++ const lock = path.join(dir, 'lock');++ const originalRm = fsp.rm;++ let failed = false;++ const spy = vi.spyOn(fsp, 'rm').mockImplementation((async (target: unknown, options?: unknown) => {++ if (target === lock && !failed) {++ failed = true;++ throw Object.assign(new Error('EPERM'), { code: 'EPERM' });++ }++ return (originalRm as (...args: unknown[]) => Promise<unknown>)(target, options);++ }) as typeof fsp.rm);++ try {++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });} finally {spy.mockRestore();}++ expect(fs.existsSync(lock)).toBe(false);++ });++++ it('recovers a released record after deletion stays unavailable', async () => {++ const lock = path.join(dir, 'lock');++ const originalRename = fsp.rename;++ const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (++ from: unknown,++ to: unknown,++ ) => {++ if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.release-`)) {++ throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' });++ }++ return (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);++ }) as typeof fsp.rename);++ try {++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ } finally {++ spy.mockRestore();++ }++ expect(fs.existsSync(lock)).toBe(true);++++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ });++++ it('retries when a released lock disappears during stale takeover', async () => {++ const lock = path.join(dir, 'lock');++ await fsp.writeFile(++ lock,++ JSON.stringify({++ pid: 0x7ffffffe,++ startedAt: 1,++ nonce: '00000000-0000-4000-8000-000000000001',++ state: 'released',++ }),++ 'utf8',++ );++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(lock, old, old);++++ const originalRename = fsp.rename;++++ let removedByRacingOwner = false;++ const race = vi.spyOn(fsp, 'rename').mockImplementation((async (++ from: unknown,++ to: unknown,++ ) => {++ if (++ !removedByRacingOwner++ && from === lock++ && typeof to === 'string'++ && to.startsWith(`${lock}.reclaim-`)++ ) {++ removedByRacingOwner = true;++ await fsp.rm(lock, { force: true });++ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });++ }++ return (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);++ }) as typeof fsp.rename);++ try {++ await expect(++ withCrossProcessLock(lock, { label: 'waiter', waitMs: 1_000 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ } finally {++ race.mockRestore();++ }++ expect(removedByRacingOwner).toBe(true);++ });++++ it('keeps a stale lock when process liveness cannot be proven', async () => {++ const lock = path.join(dir, 'lock');++ const identity = await __testing.getProcessIdentity(process.pid);++ if (!identity) throw new Error('current process identity unavailable in test');++ await fsp.writeFile(++ lock,++ JSON.stringify({++ pid: process.pid,++ startedAt: 1,++ nonce: 'live-owner',++ processStartIdentity: identity.key,++ state: 'held',++ }),++ 'utf8',++ );++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(lock, old, old);++ const kill = vi.spyOn(process, 'kill').mockImplementation((() => {++ throw Object.assign(new Error('liveness query unavailable'), { code: 'EACCES' });++ }) as typeof process.kill);++ try {++ await expect(++ withCrossProcessLock(++ lock,++ {++ label: 'strict',++ waitMs: 100,++ requireProcessIdentity: true,++ allowMalformedStaleTakeover: false,++ },++ async (s) => s,++ ),++ ).resolves.toEqual({ held: false, reason: 'busy' });++ } finally {++ kill.mockRestore();++ }++ expect(fs.existsSync(lock)).toBe(true);++ });++++ it.each(['unknown-format', 'bogus-state'])('keeps an unverifiable strict record fail-closed: %s', async (value) => {++ const lock = path.join(dir, 'lock');++ const identity = value === 'unknown-format' ? value : undefined;++ await fsp.writeFile(++ lock,++ JSON.stringify({++ pid: process.pid,++ startedAt: 1,++ nonce: '00000000-0000-4000-8000-000000000001',++ ...(identity ? { processStartIdentity: identity } : { state: value }),++ }),++ 'utf8',++ );++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(lock, old, old);++++ await expect(++ withCrossProcessLock(++ lock,++ { label: 'strict', waitMs: 100, requireProcessIdentity: true, allowMalformedStaleTakeover: false },++ async (s) => s,++ ),++ ).resolves.toEqual({ held: false, reason: 'busy' });++ expect(fs.existsSync(lock)).toBe(true);++ });++++ it.each([++ { label: 'missing nonce', omit: 'nonce' },++ { label: 'null nonce', nonce: null },++ { label: 'unknown nonce', nonce: 'unknown-format' },++ { label: 'missing identity', omit: 'processStartIdentity' },++ { label: 'zero identity', processStartIdentity: 'start-ms:0' },++ { label: 'negative ticks identity', processStartIdentity: '-621355968000000001' },++ { label: 'missing state', omit: 'state' },++ ])('keeps a strict record with $label fail-closed', async (variant) => {++ const lock = path.join(dir, 'lock');++ const identity = await __testing.getProcessIdentity(process.pid);++ if (!identity) throw new Error('current process identity unavailable in test');++ const record: Record<string, unknown> = {++ pid: process.pid,++ startedAt: 1,++ nonce: '00000000-0000-4000-8000-000000000001',++ processStartIdentity: identity.key,++ state: 'held',++ };++ if (variant.omit) delete record[variant.omit];++ if (Object.prototype.hasOwnProperty.call(variant, 'nonce')) record.nonce = variant.nonce;++ if (variant.processStartIdentity !== undefined) {++ record.processStartIdentity = variant.processStartIdentity;++ }++ await fsp.writeFile(lock, JSON.stringify(record), 'utf8');++ const old = new Date(Date.now() - 60_000);++ await fsp.utimes(lock, old, old);++++ await expect(++ withCrossProcessLock(++ lock,++ { label: 'strict', waitMs: 100, requireProcessIdentity: true, allowMalformedStaleTakeover: false },++ async (s) => s,++ ),++ ).resolves.toEqual({ held: false, reason: 'busy' });++ expect(fs.existsSync(lock)).toBe(true);++ });++++ it('bounds repeated successful stale takeovers by time and count', async () => {++ const lock = path.join(dir, 'lock');++ await writeStaleLock(lock);++ const originalRename = fsp.rename;++ let takeovers = 0;++ const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (++ from: unknown,++ to: unknown,++ ) => {++ const result = await (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);++ if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {++ takeovers += 1;++ await writeStaleLock(lock);++ }++ return result;++ }) as typeof fsp.rename);++ try {++ const started = performance.now();++ await expect(++ withCrossProcessLock(lock, { label: 'churn', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: false, reason: 'busy' });++ expect(performance.now() - started).toBeLessThan(1_000);++ expect(takeovers).toBe(3);++ } finally {++ spy.mockRestore();++ }++ });++++ it('publishes after the final stale takeover when the path stays empty', async () => {++ const lock = path.join(dir, 'lock');++ await writeStaleLock(lock);++ const originalRename = fsp.rename;++ let takeovers = 0;++ const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (++ from: unknown,++ to: unknown,++ ) => {++ const result = await (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);++ if (from === lock && typeof to === 'string' && to.startsWith(`${lock}.reclaim-`)) {++ takeovers += 1;++ if (takeovers < 3) await writeStaleLock(lock);++ }++ return result;++ }) as typeof fsp.rename);++ try {++ await expect(++ withCrossProcessLock(lock, { label: 'final-takeover', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ expect(takeovers).toBe(3);++ } finally {++ spy.mockRestore();++ }++ });++++ it('recovers an own reclaim gate after rename and fsync both fail', async () => {++ const lock = path.join(dir, 'lock');++ const originalOpen = fsp.open;++ const originalRename = fsp.rename;++ const openSpy = vi.spyOn(fsp, 'open').mockImplementation((async (...args: any[]) => {++ const handle = await (originalOpen as (...inner: any[]) => Promise<any>)(...args);++ const file = args[0];++ if (typeof file === 'string' && file.startsWith(`${lock}.reclaim.candidate-`)) {++ const originalSync = handle.sync.bind(handle);++ let syncCount = 0;++ handle.sync = async () => {++ syncCount += 1;++ if (syncCount >= 2) throw Object.assign(new Error('fsync unavailable'), { code: 'EIO' });++ return originalSync();++ };++ }++ return handle;++ }) as typeof fsp.open);++ const renameSpy = vi.spyOn(fsp, 'rename').mockImplementation((async (++ from: unknown,++ to: unknown,++ ) => {++ if (from === `${lock}.reclaim` && typeof to === 'string' && to.startsWith(`${lock}.reclaim.release-`)) {++ throw Object.assign(new Error('rename unavailable'), { code: 'EBUSY' });++ }++ return (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);++ }) as typeof fsp.rename);++ try {++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ } finally {++ renameSpy.mockRestore();++ openSpy.mockRestore();++ }++++ await expect(++ withCrossProcessLock(lock, { label: 'test', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ expect(fs.existsSync(`${lock}.reclaim`)).toBe(false);++ });++++ it('keeps a successor protected while the previous owner is releasing', async () => {++ const lock = path.join(dir, 'lock');++ const releaseFirstTask = deferred();++ const firstTaskStarted = deferred();++ const releaseRenameStarted = deferred();++ const allowReleaseRename = deferred();++ const secondTaskStarted = deferred();++ const releaseSecondTask = deferred();++ const originalRename = fsp.rename;++ let blockedRelease = false;++ const spy = vi.spyOn(fsp, 'rename').mockImplementation((async (++ from: unknown,++ to: unknown,++ ) => {++ if (++ !blockedRelease++ && from === lock++ && typeof to === 'string'++ && to.startsWith(`${lock}.release-`)++ ) {++ blockedRelease = true;++ releaseRenameStarted.resolve();++ await allowReleaseRename.promise;++ }++ return (originalRename as (...args: unknown[]) => Promise<unknown>)(from, to);++ }) as typeof fsp.rename);++++ try {++ const first = withCrossProcessLock(++ lock,++ { label: 'first', waitMs: 500 },++ async (status) => {++ expect(status).toEqual({ held: true });++ firstTaskStarted.resolve();++ await releaseFirstTask.promise;++ return status;++ },++ );++ await firstTaskStarted.promise;++ releaseFirstTask.resolve();++ await releaseRenameStarted.promise;++++ await expect(++ withCrossProcessLock(lock, { label: 'second', waitMs: 100 }, async (s) => s),++ ).resolves.toEqual({ held: false, reason: 'busy' });++++ allowReleaseRename.resolve();++ await expect(first).resolves.toEqual({ held: true });++++ const second = withCrossProcessLock(++ lock,++ { label: 'second', waitMs: 500 },++ async (status) => {++ expect(status).toEqual({ held: true });++ secondTaskStarted.resolve();++ await releaseSecondTask.promise;++ return status;++ },++ );++ await secondTaskStarted.promise;++++ await expect(++ withCrossProcessLock(lock, { label: 'third', waitMs: 100 }, async (s) => s),++ ).resolves.toEqual({ held: false, reason: 'busy' });++++ releaseSecondTask.resolve();++ await expect(second).resolves.toEqual({ held: true });++ } finally {++ allowReleaseRename.resolve();++ releaseFirstTask.resolve();++ releaseSecondTask.resolve();++ spy.mockRestore();++ }++ });++++ it('does not remove a successor after the predecessor path disappeared', async () => {++ const lock = path.join(dir, 'lock');++ const firstTaskStarted = deferred();++ const releaseFirstTask = deferred();++ const secondTaskStarted = deferred();++ const releaseSecondTask = deferred();++++ const first = withCrossProcessLock(++ lock,++ { label: 'first', waitMs: 500 },++ async (status) => {++ expect(status).toEqual({ held: true });++ firstTaskStarted.resolve();++ await releaseFirstTask.promise;++ return status;++ },++ );++ await firstTaskStarted.promise;++ await fsp.rm(lock, { force: true });++++ const second = withCrossProcessLock(++ lock,++ { label: 'second', waitMs: 500 },++ async (status) => {++ expect(status).toEqual({ held: true });++ secondTaskStarted.resolve();++ await releaseSecondTask.promise;++ return status;++ },++ );++ await secondTaskStarted.promise;++++ releaseFirstTask.resolve();++ await expect(first).resolves.toEqual({ held: true });++ await expect(++ withCrossProcessLock(lock, { label: 'third', waitMs: 100 }, async (s) => s),++ ).resolves.toEqual({ held: false, reason: 'busy' });++++ releaseSecondTask.resolve();++ await expect(second).resolves.toEqual({ held: true });++ });++++ it('recovers a main lock left held when release marking and gate publication fail', async () => {++ const lock = path.join(dir, 'lock');++ const originalOpen = fsp.open;++ const openSpy = vi.spyOn(fsp, 'open').mockImplementation((async (...args: any[]) => {++ const file = args[0];++ if (typeof file === 'string' && file.startsWith(`${lock}.reclaim.candidate-`)) {++ throw Object.assign(new Error('gate unavailable'), { code: 'EIO' });++ }++ const handle = await (originalOpen as (...inner: any[]) => Promise<any>)(...args);++ if (typeof file === 'string' && file.startsWith(`${lock}.candidate-`)) {++ handle.write = async () => {++ throw Object.assign(new Error('release write unavailable'), { code: 'EIO' });++ };++ }++ return handle;++ }) as typeof fsp.open);++ try {++ await expect(++ withCrossProcessLock(lock, { label: 'first', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ expect(JSON.parse(await fsp.readFile(lock, 'utf8')).state).toBe('held');++++ await expect(++ withCrossProcessLock(lock, { label: 'second', waitMs: 500 }, async (s) => s),++ ).resolves.toEqual({ held: true });++ } finally {++ openSpy.mockRestore();++ }++ });++++ it('keeps strict acquisition available when current-process identity commands fail', async () => {++ const identity = await __testing.readProcessIdentity(++ process.pid,++ async () => {++ throw new Error('identity command unavailable');++ },++ );++++ expect(identity?.startedAtMs).toEqual(expect.any(Number));++ expect(identity?.key).toMatch(/^start-ms:\d+$/);++ });++++ it('does not invent an identity for another process when OS queries fail', async () => {++ await expect(++ __testing.readProcessIdentity(++ 0x7ffffffe,++ async () => {++ throw new Error('identity command unavailable');++ },++ ),++ ).resolves.toBeNull();});});diff --cc apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.tsindex 2e67d6e899,2e67d6e899..6e7b9f06d0--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts@@@ -1493,7 -1493,7 +1493,13 @@@ describe('跨进程互斥(锁 + 清理�target: unknown,...rest: unknown[]) => {-- if (typeof target === 'string' && target === lock) {++ if (++ typeof target === 'string'++ && (++ target === lock++ || target.startsWith(`${lock}.candidate-`)++ )++ ) {// 不是 EEXIST:锁**建不出来**(EMFILE / 控制目录被 ACL 挡住)。throw Object.assign(new Error('EMFILE'), { code: 'EMFILE' });}diff --cc apps/desktop/src/main/device-link/crossProcessLock.tsindex 26a4e1bcd9,26a4e1bcd9..3dbab627a0--- a/apps/desktop/src/main/device-link/crossProcessLock.ts+++ b/apps/desktop/src/main/device-link/crossProcessLock.ts@@@ -1,181 -1,181 +1,965 @@@--/**-- * crossProcessLock —— 同一台机器上多个 Cindy 实例之间的建议性文件锁。-- * ----------------------------------------------------------------------------- * 为什么需要:dev 实例与打包实例可以共用同一个 userData(见 devStartupStatus.ts),于是-- * 「读 → 改 → 整份写回」「先扫描再删除」这类临界区在两个进程之间会互相覆盖 —— 后落位的-- * 那次赢,而另一边以为自己成功了(review: codex P1,镜像缓存的队列与清理都撞过)。-- *-- * 用 `open(lock, 'wx')` 做锁:同目录、O_EXCL 语义在 Windows / macOS / Linux 都可靠。-- *-- * 陈旧锁的接管**不能只看时间**:临界区可能包含递归删除,正常持锁跑过 10 秒完全可能。-- * 只按 mtime 抢锁会把活着的持有者挤掉,它随后还会在 finally 里删掉别人的锁。所以:-- * - 锁内容写 `{ pid, startedAt }`,持锁期间每 2 秒 touch 一次 mtime(心跳);-- * - 只有「mtime 陈旧」**且**「owner pid 已经不在」才接管 —— 共享 userData 必然同机,-- * `process.kill(pid, 0)` 是可靠的存活判定;读不到锁 / 读不出内容一律保守不接管;-- * - 等不到锁就把 `held=false` 交给调用方**自行降级**(绝不无限等待:登出 / teardown 都会-- * 经过这些临界区,卡住比降级更糟);-- * - 释放时先确认锁里还是自己的 pid,再删。-- */--++import crypto from 'node:crypto';++import { execFile } from 'node:child_process';import fsp from 'node:fs/promises';++import path from 'node:path';++import { promisify } from 'node:util';import { createLogger } from '../logger';const log = createLogger('device-link:cross-process-lock');--/** 超过这个年龄的锁**可能**是崩溃残留(还要再验 owner 存活)。 */const LOCK_STALE_MS = 10_000;--/** 抢锁最长等待;之后交给调用方降级。 */const LOCK_WAIT_MS = 3_000;const LOCK_RETRY_MS = 40;--/** 一次调用里最多接管几次陈旧锁(正常只需 1 次;更多说明有人在高频重建,该降级)。 */const MAX_TAKEOVERS = 3;--/** 持锁期间刷新 mtime 的间隔:让「陈旧」只对真正死掉的持有者成立。 */const LOCK_HEARTBEAT_MS = 2_000;++const LEGACY_PID_REUSE_TOLERANCE_MS = 2_000;++const REMOVE_RETRY_ATTEMPTS = 3;++const RELEASE_GATE_WAIT_MS = 3_000;++const execFileAsync = promisify(execFile);++++type ExecFileResult = { stdout: string };++type ExecFileRunner = (++ file: string,++ args: string[],++ options: {++ encoding: 'utf8';++ timeout: number;++ windowsHide?: boolean;++ env?: NodeJS.ProcessEnv;++ },++) => Promise<ExecFileResult>;--/**-- * 没拿到锁时**为什么**没拿到:-- * - `busy`:锁一直被别人持着(EEXIST 直到超时)→ 另一个进程正在临界区里,调用方应当避让;-- * - `unavailable`:锁根本建不出来(EMFILE / EACCES / 只读目录…)→ 无从判断有没有别人,-- * 调用方通常应当**照常做事**(best-effort),否则在这些环境里功能会被静默关掉。-- */export type LockStatus = { held: true } | { held: false; reason: 'busy' | 'unavailable' };export interface FileLockOptions {-- /** 日志里用来标识这把锁(如 'purge-queue' / 'mirror-cache')。 */label: string;-- /** 抢不到锁时最长等待毫秒数,默认 3 秒。 */waitMs?: number;++ /** Defaults to true. Set false only for legacy callers that must never reclaim. */++ allowStaleTakeover?: boolean;++ /** Security boundaries may require an OS process birth identity before publishing. */++ requireProcessIdentity?: boolean;++ /** Legacy advisory locks treated stale readable garbage as crash residue. */++ allowMalformedStaleTakeover?: boolean;++}++++interface LockRecord {++ pid: number;++ startedAt: number;++ nonce: string | null;++ processStartIdentity: string | null;++ state: 'held' | 'released';++}++++type ReadLockRecord = LockRecord | 'missing' | 'malformed' | 'unreadable';++interface MalformedLockIdentity {++ dev: number;++ ino: number;++ size: number;++ mtimeMs: number;++}++type StaleLockCandidate =++ | { kind: 'record'; record: LockRecord }++ | { kind: 'malformed'; identity: MalformedLockIdentity };++interface ProcessIdentity {++ key: string;++ startedAtMs: number | null;}++type PublishedLock = {++ handle: Awaited<ReturnType<typeof fsp.open>>;++ nonce: string;++ record: LockRecord;++};++type ReclaimGate = {++ dirPath: string;++ filePath: string;++ lock: PublishedLock;++ heartbeat: ReturnType<typeof setInterval>;++};++++let currentProcessIdentityPromise: Promise<ProcessIdentity | null> | null = null;++// A release gate whose final rename/fsync failed may still be ours. Keep its++// nonce so the same process can recover it before treating the gate as busy.++const pendingOwnRecordRecovery = new Map<string, string>();++const pendingOwnGateCleanup = new Set<string>();--/**-- * 拿着 `lockPath` 这把跨进程锁执行 `task`。`held=false` 表示没拿到(调用方自行降级)。-- * 无论是否拿到都会执行 task —— 由调用方决定"降级怎么做"。-- */export async function withCrossProcessLock<T>(lockPath: string,opts: FileLockOptions,task: (status: LockStatus) => Promise<T>,): Promise<T> {-- const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);let held = false;let reason: 'busy' | 'unavailable' = 'unavailable';-- // 接管次数上限:正常最多一次(删掉陈旧锁 → 下一轮建成功)。反复"删得掉却又立刻 EEXIST"-- // 说明有人在高频重建锁,那时该降级而不是继续跟它抢。++ let ownLock: PublishedLock | null = null;let takeovers = 0;++ let publishingAfterTakeover = false;++ const processIdentity = await getProcessIdentity(process.pid);++ // Do not charge the first process-identity probe against the caller's wait++ // budget. On Windows the initial CIM/WMIC lookup can take several seconds.++ const deadline = Date.now() + (opts.waitMs ?? LOCK_WAIT_MS);++ if (opts.requireProcessIdentity && !processIdentity) {++ return task({ held: false, reason: 'unavailable' });++ }++for (;;) {++ await recoverPendingOwnRecord(lockPath);++ if (await reclaimInProgress(lockPath)) {++ reason = 'busy';++ if (Date.now() >= deadline) break;++ await sleep(LOCK_RETRY_MS);++ continue;++ }try {-- const handle = await fsp.open(lockPath, 'wx');-- await handle-- .writeFile(JSON.stringify({ pid: process.pid, startedAt: Date.now() }), 'utf8')-- .catch(() => undefined);-- await handle.close().catch(() => undefined);++ const publishedLock = await publishLockRecord(lockPath, processIdentity?.key ?? null);++ if (!publishedLock) throw Object.assign(new Error('lock exists'), { code: 'EEXIST' });++ const { nonce } = publishedLock;++ const [published, reclaiming] = await Promise.all([++ readLockRecord(lockPath, opts.requireProcessIdentity === true),++ reclaimInProgress(lockPath),++ ]);++ if (reclaiming || typeof published === 'string' || published.nonce !== nonce) {++ await cleanupPublishedLock(lockPath, opts.label, publishedLock);++ reason = 'busy';++ if (Date.now() >= deadline) break;++ await sleep(LOCK_RETRY_MS);++ continue;++ }++ ownLock = publishedLock;held = true;break;-- } catch (err) {-- if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') {-- // 锁**建不出来**(EMFILE / EACCES / 目录不存在…):无从判断有没有别人在临界区。++ } catch (error) {++ if ((error as NodeJS.ErrnoException)?.code !== 'EEXIST') {reason = 'unavailable';break;}-- if (takeovers < MAX_TAKEOVERS && (await canTakeOverLock(lockPath))) {-- log.warn(`taking over stale ${opts.label} lock from a dead owner`);-- takeovers += 1;-- const removed = await fsp-- .rm(lockPath, { force: true })-- .then(() => true)-- .catch(() => false);-- if (removed) continue;-- // 删不掉(Windows 上 EPERM / EBUSY 最常见:别的进程还开着句柄)。原先是 catch 掉再-- // `continue`,而"陈旧 + owner 已死"的判定下一轮仍然成立 —— 于是这里会变成没有退避、-- // 没有截止时间的空转,把调用方永久卡住(review: copilot)。删不掉就当"有人在临界区"-- // 降级退出:内容写会跳过(安全方向),清理路径照常执行。-- log.warn(`${opts.label} stale lock is undeletable; proceeding in degraded mode`);++++ if (++ publishingAfterTakeover++ && (Date.now() >= deadline || takeovers >= MAX_TAKEOVERS)++ ) {reason = 'busy';break;}++ publishingAfterTakeover = false;++++ if (++ opts.allowStaleTakeover !== false &&++ takeovers < MAX_TAKEOVERS++ ) {++ const stale = await inspectStaleLock(++ lockPath,++ opts.allowMalformedStaleTakeover !== false,++ opts.requireProcessIdentity === true,++ );++ if (stale) {++ log.warn(`taking over stale ${opts.label} lock from a dead owner`);++ const takeover = await quarantineStaleLock(++ lockPath,++ stale,++ opts.requireProcessIdentity === true,++ );++ if (takeover === 'taken') {++ takeovers += 1;++ // A slow but successful stale-owner check may consume waitMs. Give++ // the caller one immediate publication attempt, then enforce the++ // deadline before considering another takeover. The final++ // takeover still gets this publication attempt if the path is now++ // empty, but a competing record cannot trigger a fourth takeover.++ publishingAfterTakeover = true;++ continue;++ }++ if (takeover === 'reclaiming' || takeover === 'changed' || takeover === 'retry') {++ reason = 'busy';++ if (Date.now() >= deadline) break;++ await sleep(LOCK_RETRY_MS);++ continue;++ }++ takeovers += 1;++ if (takeovers >= MAX_TAKEOVERS) {++ reason = 'busy';++ break;++ }++ reason = 'busy';++ break;++ }++ }++if (Date.now() >= deadline) {-- log.warn(`${opts.label} lock busy; proceeding in degraded mode`);reason = 'busy';break;}-- await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));++ await sleep(LOCK_RETRY_MS);}}++const heartbeat = held? setInterval(() => {const now = new Date();-- void fsp.utimes(lockPath, now, now).catch(() => undefined);++ void ownLock?.handle.utimes(now, now).catch(() => undefined);}, LOCK_HEARTBEAT_MS): null;heartbeat?.unref?.();++try {return await task(held ? { held: true } : { held: false, reason });} finally {if (heartbeat) clearInterval(heartbeat);-- if (held) await releaseOwnLock(lockPath, opts.label);++ if (held && ownLock) await cleanupPublishedLock(lockPath, opts.label, ownLock);}}--/** 只有「心跳早已停」且「owner 进程确实不在了」才允许接管。 */--async function canTakeOverLock(lock: string): Promise<boolean> {++function sleep(ms: number): Promise<void> {++ return new Promise((resolve) => setTimeout(resolve, ms));++}++++async function inspectStaleLock(++ lockPath: string,++ allowMalformedTakeover = false,++ requireCompleteRecord = false,++): Promise<StaleLockCandidate | null> {let stat: Awaited<ReturnType<typeof fsp.stat>>;try {-- stat = await fsp.stat(lock);-- } catch (err) {-- const code = (err as NodeJS.ErrnoException)?.code;-- // 只有"锁文件真的没了"才算可以重新抢;EACCES / EPERM 这类读不到锁的情况必须保守。-- if (code === 'ENOENT' || code === 'ENOTDIR') return true;-- return false;++ stat = await fsp.stat(lockPath);++ } catch {++ return null;}-- if (Date.now() - stat.mtimeMs <= LOCK_STALE_MS) return false;-- const owner = await readLockOwnerPid(lock);-- if (owner === 'unreadable') return false; // 读不出来 ≠ 持有者已死-- if (owner === null) return true; // 能读但不是本模块写的(陈旧残留)-- if (owner === process.pid) return true; // 本进程上一轮崩在临界区里(心跳早停)-- try {-- process.kill(owner, 0);-- return false; // owner 还活着-- } catch (err) {-- // ESRCH = 进程不在了;EPERM = 进程在但不属于当前用户(保守认为活着)-- return (err as NodeJS.ErrnoException)?.code !== 'EPERM';++ const record = await readLockRecord(lockPath, requireCompleteRecord);++ if (record === 'missing' || record === 'unreadable') return null;++ if (typeof record !== 'string' && record.state === 'released') {++ return { kind: 'record', record };++ }++ if (Date.now() - stat.mtimeMs <= LOCK_STALE_MS) return null;++ if (record === 'malformed') {++ return allowMalformedTakeover++ ? { kind: 'malformed', identity: malformedLockIdentity(stat) }++ : null;}++ const createdAtMs = Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0++ ? stat.birthtimeMs++ : null;++ return (await isRecordOwnerActive(record, createdAtMs))++ ? null++ : { kind: 'record', record };}--/**-- * 锁文件里的 owner pid。三态:number = 正常;null = 能读但不是本模块写的;-- * 'unreadable' = 读不出来(不能据此判定持有者已死)。-- */--async function readLockOwnerPid(lock: string): Promise<number | null | 'unreadable'> {++async function readLockRecord(++ lockPath: string,++ requireCompleteRecord = false,++): Promise<ReadLockRecord> {let raw: string;try {-- raw = await fsp.readFile(lock, 'utf8');-- } catch (err) {-- const code = (err as NodeJS.ErrnoException)?.code;-- if (code === 'ENOENT' || code === 'ENOTDIR') return null;++ raw = await fsp.readFile(lockPath, 'utf8');++ } catch (error) {++ const code = (error as NodeJS.ErrnoException)?.code;++ if (code === 'ENOENT' || code === 'ENOTDIR') return 'missing';return 'unreadable';}try {const parsed = JSON.parse(raw) as unknown;-- if (parsed && typeof parsed === 'object') {-- const pid = (parsed as { pid?: unknown }).pid;-- if (typeof pid === 'number' && Number.isInteger(pid) && pid > 0) return pid;++ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return 'malformed';++ const value = parsed as Record<string, unknown>;++ if (++ typeof value.pid !== 'number' ||++ !Number.isInteger(value.pid) ||++ value.pid <= 0 ||++ typeof value.startedAt !== 'number' ||++ !Number.isFinite(value.startedAt)++ ) {++ return 'malformed';++ }++ const noncePresent = Object.prototype.hasOwnProperty.call(value, 'nonce');++ const identityPresent = Object.prototype.hasOwnProperty.call(value, 'processStartIdentity');++ const statePresent = Object.prototype.hasOwnProperty.call(value, 'state');++ if (++ requireCompleteRecord++ && (++ !noncePresent++ || typeof value.nonce !== 'string'++ || !isValidNonce(value.nonce)++ || !identityPresent++ || typeof value.processStartIdentity !== 'string'++ || parseRecordedProcessStartMs(value.processStartIdentity) === null++ || !statePresent++ || (value.state !== 'held' && value.state !== 'released')++ )++ ) {++ return 'malformed';++ }++ if (++ noncePresent++ && value.nonce !== null++ && (typeof value.nonce !== 'string' || value.nonce === '')++ ) {++ return 'malformed';++ }++ if (++ identityPresent++ && value.processStartIdentity !== null++ && (++ typeof value.processStartIdentity !== 'string'++ || value.processStartIdentity === ''++ || parseRecordedProcessStartMs(value.processStartIdentity) === null++ )++ ) {++ return 'malformed';}++ if (statePresent && value.state !== 'held' && value.state !== 'released') {++ return 'malformed';++ }++ return {++ pid: value.pid,++ startedAt: value.startedAt,++ nonce: typeof value.nonce === 'string' && value.nonce !== '' ? value.nonce : null,++ processStartIdentity:++ typeof value.processStartIdentity === 'string' && value.processStartIdentity !== ''++ ? value.processStartIdentity++ : null,++ state: value.state === 'released' ? 'released' : 'held',++ };} catch {-- // 能读但不是合法 JSON:按陈旧残留处理。++ return 'malformed';++ }++}++++async function publishLockRecord(++ targetPath: string,++ processStartIdentity: string | null,++): Promise<PublishedLock | null> {++ const nonce = crypto.randomUUID();++ const candidatePath = `${targetPath}.candidate-${process.pid}-${nonce}.tmp`;++ let handle: Awaited<ReturnType<typeof fsp.open>> | null = null;++ try {++ handle = await fsp.open(candidatePath, 'wx');++ const record: LockRecord = {++ pid: process.pid,++ startedAt: Date.now(),++ nonce,++ processStartIdentity,++ state: 'held',++ };++ await handle.writeFile(JSON.stringify(record), 'utf8');++ await handle.sync();++ try {++ // A hard link publishes the already-flushed inode atomically and refuses++ // to replace an existing target on every supported desktop platform.++ await fsp.link(candidatePath, targetPath);++ } catch (error) {++ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {++ await handle.close().catch(() => undefined);++ handle = null;++ return null;++ }++ throw error;++ }++ await fsp.rm(candidatePath, { force: true }).catch(() => undefined);++ return { handle, nonce, record };++ } catch (error) {++ await handle?.close().catch(() => undefined);++ throw error;++ } finally {++ await fsp.rm(candidatePath, { force: true }).catch(() => undefined);}-- return null;}--/** 释放前确认锁里还是自己的 pid:别人接管过之后不能替他删。 */--async function releaseOwnLock(lock: string, label: string): Promise<void> {-- const owner = await readLockOwnerPid(lock);-- if (owner === 'unreadable') return; // 读不出来就别乱删别人的锁-- if (owner !== null && owner !== process.pid) {-- log.warn(`${label} lock was taken over; leaving it to its new owner`);++async function quarantineStaleLock(++ lockPath: string,++ expected: StaleLockCandidate,++ requireCompleteRecord = false,++): Promise<'taken' | 'reclaiming' | 'changed' | 'retry' | 'failed'> {++ const gate = await acquireReclaimGate(lockPath, 0);++ if (!gate) return 'reclaiming';++ const quarantinePath = `${lockPath}.reclaim-${process.pid}-${crypto.randomUUID()}`;++ let quarantineMatchesExpected = false;++ try {++ const current = await inspectStaleLock(++ lockPath,++ expected.kind === 'malformed',++ requireCompleteRecord,++ );++ if (!sameStaleCandidate(current, expected)) return 'changed';++ try {++ await fsp.rename(lockPath, quarantinePath);++ } catch (error) {++ const code = (error as NodeJS.ErrnoException).code;++ return code === 'ENOENT' || code === 'ENOTDIR' ? 'changed' : 'failed';++ }++ if (!(await pathMatchesStaleCandidate(quarantinePath, expected, requireCompleteRecord))) {++ await restoreMovedPathSafely(quarantinePath, lockPath);++ return 'retry';++ }++ quarantineMatchesExpected = true;++ return 'taken';++ } finally {++ if (quarantineMatchesExpected) await removePathWithRetry(quarantinePath);++ await releaseReclaimGate(gate);++ }++}++++async function reclaimInProgress(lockPath: string): Promise<boolean> {++ if (await legacyReclaimInProgress(lockPath)) return true;++ return (await findActiveReclaimGate(reclaimGateDirPath(lockPath))) !== null;++}++++async function legacyReclaimInProgress(lockPath: string): Promise<boolean> {++ const gatePath = `${lockPath}.reclaim`;++ let exists = true;++ try {++ await fsp.stat(gatePath);++ } catch (error) {++ const code = (error as NodeJS.ErrnoException).code;++ exists = code !== 'ENOENT' && code !== 'ENOTDIR';++ }++ if (!exists) return false;++ const expected = await inspectStaleLock(gatePath, false);++ if (!expected) return true;++++ const quarantinePath = `${gatePath}-stale-${process.pid}-${crypto.randomUUID()}`;++ try {++ await fsp.rename(gatePath, quarantinePath);++ } catch {++ return true;++ }++ let result = true;++ try {++ if (!(await pathMatchesStaleCandidate(quarantinePath, expected))) {++ await restoreMovedPathSafely(quarantinePath, gatePath);++ result = true;++ } else {++ result = false;++ }++ } finally {++ // A mismatched file is never removed here: it may be a live successor.++ if (++ await pathExists(quarantinePath)++ && await pathMatchesStaleCandidate(quarantinePath, expected)++ ) {++ await removePathWithRetry(quarantinePath);++ }++ }++ return result;++}++++function reclaimGateDirPath(lockPath: string): string {++ return `${lockPath}.reclaim.d`;++}++++async function cleanupPendingOwnGates(): Promise<void> {++ for (const file of [...pendingOwnGateCleanup]) {++ await removePathWithRetry(file);++ if (!(await pathExists(file))) pendingOwnGateCleanup.delete(file);++ }++}++++async function findActiveReclaimGate(dirPath: string): Promise<string | null> {++ let entries: string[];++ try {++ entries = await fsp.readdir(dirPath);++ } catch (error) {++ const code = (error as NodeJS.ErrnoException).code;++ return code === 'ENOENT' || code === 'ENOTDIR' ? null : dirPath;++ }++++ const active: Array<{ filePath: string; record: LockRecord }> = [];++ for (const entry of entries) {++ if (!entry.startsWith('gate-') || !entry.endsWith('.json')) continue;++ const filePath = path.join(dirPath, entry);++ let stat: Awaited<ReturnType<typeof fsp.stat>>;++ try {++ stat = await fsp.stat(filePath);++ } catch {++ continue;++ }++ const record = await readLockRecord(filePath, true);++ if (record === 'missing') continue;++ if (typeof record === 'string') return filePath;++ if (record.state === 'released') {++ await removePathWithRetry(filePath);++ continue;++ }++ const fresh = Date.now() - stat.mtimeMs <= LOCK_STALE_MS;++ const createdAtMs = Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0++ ? stat.birthtimeMs++ : null;++ if (fresh || await isRecordOwnerActive(record, createdAtMs)) {++ active.push({ filePath, record });++ } else {++ // Gate paths contain a never-reused nonce, so deleting a dead contender++ // cannot remove a successor that later acquired the same logical gate.++ await removePathWithRetry(filePath);++ }++ }++ active.sort((left, right) =>++ left.record.startedAt - right.record.startedAt++ || (left.record.nonce ?? '').localeCompare(right.record.nonce ?? '')++ || left.filePath.localeCompare(right.filePath));++ return active[0]?.filePath ?? null;++}++++async function acquireReclaimGate(++ lockPath: string,++ waitMs = RELEASE_GATE_WAIT_MS,++): Promise<ReclaimGate | null> {++ await cleanupPendingOwnGates();++ const deadline = Date.now() + waitMs;++ do {++ if (await legacyReclaimInProgress(lockPath)) {++ if (Date.now() >= deadline) return null;++ await sleep(LOCK_RETRY_MS);++ continue;++ }++++ const dirPath = reclaimGateDirPath(lockPath);++ try {++ await fsp.mkdir(dirPath, { recursive: true });++ } catch {++ return null;++ }++ const filePath = path.join(dirPath, `gate-${process.pid}-${crypto.randomUUID()}.json`);++ let lock: PublishedLock | null = null;++ try {++ lock = await publishLockRecord(++ filePath,++ (await getProcessIdentity(process.pid))?.key ?? null,++ );++ } catch {++ return null;++ }++ if (!lock) return null;++++ const heartbeat = setInterval(() => {++ const now = new Date();++ void lock?.handle.utimes(now, now).catch(() => undefined);++ }, LOCK_HEARTBEAT_MS);++ heartbeat.unref?.();++ const gate: ReclaimGate = { dirPath, filePath, lock, heartbeat };++ for (;;) {++ const winner = await findActiveReclaimGate(dirPath);++ if (winner === filePath) return gate;++ if (winner === null || Date.now() >= deadline) {++ await releaseReclaimGate(gate);++ break;++ }++ await sleep(LOCK_RETRY_MS);++ }++ if (Date.now() >= deadline) return null;++ } while (true);++}++++function sameRecord(left: LockRecord, right: LockRecord): boolean {++ return left.pid === right.pid++ && left.startedAt === right.startedAt++ && left.nonce === right.nonce++ && left.processStartIdentity === right.processStartIdentity++ && left.state === right.state;++}++++function sameLockOwner(left: LockRecord, right: LockRecord): boolean {++ return left.pid === right.pid++ && left.startedAt === right.startedAt++ && left.nonce === right.nonce++ && left.processStartIdentity === right.processStartIdentity;++}++++function malformedLockIdentity(stat: {++ dev: number | bigint;++ ino: number | bigint;++ size: number | bigint;++ mtimeMs: number;++}): MalformedLockIdentity {++ return {++ dev: Number(stat.dev),++ ino: Number(stat.ino),++ size: Number(stat.size),++ mtimeMs: stat.mtimeMs,++ };++}++++function sameMalformedLockIdentity(++ left: MalformedLockIdentity,++ right: MalformedLockIdentity,++): boolean {++ return left.dev === right.dev++ && left.ino === right.ino++ && left.size === right.size++ && left.mtimeMs === right.mtimeMs;++}++++function sameStaleCandidate(++ left: StaleLockCandidate | null,++ right: StaleLockCandidate,++): boolean {++ if (!left || left.kind !== right.kind) return false;++ if (left.kind === 'record' && right.kind === 'record') {++ return sameRecord(left.record, right.record);++ }++ return left.kind === 'malformed'++ && right.kind === 'malformed'++ && sameMalformedLockIdentity(left.identity, right.identity);++}++++async function pathMatchesStaleCandidate(++ file: string,++ expected: StaleLockCandidate,++ requireCompleteRecord = false,++): Promise<boolean> {++ if (expected.kind === 'record') {++ const moved = await readLockRecord(file, requireCompleteRecord);++ return typeof moved !== 'string' && sameRecord(moved, expected.record);++ }++ try {++ const [stat, moved] = await Promise.all([fsp.stat(file), readLockRecord(file)]);++ return moved === 'malformed'++ && sameMalformedLockIdentity(malformedLockIdentity(stat), expected.identity);++ } catch {++ return false;++ }++}++++async function isRecordOwnerActive(++ record: LockRecord,++ lockCreatedAtMs: number | null,++): Promise<boolean> {++ try {++ process.kill(record.pid, 0);++ } catch (error) {++ const code = (error as NodeJS.ErrnoException)?.code;++ if (code === 'ESRCH') return false;++ if (code === 'EPERM' || code === 'EACCES') return true;++ // Some Windows runtimes report EINVAL for signal 0. Let the process-start++ // identity query decide when possible; if it also fails, the caller below++ // remains fail-closed.++ }++ const currentIdentity = await getProcessIdentity(record.pid);++ if (!currentIdentity) return true;++ if (record.processStartIdentity) {++ return processIdentitiesMatch(record.processStartIdentity, currentIdentity);++ }++ return currentIdentity.startedAtMs === null++ || lockCreatedAtMs === null++ || currentIdentity.startedAtMs <= lockCreatedAtMs + LEGACY_PID_REUSE_TOLERANCE_MS;++}++++async function getProcessIdentity(pid: number): Promise<ProcessIdentity | null> {++ if (pid === process.pid) {++ currentProcessIdentityPromise ??= readProcessIdentity(pid);++ return currentProcessIdentityPromise;++ }++ return readProcessIdentity(pid);++}++++async function readProcessIdentity(++ pid: number,++ runCommand: ExecFileRunner = execFileAsync as ExecFileRunner,++): Promise<ProcessIdentity | null> {++ if (process.platform === 'win32') {++ const fromPowershell = await readWindowsIdentityWithPowershell(pid, runCommand);++ if (fromPowershell) return fromPowershell;++ const fromWmic = await readWindowsIdentityWithWmic(pid, runCommand);++ if (fromWmic) return fromWmic;++ return pid === process.pid ? estimateCurrentProcessIdentity() : null;++ }++ try {++ const { stdout } = await runCommand(++ 'ps',++ ['-p', String(pid), '-o', 'lstart='],++ {++ encoding: 'utf8',++ timeout: 5_000,++ env: { ...process.env, LC_ALL: 'C', TZ: 'UTC0' },++ },++ );++ const value = stdout.trim().replace(/\s+/g, ' ');++ if (!value) return pid === process.pid ? estimateCurrentProcessIdentity() : null;++ const parsed = Date.parse(`${value} UTC`);++ return processIdentityFromStartMs(parsed, value);++ } catch {++ return pid === process.pid ? estimateCurrentProcessIdentity() : null;++ }++}++++async function readWindowsIdentityWithPowershell(++ pid: number,++ runCommand: ExecFileRunner,++): Promise<ProcessIdentity | null> {++ try {++ const powershell = `${process.env.SystemRoot ?? 'C:\\Windows'}`++ + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';++ const script =++ `$p = Get-CimInstance Win32_Process -Filter \"ProcessId = ${pid}\" -ErrorAction Stop; `++ + `if ($p) { $p.CreationDate.ToUniversalTime().Ticks }`;++ const { stdout } = await runCommand(++ powershell,++ ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script],++ { encoding: 'utf8', timeout: 5_000, windowsHide: true },++ );++ const ticks = Number(stdout.trim());++ if (!Number.isFinite(ticks)) return null;++ return processIdentityFromStartMs(ticks / 10_000 - 62_135_596_800_000);++ } catch {++ return null;++ }++}++++async function readWindowsIdentityWithWmic(++ pid: number,++ runCommand: ExecFileRunner,++): Promise<ProcessIdentity | null> {++ try {++ const wmic = `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\wbem\\WMIC.exe`;++ const { stdout } = await runCommand(++ wmic,++ ['process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value'],++ { encoding: 'utf8', timeout: 5_000, windowsHide: true },++ );++ const match = stdout.match(/CreationDate=(\d{14})\.(\d{1,6})([+-]\d{3})/i);++ if (!match) return null;++ const stamp = match[1];++ const micros = match[2].padEnd(6, '0');++ const offsetMinutes = Number(match[3]);++ const localMs = Date.UTC(++ Number(stamp.slice(0, 4)),++ Number(stamp.slice(4, 6)) - 1,++ Number(stamp.slice(6, 8)),++ Number(stamp.slice(8, 10)),++ Number(stamp.slice(10, 12)),++ Number(stamp.slice(12, 14)),++ Number(micros.slice(0, 3)),++ );++ return processIdentityFromStartMs(localMs - offsetMinutes * 60_000);++ } catch {++ return null;++ }++}++++function estimateCurrentProcessIdentity(): ProcessIdentity {++ return processIdentityFromStartMs(Date.now() - process.uptime() * 1_000)!;++}++++function processIdentityFromStartMs(++ startedAtMs: number,++ legacyKey?: string,++): ProcessIdentity | null {++ if (!Number.isFinite(startedAtMs) || startedAtMs <= 0) return null;++ const normalized = Math.round(startedAtMs);++ return { key: legacyKey ?? `start-ms:${normalized}`, startedAtMs: normalized };++}++++function isValidNonce(value: string): boolean {++ return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);++}++++function parseRecordedProcessStartMs(key: string): number | null {++ const normalized = /^start-ms:(\d+)$/.exec(key);++ if (normalized) {++ const value = Number(normalized[1]);++ return value > 0 && Number.isFinite(value) ? value : null;++ }++ if (/^\d{15,}$/.test(key)) {++ const ticks = Number(key);++ const value = ticks / 10_000 - 62_135_596_800_000;++ return Number.isFinite(value) && value > 0 ? value : null;++ }++ const parsed = Date.parse(`${key} UTC`);++ return Number.isFinite(parsed) ? parsed : null;++}++++function processIdentitiesMatch(recordedKey: string, current: ProcessIdentity): boolean {++ if (recordedKey === current.key) return true;++ const recordedStartedAtMs = parseRecordedProcessStartMs(recordedKey);++ return recordedStartedAtMs !== null++ && current.startedAtMs !== null++ && Math.abs(recordedStartedAtMs - current.startedAtMs) <= LEGACY_PID_REUSE_TOLERANCE_MS;++}++++async function markReleased(lock: PublishedLock): Promise<void> {++ const released: LockRecord = { ...lock.record, state: 'released' };++ const originalText = JSON.stringify(lock.record);++ const releasedText = JSON.stringify(released);++ try {++ await writeAllAt(lock.handle, releasedText);++ await lock.handle.truncate(Buffer.byteLength(releasedText));++ await lock.handle.sync();++ lock.record = released;++ } catch (error) {++ // A partial write must never be left as the canonical lock record. Restore++ // the held record when possible; if that also fails, callers remain++ // fail-closed and retain the nonce for the next safe recovery attempt.++ try {++ await writeAllAt(lock.handle, originalText);++ await lock.handle.truncate(Buffer.byteLength(originalText));++ await lock.handle.sync();++ lock.record = { ...lock.record, state: 'held' };++ } catch (restoreError) {++ log.error('lock release record could not be restored after a short write', restoreError);++ }++ throw error;++ }++}++++async function writeAllAt(++ handle: Awaited<ReturnType<typeof fsp.open>>,++ text: string,++): Promise<void> {++ const bytes = Buffer.from(text, 'utf8');++ let offset = 0;++ while (offset < bytes.byteLength) {++ const result = await handle.write(bytes, offset, bytes.byteLength - offset, offset);++ if (result.bytesWritten <= 0) throw new Error('lock record write made no progress');++ offset += result.bytesWritten;++ }++}++++async function cleanupPublishedLock(++ lockPath: string,++ label: string,++ lock: PublishedLock,++): Promise<void> {++ const gate = await acquireReclaimGate(lockPath);++ if (!gate) {++ pendingOwnRecordRecovery.set(lockPath, lock.nonce);++ await markReleased(lock).catch((error) => {++ log.warn(`${label} lock could not be flushed before release`, error);++ });++ await lock.handle.close().catch(() => undefined);++ log.warn(`${label} lock release gate is busy; leaving a recoverable released record`);return;}-- await fsp.rm(lock, { force: true }).catch(() => undefined);++++ const releasePath = `${lockPath}.release-${process.pid}-${crypto.randomUUID()}`;++ try {++ const current = await readLockRecord(lockPath);++ if (typeof current === 'string' || !sameLockOwner(current, lock.record)) {++ await lock.handle.close().catch(() => undefined);++ log.warn(`${label} lock identity changed before release; preserving current lock`);++ return;++ }++ try {++ await markReleased(lock);++ } catch (error) {++ pendingOwnRecordRecovery.set(lockPath, lock.nonce);++ log.warn(`${label} lock could not be flushed before release`, error);++ // Keep the canonical record held until a later nonce-checked recovery.++ // Moving an uncertain record would allow another process to acquire the++ // lock without knowing whether the release state reached durable storage.++ await lock.handle.close().catch(() => undefined);++ return;++ }++ await lock.handle.close().catch(() => undefined);++ try {++ await fsp.rename(lockPath, releasePath);++ } catch {++ pendingOwnRecordRecovery.set(lockPath, lock.nonce);++ return;++ }++ const moved = await readLockRecord(releasePath);++ if (typeof moved !== 'string' && moved.nonce === lock.nonce) {++ await removePathWithRetry(releasePath);++ } else {++ log.warn(`${label} lock identity changed during release; preserving the isolated record`);++ }++ } finally {++ await releaseReclaimGate(gate);++ }++}++++async function releaseReclaimGate(gate: ReclaimGate): Promise<void> {++ clearInterval(gate.heartbeat);++ try {++ await markReleased(gate.lock);++ } catch (error) {++ log.warn('lock reclaim gate could not be flushed before release', error);++ }++ await gate.lock.handle.close().catch(() => undefined);++ await removePathWithRetry(gate.filePath);++ if (await pathExists(gate.filePath)) {++ pendingOwnGateCleanup.add(gate.filePath);++ }++ try {++ await fsp.rmdir(gate.dirPath);++ } catch {++ // Another contender may already be publishing in the directory.++ }++}++++async function recoverPendingOwnRecord(file: string): Promise<void> {++ const nonce = pendingOwnRecordRecovery.get(file);++ if (!nonce) return;++++ const gate = await acquireReclaimGate(file);++ if (!gate) return;++ try {++ const record = await readLockRecord(file);++ if (record === 'missing' || (typeof record !== 'string' && record.nonce !== nonce)) {++ pendingOwnRecordRecovery.delete(file);++ return;++ }++ if (++ typeof record === 'string'++ || record.pid !== process.pid++ || record.nonce !== nonce++ ) {++ return;++ }++++ const recoveryPath = `${file}.recover-${process.pid}-${crypto.randomUUID()}`;++ try {++ await fsp.rename(file, recoveryPath);++ } catch (error) {++ const code = (error as NodeJS.ErrnoException).code;++ if (code === 'ENOENT' || code === 'ENOTDIR') pendingOwnRecordRecovery.delete(file);++ return;++ }++++ const moved = await readLockRecord(recoveryPath);++ if (typeof moved !== 'string' && moved.pid === process.pid && moved.nonce === nonce) {++ pendingOwnRecordRecovery.delete(file);++ await removePathWithRetry(recoveryPath);++ return;++ }++++ await restoreMovedPathSafely(recoveryPath, file);++ } finally {++ await releaseReclaimGate(gate);++ }++}++++async function pathExists(file: string): Promise<boolean> {++ try {++ await fsp.stat(file);++ return true;++ } catch {++ return false;++ }++}++++/** Restore a moved record without replacing a successor that won the path. */++async function restoreMovedPathSafely(from: string, to: string): Promise<void> {++ try {++ await fsp.link(from, to);++ await removePathWithRetry(from);++ } catch (error) {++ if ((error as NodeJS.ErrnoException)?.code !== 'EEXIST') return;++ }++}++++async function removePathWithRetry(file: string): Promise<void> {++ for (let attempt = 0; attempt < REMOVE_RETRY_ATTEMPTS; attempt += 1) {++ try {++ await fsp.rm(file, { force: true });++ return;++ } catch (error) {++ const code = (error as NodeJS.ErrnoException).code;++ if (code !== 'EPERM' && code !== 'EBUSY' && code !== 'EACCES') return;++ if (attempt + 1 < REMOVE_RETRY_ATTEMPTS) await sleep(LOCK_RETRY_MS * (attempt + 1));++ }++ }}--export const __testing = { staleMs: LOCK_STALE_MS, heartbeatMs: LOCK_HEARTBEAT_MS };++export const __testing = {++ staleMs: LOCK_STALE_MS,++ heartbeatMs: LOCK_HEARTBEAT_MS,++ getProcessIdentity,++ readProcessIdentity,++ parseRecordedProcessStartMs,++ processIdentitiesMatch,++};diff --cc apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.tsindex ebea6b954d,ebea6b954d..2e5e812b2f--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthBindingClaim.test.ts@@@ -29,6 -29,6 +29,15 @@@ vi.mock('electron', () => (vi.mock('@cindy/maker-core', () => ({}));++vi.mock('../../authBoundaryQuarantine.js', async (importOriginal) => {++ const actual = await importOriginal<typeof import('../../authBoundaryQuarantine.js')>();++ return {++ ...actual,++ isGhostSkillProjectionBoundaryStableForOwner: (ownerId: string | null) =>++ ownerId === h.dataOwnerId,++ };++});++// 只覆写 getActiveAppSession(绑定判定的唯一输入);其余导出保持原实现,供// appCapabilities / providerSecretStore 等传递依赖正常加载。mode 用 'local':// 绑定逻辑只看 dataOwnerId,而 local 模式关闭网关能力,readState 的网关 key@@@ -42,6 -42,6 +51,7 @@@ vi.mock('../../appSessionState.js', asydataOwnerId: h.dataOwnerId,generation: 1,}),++ isAppSessionBoundaryPending: () => false,};});@@@ -75,6 -75,6 +85,21 @@@ function readBindingFile(bindingFile: sreturn JSON.parse(fs.readFileSync(bindingFile, 'utf8')) as Record<string, unknown>;}++function writeStableProjectionOwner(ownerId: string | null): void {++ const markerDir = path.join(os.homedir(), '.cindy');++ fs.mkdirSync(markerDir, { recursive: true });++ fs.writeFileSync(++ path.join(markerDir, 'ghost-skill-projection-boundary.json'),++ JSON.stringify({++ version: 1,++ phase: 'stable',++ ownerId,++ transitionId: 'test-transition',++ updatedAt: Date.now(),++ }),++ );++}++afterEach(() => {vi.restoreAllMocks();h.dataOwnerId = null;@@@ -85,6 -85,6 +110,7 @@@ describe('codex OAuth binding auto-claiit('binds the detected system CLI credential to the current owner within one getState call', async () => {const { bindingFile } = fixture();h.dataOwnerId = 'owner-a';++ writeStableProjectionOwner('owner-a');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();@@@ -102,6 -102,6 +128,7 @@@// 竞态残局:legacyClaimOwner 已写下,openai 名额被 false 消费。fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: 'owner-a' }));h.dataOwnerId = 'owner-a';++ writeStableProjectionOwner('owner-a');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();@@@ -122,6 -122,6 +149,7 @@@JSON.stringify({ openai: 'owner-a', legacyClaimOwner: 'owner-a' }),);h.dataOwnerId = 'owner-b';++ writeStableProjectionOwner('owner-b');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();@@@ -150,6 -150,6 +178,7 @@@),).toBe(true);h.dataOwnerId = 'owner-a';++ writeStableProjectionOwner('owner-a');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();@@@ -162,6 -162,6 +191,7 @@@// 绝不把 A 时代发起的认领写到 B 名下。B 自己的下一次 reconcile 会按 B 的规则重试。const { bindingFile } = fixture();h.dataOwnerId = 'owner-a';++ writeStableProjectionOwner('owner-a');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();@@@ -180,6 -180,6 +210,7 @@@// 认领完不补拉,供应商就停在「已连接 + 零模型」,清单要等用户打开某个面板才出现。const { bindingFile } = fixture();h.dataOwnerId = 'owner-a';++ writeStableProjectionOwner('owner-a');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();const claimed = vi.fn();@@@ -201,6 -201,6 +232,7 @@@JSON.stringify({ openai: 'owner-a', legacyClaimOwner: 'owner-a' }),);h.dataOwnerId = 'owner-b';++ writeStableProjectionOwner('owner-b');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();const claimed = vi.fn();@@@ -214,6 -214,6 +246,7 @@@// 补拉是「认领之后要做什么」,它失败不该被记成认领失败,更不该把 reconcile 链路搞挂。const { bindingFile } = fixture();h.dataOwnerId = 'owner-a';++ writeStableProjectionOwner('owner-a');const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const throwing = new DesktopCodexAuthAdapter();@@@ -234,6 -234,6 +267,7 @@@it('keeps pre-session behavior without writing any binding when no owner is committed', async () => {const { bindingFile } = fixture();++ writeStableProjectionOwner(null);const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');const adapter = new DesktopCodexAuthAdapter();diff --cc apps/desktop/src/main/maker-host/shared-global-skills.tsindex 87838143e4,87838143e4..bbec9a67d9--- a/apps/desktop/src/main/maker-host/shared-global-skills.ts+++ b/apps/desktop/src/main/maker-host/shared-global-skills.ts@@@ -34,6 -34,6 +34,8 @@@ export interface SharedGlobalSkillLinksinterface PrepareOptions {homeDir?: string;++ /** Optional owner-bound caller guard for Ghost-managed fanout. */++ assertOwnerStable?: () => void;}export interface SharedProjectSkillLinksResult {@@@ -215,7 -215,7 +217,7 @@@ async function cleanupBrokenManagedLinkif (!pointsIntoCurrentRoots && !matchesMovedProjectLink) continue;try {-- await fsp.rm(linkPath, { recursive: true, force: true });++ await fsp.unlink(linkPath);changed = true;} catch {// Broken symlink cleanup is best-effort; later link creation will report conflicts if needed.@@@ -316,6 -316,6 +318,7 @@@ async function linkEntriesIntoRootexport async function prepareSharedGlobalSkillLinks(opts: PrepareOptions = {},): Promise<SharedGlobalSkillLinksResult> {++ opts.assertOwnerStable?.();const paths = sharedGlobalSkillsPaths(opts.homeDir);await fsp.mkdir(paths.sharedSkillsDir, { recursive: true });await fsp.mkdir(paths.claudeSkillsDir, { recursive: true });diff --cc apps/desktop/src/main/mcp-integrations/__tests__/android.test.tsindex 46adfa974a,46adfa974a..eb959cfc0d--- a/apps/desktop/src/main/mcp-integrations/__tests__/android.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/android.test.ts@@@ -1,14 -1,14 +1,16 @@@import { EventEmitter } from 'node:events';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--const { existsSyncMock, outboundFetchMock, spawnMock } = vi.hoisted(() => ({++const { existsSyncMock, outboundFetchMock, spawnMock, execFileMock } = vi.hoisted(() => ({existsSyncMock: vi.fn(),outboundFetchMock: vi.fn(),spawnMock: vi.fn(),++ execFileMock: vi.fn(),}));vi.mock('node:child_process', () => ({spawn: spawnMock,++ execFile: execFileMock,}));vi.mock('node:fs', async (importOriginal) => {diff --cc apps/desktop/src/main/ownerNamespaceMigration.tsindex e3d38ab6c9,482c283990..f6445851f0--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@@ -16,9 -14,8 +16,10 @@@ importNO_LEGACY_GHOST_RECOVERY,type LegacyGhostRecoveryStatus,} from '../shared/legacyGhostRecovery.js';++import { readLegacyGhostApprovalProjection } from './cindy-brain/GhostManager.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',@@@ -57,30 -54,12 +58,33 @@@ interface ClaimMarkercomplete: boolean;}+interface LegacyGhostRecoveryMarker {- version: 1;++ version: 1 | 2;+ ownerKey: string;+ pendingIds: string[];+ /** Deterministic content failures remain inside the frozen id whitelist. */+ failedIds?: string[];++ /** Complete approval-fact digest frozen before a source directory is moved. */++ approvalProjectionSha256ById?: Record<string, 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 }>;++ unlink(file: string): Promise<void>;+ 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>;@@@ -104,8 -82,6 +108,10 @@@ export interface OwnerNamespaceMigratioconflicts: number;provisioningStateMoved?: boolean;deferredReason?: OwnerNamespaceClaimDeferredReason;+ /** Ghost directories moved before approval backfill; durable across restart. */+ recoveredIds?: string[];++ /** Expected full approval projection where the source was still available to freeze. */++ recoveredApprovalProjectionSha256ById?: Record<string, string>;}const log = createLogger('ownerNamespaceMigration');@@@ -119,6 -95,6 +125,7 @@@ const productionDeps: MigrationDeps =readFile: (file) => fs.readFile(file, 'utf-8'),writeFileExclusive: (file, text) => fs.writeFile(file, text, { encoding: 'utf-8', flag: 'wx' }),writeFile: (file, text) => fs.writeFile(file, text, 'utf-8'),++ unlink: (file) => fs.unlink(file),lstat: (file) => fs.lstat(file),readdir: (dir) => fs.readdir(dir),mkdir: async (dir) => {@@@ -152,6 -128,6 +159,33 @@@ function isMissing(error: unknown): booreturn (error as NodeJS.ErrnoException).code === 'ENOENT';}++const SHA256_HEX_RE = /^[a-f0-9]{64}$/;++++function normalizeLegacyApprovalProjectionDigests(++ value: unknown,++ pendingIds: readonly string[],++): { ok: true; digests?: Record<string, string> } | { ok: false } {++ if (value === undefined) return { ok: true };++ if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false };++ const pending = new Set(pendingIds);++ const entries = Object.entries(value as Record<string, unknown>);++ if (++ entries.some(++ ([id, digest]) =>++ !pending.has(id) || typeof digest !== 'string' || !SHA256_HEX_RE.test(digest),++ )++ ) {++ return { ok: false };++ }++ return {++ ok: true,++ digests: Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right))) as Record<++ string,++ string++ >,++ };++}++async function readMarker(deps: MigrationDeps, markerPath: string): Promise<ClaimMarker | null> {try {const parsed = JSON.parse(await deps.readFile(markerPath)) as Partial<ClaimMarker>;@@@ -169,60 -145,6 +203,69 @@@}}+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 ?? [];++ const projections = normalizeLegacyApprovalProjectionDigests(++ parsed.approvalProjectionSha256ById,++ parsed.pendingIds ?? [],++ );+ if (- parsed.version === 1 &&++ (parsed.version === 1 || parsed.version === 2) &&+ 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))++ failedIds.every((id) => parsed.pendingIds?.includes(id)) &&++ projections.ok+ ) {++ if (parsed.pendingIds.length === 0) return { kind: 'missing' };+ const marker: LegacyGhostRecoveryMarker = {- version: 1,++ version: parsed.version,+ ownerKey: parsed.ownerKey,+ pendingIds: [...new Set(parsed.pendingIds)],+ ...(failedIds.length > 0 ? { failedIds: [...new Set(failedIds)] } : {}),++ ...(projections.digests++ ? { approvalProjectionSha256ById: projections.digests }++ : {}),+ };+ 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);@@@ -755,81 -493,10 +798,83 @@@ export function getLegacyGhostRecoverySconst 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 recoveredIds = (recoveryMarker?.pendingIds ?? []).filter((id) =>++ installedTargetIds.has(id) &&++ !legacySourceIds.has(id) &&++ recoveryMarker?.approvalProjectionSha256ById?.[id] !== undefined,+ );+ 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 };@@@ -976,66 -597,6 +1021,89 @@@ export async function recoverLegacyGhos});}}+ 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;++ const recoveryMarkerNeedsVersionUpgrade = recoveryMarker?.version === 1;+ 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 approvalProjectionSha256ById = new Map<string, string>(++ Object.entries(recoveryMarker?.approvalProjectionSha256ById ?? {}),++ );+ 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();++ const targetOnlyPendingIdsWithoutFrozenDigest = (): string[] => [...pendingRecoveryIds]++ .filter((id) =>++ targetDiscoveryIds.has(id) &&++ !sourceDiscoveryIds.has(id) &&++ !approvalProjectionSha256ById.has(id)++ )++ .sort();++ const recoveredApprovalProjectionDigests = (): Record<string, string> => {++ const recovered: Record<string, string> = {};++ for (const id of recoveredTargetIds()) {++ const frozenDigest = approvalProjectionSha256ById.get(id);++ if (frozenDigest !== undefined) {++ recovered[id] = frozenDigest;++ }++ }++ return Object.fromEntries(Object.entries(recovered).sort(([left], [right]) =>++ left.localeCompare(right),++ ));++ };if (sharedRecoveryBlocked &&scopedLegacyGhosts.length === 0 &&@@@ -1078,32 -626,12 +1146,42 @@@conflicts += 1;}}- if (movableLegacyGhosts.length === 0) {- const result: OwnerNamespaceMigrationResult = {- status: conflicts > 0 ? 'partial' : 'skipped',+ 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 || recoveredIds.length > 0 ? 'partial' : 'skipped',++ const buildNoMoveResult = (): OwnerNamespaceMigrationResult => {++ const recoveredApprovalProjectionSha256ById = recoveredApprovalProjectionDigests();++ const recoveredIds = Object.keys(recoveredApprovalProjectionSha256ById);++ const effectiveConflicts = conflicts + targetOnlyPendingIdsWithoutFrozenDigest().length;++ return {++ status: effectiveConflicts > 0 || recoveredIds.length > 0 ? 'partial' : 'skipped',moved: 0,-- conflicts,- ...(recoveredIds.length > 0 ? { recoveredIds } : {}),++ conflicts: effectiveConflicts,++ ...(recoveredIds.length > 0++ ? {++ recoveredIds,++ recoveredApprovalProjectionSha256ById,++ }++ : {}),};++ };++ if (movableLegacyGhosts.length === 0 && !recoveryMarkerNeedsVersionUpgrade) {++ const result = buildNoMoveResult();recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;}@@@ -1144,19 -672,6 +1222,65 @@@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) {++ // Freeze the complete approval projection only after passive/concurrent++ // ownership has been ruled out. A source that is still in the legacy root++ // can be re-frozen on every retry, but a target-only directory can never be++ // inferred from its current mutable bytes.++ let approvalProjectionDigestsChanged = false;++ const projectionReadyLegacyGhosts: typeof movableLegacyGhosts = [];++ for (const legacy of movableLegacyGhosts) {++ try {++ const frozen = await readLegacyGhostApprovalProjection(legacy.dir, legacy.id);++ if (approvalProjectionSha256ById.get(legacy.id) !== frozen.sha256) {++ approvalProjectionSha256ById.set(legacy.id, frozen.sha256);++ approvalProjectionDigestsChanged = true;++ }++ } catch (error) {++ conflicts += 1;++ log.warn('legacy ghost recovery could not freeze approval projection', {++ id: legacy.id,++ error: error instanceof Error ? error.message : String(error),++ });++ continue;++ }++ projectionReadyLegacyGhosts.push(legacy);++ }++ movableLegacyGhosts = projectionReadyLegacyGhosts;++++ // Freeze the recovery whitelist and its projections before any rename. A++ // deferred instance must not write durable recovery state.++ if (++ (!recoveryMarkerPersisted ||++ approvalProjectionDigestsChanged ||++ recoveryMarkerNeedsVersionUpgrade) &&++ pendingRecoveryIds.size > 0 &&++ !sharedRecoveryBlocked++ ) {+ await deps.mkdir(path.dirname(recoveryMarkerPath));+ await writeLegacyGhostRecoveryMarker(deps, recoveryMarkerPath, {- version: 1,++ version: 2,+ ownerKey,+ pendingIds: [...pendingRecoveryIds].sort(),+ ...(failedRecoveryIds.size > 0 ? { failedIds: [...failedRecoveryIds].sort() } : {}),++ ...(approvalProjectionSha256ById.size > 0++ ? {++ approvalProjectionSha256ById: Object.fromEntries(++ [...approvalProjectionSha256ById.entries()].sort(([left], [right]) =>++ left.localeCompare(right),++ ),++ ),++ }++ : {}),+ });+ recoveryMarkerPersisted = true;+ }+++ if (movableLegacyGhosts.length === 0) {++ const result = buildNoMoveResult();++ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);++ return result;++ }++if (options.shouldAbort?.()) return { status: 'deferred', moved: 0, conflicts: 0 };await deps.mkdir(userDataDir);const sharedDirs = new Set(sharedLegacyGhosts.map((legacy) => legacy.dir));@@@ -1190,13 -705,11 +1314,7 @@@);}if (movableLegacyGhosts.length === 0) {- const recoveredIds = recoveredTargetIds();-- const result: OwnerNamespaceMigrationResult = {- status: conflicts > 0 || recoveredIds.length > 0 ? 'partial' : 'skipped',- status: conflicts > 0 ? 'partial' : 'skipped',-- moved: 0,-- conflicts,- ...(recoveredIds.length > 0 ? { recoveredIds } : {}),-- };++ const result = buildNoMoveResult();recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;}@@@ -1220,13 -733,11 +1338,7 @@@}movableLegacyGhosts = commandSafeLegacyGhosts;if (movableLegacyGhosts.length === 0) {- const recoveredIds = recoveredTargetIds();-- const result: OwnerNamespaceMigrationResult = {- status: conflicts > 0 || recoveredIds.length > 0 ? 'partial' : 'skipped',- status: conflicts > 0 ? 'partial' : 'skipped',-- moved: 0,-- conflicts,- ...(recoveredIds.length > 0 ? { recoveredIds } : {}),-- };++ const result = buildNoMoveResult();recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;}@@@ -1258,26 -769,6 +1370,35 @@@}}}+ 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,++ version: 2,+ ownerKey,+ pendingIds: [...pendingRecoveryIds].sort(),+ ...(failedRecoveryIds.size > 0 ? { failedIds: [...failedRecoveryIds].sort() } : {}),++ ...(approvalProjectionSha256ById.size > 0++ ? {++ approvalProjectionSha256ById: Object.fromEntries(++ [...approvalProjectionSha256ById.entries()].sort(([left], [right]) =>++ left.localeCompare(right),++ ),++ ),++ }++ : {}),+ };+ await writeLegacyGhostRecoveryMarker(deps, recoveryMarkerPath, nextRecoveryMarker);+ recoveryMarkerPersisted = true;+ }const targetRootWasMissing = (await pathType(deps, targetRoot)) === 'missing';await deps.mkdir(targetRoot);if (!hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {@@@ -1428,14 -919,6 +1549,42 @@@});break;}+ if (!hasStableLegacyGhostSourceSync(legacy)) {+ failed = true;+ conflicts += 1;+ log.warn('legacy ghost recovery refused source whose root or directory changed', {+ id: legacy.id,+ });+ continue;+ }++ const expectedApprovalProjectionSha256 = approvalProjectionSha256ById.get(legacy.id);++ if (!expectedApprovalProjectionSha256) {++ failed = true;++ conflicts += 1;++ log.warn('legacy ghost recovery refused source without a frozen approval projection', {++ id: legacy.id,++ });++ continue;++ }++ try {++ const current = await readLegacyGhostApprovalProjection(legacy.dir, legacy.id);++ if (current.sha256 !== expectedApprovalProjectionSha256) {++ failed = true;++ conflicts += 1;++ log.warn('legacy ghost recovery refused source whose approval projection changed', {++ id: legacy.id,++ });++ continue;++ }++ } catch (error) {++ failed = true;++ conflicts += 1;++ log.warn('legacy ghost recovery could not re-read the frozen approval projection', {++ id: legacy.id,++ error: error instanceof Error ? error.message : String(error),++ });++ continue;++ }try {await deps.rename(legacy.dir, target);moved += 1;@@@ -1508,106 -990,19 +1657,144 @@@}}}- const recoveredIds = recoveredTargetIds();++ const recoveredApprovalProjectionSha256ById = recoveredApprovalProjectionDigests();++ const recoveredIds = Object.keys(recoveredApprovalProjectionSha256ById);++ const effectiveConflicts = conflicts + targetOnlyPendingIdsWithoutFrozenDigest().length;const result: OwnerNamespaceMigrationResult = {-- status: failed || conflicts > 0 ? 'partial' : 'migrated',++ status: failed || effectiveConflicts > 0 ? 'partial' : 'migrated',moved,-- conflicts,++ conflicts: effectiveConflicts,...(provisioningStateMoved ? { provisioningStateMoved: true } : {}),...(concurrentRecoveryInterrupted? { deferredReason: 'concurrent-live-instances' as const }: {}),- ...(recoveredIds.length > 0 ? { recoveredIds } : {}),++ ...(recoveredIds.length > 0++ ? {++ recoveredIds,++ recoveredApprovalProjectionSha256ById,++ }++ : {}),};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 ?? [];++ const projections = normalizeLegacyApprovalProjectionDigests(++ parsed.approvalProjectionSha256ById,++ parsed.pendingIds ?? [],++ );+ if (- parsed.version === 1 &&++ (parsed.version === 1 || parsed.version === 2) &&+ 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))++ failedIds.every((id) => parsed.pendingIds?.includes(id)) &&++ projections.ok+ ) {++ if (parsed.pendingIds.length === 0) return { kind: 'missing' };+ return { kind: 'ready', marker: {- version: 1,++ version: parsed.version,+ ownerKey,+ pendingIds: [...new Set(parsed.pendingIds)],+ ...(failedIds.length > 0 ? { failedIds: [...new Set(failedIds)] } : {}),++ ...(projections.digests++ ? { approvalProjectionSha256ById: projections.digests }++ : {}),+ } };+ }+ 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;++ if (pendingIds.length === 0) {++ try {++ await deps.unlink(markerPath);++ } catch (error) {++ if (isMissing(error)) return;++ await writeLegacyGhostRecoveryMarker(deps, markerPath, {++ version: 2,++ ownerKey,++ pendingIds: [],++ });++ }++ return;++ }+ await writeLegacyGhostRecoveryMarker(deps, markerPath, {- version: 1,++ version: 2,+ ownerKey,+ pendingIds,+ ...(marker.failedIds?.length+ ? { failedIds: marker.failedIds.filter((id) => !acknowledged.has(id)) }+ : {}),++ ...(marker.approvalProjectionSha256ById++ ? {++ approvalProjectionSha256ById: Object.fromEntries(++ Object.entries(marker.approvalProjectionSha256ById).filter(++ ([id]) => !acknowledged.has(id),++ ),++ ),++ }++ : {}),+ });+}+async function pathType(deps: MigrationDeps,file: string,diff --cc apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.tsindex d43d88f0c4,d43d88f0c4..9763d5c121--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts@@@ -14,6 -14,6 +14,10 @@@ const installServiceMocks = vi.hoisted(}));vi.mock('electron', () => ({++ app: {++ isPackaged: false,++ getPath: vi.fn(() => '/tmp/cindy-skillhub-test'),++ },BrowserWindow: {fromWebContents: vi.fn(() => ({ isDestroyed: () => false })),getAllWindows: vi.fn(() => []),@@@ -36,6 -36,6 +40,10 @@@ vi.mock('../../authManager', () => (getCurrentDataOwnerId: vi.fn(() => 'local-v1'),}));++vi.mock('../../appSessionState', () => ({++ isAppSessionBoundaryPending: vi.fn(() => false),++}));++const ensureReady = vi.fn();const getRawDb = vi.fn(() => ({ id: 'db' }));vi.mock('../../localDb', () => ({diff --cc apps/desktop/src/main/utils/__tests__/readBoundedFile.test.tsindex d3de6490e2,d3de6490e2..6baf385e1a--- a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts+++ b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts@@@ -11,6 -11,6 +11,7 @@@ import { afterEach, beforeEach, describimport {GHOST_MANIFEST_MAX_BYTES,++ readBoundedFileFollowLinks,readBoundedFileNoFollow,readBoundedFileNoFollowSync,} from '../readBoundedFile';@@@ -26,6 -26,6 +27,31 @@@ afterEach(async () =>});describe('readBoundedFileNoFollow', () => {++ it('opens untrusted paths in non-blocking mode before checking the file type', async () => {++ const file = path.join(workDir, 'plain.json');++ await fs.promises.writeFile(file, '{"ok":1}');++ const realOpen = fs.promises.open;++ const flags: number[] = [];++ const spy = vi.spyOn(fs.promises, 'open').mockImplementation((async (++ ...args: Parameters<typeof fs.promises.open>++ ) => {++ flags.push(Number(args[1]));++ return realOpen(...args);++ }) as typeof fs.promises.open);++++ try {++ await expect(readBoundedFileNoFollow(file, 1024)).resolves.not.toBeNull();++ await expect(readBoundedFileFollowLinks(file, 1024)).resolves.not.toBeNull();++ } finally {++ spy.mockRestore();++ }++++ expect(flags).toHaveLength(2);++ const nonBlockingFlag = fs.constants.O_NONBLOCK ?? 0;++ expect(flags.every((flag) => (flag & nonBlockingFlag) === nonBlockingFlag))++ .toBe(true);++ });++it('普通文件按实际字节返回,超限返回 null', async () => {const small = path.join(workDir, 'small.json');await fs.promises.writeFile(small, '{"ok":true}');@@@ -201,6 -201,6 +227,28 @@@});describe('readBoundedFileNoFollowSync', () => {++ it('opens untrusted paths in non-blocking mode before checking the file type', async () => {++ const file = path.join(workDir, 'plain.json');++ await fs.promises.writeFile(file, '{"ok":1}');++ const realOpenSync = fs.openSync;++ let flags = 0;++ const spy = vi.spyOn(fs, 'openSync').mockImplementation(((++ ...args: Parameters<typeof fs.openSync>++ ) => {++ flags = Number(args[1]);++ return realOpenSync(...args);++ }) as typeof fs.openSync);++++ try {++ expect(readBoundedFileNoFollowSync(file, 1024)).not.toBeNull();++ } finally {++ spy.mockRestore();++ }++++ const nonBlockingFlag = fs.constants.O_NONBLOCK ?? 0;++ expect(flags & nonBlockingFlag).toBe(nonBlockingFlag);++ });++it('限量与回退闸语义和异步变体一致', async () => {const file = path.join(workDir, 'plain.json');await fs.promises.writeFile(file, '{"ok":1}');@@@ -221,3 -221,3 +269,26 @@@expect(readBoundedFileNoFollowSync(link, 1024, { noFollowFlag: null })).toBeNull();});});++++describe('readBoundedFileNoFollowSync mutation guard', () => {++ it('rejects a file that changes while being read', async () => {++ const file = path.join(workDir, 'mutating.json');++ await fs.promises.writeFile(file, '{"ok":1}');++ const realReadSync = fs.readSync;++ let mutated = false;++ const spy = vi.spyOn(fs, 'readSync').mockImplementation(((fd, buffer, offset, length, position) => {++ const bytesRead = (realReadSync as typeof fs.readSync)(fd, buffer, offset, length, position);++ if (!mutated && bytesRead > 0) {++ mutated = true;++ fs.writeFileSync(file, '{"ok":2,"mutated":true}');++ }++ return bytesRead;++ }) as typeof fs.readSync);++++ try {++ expect(() => readBoundedFileNoFollowSync(file, 1024)).toThrow(/changed while being read/);++ } finally {++ spy.mockRestore();++ }++ });++});diff --cc apps/desktop/src/main/utils/readBoundedFile.tsindex 1a844e9301,1a844e9301..e2da81b72c--- a/apps/desktop/src/main/utils/readBoundedFile.ts+++ b/apps/desktop/src/main/utils/readBoundedFile.ts@@@ -52,6 -52,6 +52,24 @@@ function sameInode(a: fs.BigIntStats, breturn a.dev === b.dev && a.ino === b.ino;}++function sameStableFileState(before: fs.BigIntStats, after: fs.BigIntStats): boolean {++ if (!after.isFile()) return false;++ if (before.dev !== 0n && before.ino !== 0n && after.dev !== 0n && after.ino !== 0n) {++ if (!sameInode(before, after)) return false;++ }++ return (++ before.size === after.size &&++ before.mtimeNs === after.mtimeNs &&++ before.ctimeNs === after.ctimeNs++ );++}++++function changedWhileReadingError(): NodeJS.ErrnoException {++ const error = new Error('source file changed while being read') as NodeJS.ErrnoException;++ error.code = 'EIO';++ return error;++}++/*** 在已打开句柄上循环读满已校验的长度。网络盘/FUSE 上单次 read() 不保证填满* 请求区间,单次读会把合法文件截断成解析失败。EOF 早于已校验长度(并发截断)@@@ -89,6 -89,6 +107,23 @@@ async function verifyStillWithinRoot}}++function verifyStillWithinRootSync(++ handleStat: fs.BigIntStats,++ filePath: string,++ realRoot: string,++): boolean {++ try {++ const [pathStat, realFilePath] = [++ fs.statSync(filePath, { bigint: true }),++ fs.realpathSync(filePath),++ ];++ if (!sameInode(pathStat, handleStat)) return false;++ return isWithinRoot(realFilePath, realRoot);++ } catch {++ return false;++ }++}++/*** 读取一个"必须是普通文件"的文件,拒绝符号链接,限量读取。*@@@ -112,7 -112,7 +147,7 @@@ export async function readBoundedFileNo: (fs.constants.O_NOFOLLOW ?? null);const handle = await fs.promises.open(filePath,-- fs.constants.O_RDONLY | (noFollow ?? 0),++ fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0) | (noFollow ?? 0),);try {const stat = await handle.stat({ bigint: true });@@@ -131,7 -131,7 +166,17 @@@if (options?.containWithin !== undefined) {if (!(await verifyStillWithinRoot(stat, filePath, options.containWithin))) return null;}-- return await readToLength(handle, Number(stat.size));++ const bytes = await readToLength(handle, Number(stat.size));++ const after = await handle.stat({ bigint: true });++ if (bytes.byteLength !== Number(stat.size) || !sameStableFileState(stat, after)) {++ throw changedWhileReadingError();++ }++ if (options?.containWithin !== undefined) {++ if (!(await verifyStillWithinRoot(after, filePath, options.containWithin))) {++ throw changedWhileReadingError();++ }++ }++ return bytes;} finally {await handle.close();}@@@ -147,14 -147,14 +192,27 @@@ export async function readBoundedFileFomaxBytes: number,options?: Pick<ReadBoundedFileOptions, 'containWithin'>,): Promise<Buffer | null> {-- const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY);++ const handle = await fs.promises.open(++ filePath,++ fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0),++ );try {const stat = await handle.stat({ bigint: true });if (!stat.isFile() || Number(stat.size) > maxBytes) return null;if (options?.containWithin !== undefined) {if (!(await verifyStillWithinRoot(stat, filePath, options.containWithin))) return null;}-- return await readToLength(handle, Number(stat.size));++ const bytes = await readToLength(handle, Number(stat.size));++ const after = await handle.stat({ bigint: true });++ if (bytes.byteLength !== Number(stat.size) || !sameStableFileState(stat, after)) {++ throw changedWhileReadingError();++ }++ if (options?.containWithin !== undefined) {++ if (!(await verifyStillWithinRoot(after, filePath, options.containWithin))) {++ throw changedWhileReadingError();++ }++ }++ return bytes;} finally {await handle.close();}@@@ -173,7 -173,7 +231,10 @@@ export function readBoundedFileNoFollowoptions?.noFollowFlag !== undefined? options.noFollowFlag: (fs.constants.O_NOFOLLOW ?? null);-- const fd = fs.openSync(filePath, fs.constants.O_RDONLY | (noFollow ?? 0));++ const fd = fs.openSync(++ filePath,++ fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0) | (noFollow ?? 0),++ );try {const stat = fs.fstatSync(fd, { bigint: true });if (!stat.isFile() || Number(stat.size) > maxBytes) return null;@@@ -188,23 -188,23 +249,25 @@@if (!sameInode(linkStat, stat)) return null;}if (options?.containWithin !== undefined) {-- try {-- const pathStat = fs.statSync(filePath, { bigint: true });-- const realFilePath = fs.realpathSync(filePath);-- if (!sameInode(pathStat, stat)) return null;-- if (!isWithinRoot(realFilePath, options.containWithin)) return null;-- } catch {-- return null;-- }++ if (!verifyStillWithinRootSync(stat, filePath, options.containWithin)) return null;}const size = Number(stat.size);const buffer = Buffer.alloc(size);let offset = 0;while (offset < size) {const bytesRead = fs.readSync(fd, buffer, offset, size - offset, offset);-- if (bytesRead === 0) break;++ if (bytesRead === 0) throw changedWhileReadingError();offset += bytesRead;}++ const after = fs.fstatSync(fd, { bigint: true });++ if (offset !== size || !sameStableFileState(stat, after)) {++ throw changedWhileReadingError();++ }++ if (options?.containWithin !== undefined) {++ if (!verifyStillWithinRootSync(after, filePath, options.containWithin)) {++ throw changedWhileReadingError();++ }++ }return buffer.subarray(0, offset);} finally {fs.closeSync(fd);diff --cc apps/desktop/src/renderer/components/settings/UserProfileCard.tsxindex 0d73944461,0d73944461..13bd342ce1--- a/apps/desktop/src/renderer/components/settings/UserProfileCard.tsx+++ b/apps/desktop/src/renderer/components/settings/UserProfileCard.tsx@@@ -53,7 -53,7 +53,12 @@@ export function UserProfileCard()}, [orgLogoUrl]);const handleLocalSignIn = async () => {-- await exitLocalMode();++ try {++ await exitLocalMode();++ } catch {++ // Continue to the login recovery surface; main remains fail closed while++ // the durable owner transition is incomplete.++ }navigate('/login');};diff --cc apps/desktop/src/renderer/hooks/useSignInToCindy.tsindex 7fcb487b97,7fcb487b97..8dda440713--- a/apps/desktop/src/renderer/hooks/useSignInToCindy.ts+++ b/apps/desktop/src/renderer/hooks/useSignInToCindy.ts@@@ -21,7 -21,7 +21,14 @@@ export function useSignInToCindy(): ()const navigate = useNavigate();return useCallback(async () => {-- if (mode === 'local') await exitLocalMode();++ if (mode === 'local') {++ try {++ await exitLocalMode();++ } catch {++ // The login route is also the recovery surface when the durable owner++ // transition is pending. Do not leave the sign-in action as a no-op.++ }++ }navigate('/login');}, [mode, exitLocalMode, navigate]);}