Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

WIP: harden plugin approval migration and recovery

Yuewei-LLa866332ef81c
diff --git a/apps/desktop/src/main/__tests__/accountDeletionIpc.test.ts b/apps/desktop/src/main/__tests__/accountDeletionIpc.test.ts
index 89360eacfd..561aea155b 100644
--- a/apps/desktop/src/main/__tests__/accountDeletionIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/accountDeletionIpc.test.ts
@@ -30,6 +30,7 @@ function createDeps(overrides: Partial<AccountDeletionIpcDeps> = {}): AccountDel
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),
logWarn: vi.fn(),
@@ -45,6 +46,10 @@ describe('account deletion IPC handlers', () => {
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');
}),
@@ -60,7 +65,13 @@ describe('account deletion IPC handlers', () => {
});
expect(result).toEqual({ success: true, value: pendingStatus });
- expect(order).toEqual(['confirm', 'teardown', 'clear-local']);
+ expect(order).toEqual([
+ 'confirm',
+ 'begin-boundary',
+ 'teardown',
+ 'clear-local',
+ 'release-boundary',
+ ]);
});
it('still clears local auth when post-confirm teardown reports a non-fatal failure', async () => {
@@ -80,6 +91,25 @@ describe('account deletion IPC handlers', () => {
);
});
+ it('always releases the account boundary when local session clearing throws', async () => {
+ const releaseBoundary = vi.fn();
+ const error = new Error('local auth store unavailable');
+ const deps = createDeps({
+ beginAccountBoundary: vi.fn().mockReturnValue(releaseBoundary),
+ clearLocalSession: vi.fn().mockImplementation(() => {
+ throw error;
+ }),
+ });
+
+ await expect(
+ createAccountDeletionIpcHandlers(deps).confirm({
+ challengeId: 'challenge-id',
+ code: '123456',
+ }),
+ ).rejects.toThrow(error);
+ expect(releaseBoundary).toHaveBeenCalledOnce();
+ });
+
it('preserves auth-server failure codes and leaves the local session intact', async () => {
const deps = createDeps({
confirm: vi
@@ -97,6 +127,7 @@ describe('account deletion IPC handlers', () => {
code: 'ACCOUNT_DELETION_CHALLENGE_INVALID',
});
expect(deps.teardownAccountBoundary).not.toHaveBeenCalled();
+ expect(deps.beginAccountBoundary).not.toHaveBeenCalled();
expect(deps.clearLocalSession).not.toHaveBeenCalled();
});
@@ -112,6 +143,7 @@ describe('account deletion IPC handlers', () => {
}),
).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',
diff --git a/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts b/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts
new file mode 100644
index 0000000000..829d33d298
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/ghostAccountBoundaryOrdering.test.ts
@@ -0,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> {',
+ );
+ 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();');
+
+ 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 --git a/apps/desktop/src/main/accountDeletionIpc.ts b/apps/desktop/src/main/accountDeletionIpc.ts
index c4a0f4df61..98244313f8 100644
--- a/apps/desktop/src/main/accountDeletionIpc.ts
+++ b/apps/desktop/src/main/accountDeletionIpc.ts
@@ -31,6 +31,7 @@ export interface AccountDeletionIpcDeps {
clearReceipt(): void;
consumeRestoredNotice(): boolean;
isConfirmedLocalSessionCurrent(): boolean;
+ beginAccountBoundary(): () => void;
teardownAccountBoundary(): Promise<void>;
clearLocalSession(): boolean;
logWarn(message: string, error?: unknown): void;
@@ -108,15 +109,23 @@ export function createAccountDeletionIpcHandlers(
return { success: true, value: status };
}
- // Teardown failures are non-fatal here: keeping the initiator logged in
- // would be more misleading and less safe than completing local logout.
+ // 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();
try {
- await deps.teardownAccountBoundary();
- } 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');
+ // 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()) {
+ deps.logWarn('local auth identity changed during account deletion teardown; skip clear');
+ }
+ } finally {
+ releaseBoundary();
}
return { success: true, value: status };
})();
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 90cdd12574..fa45cd5681 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -619,6 +619,7 @@ import {
getGhostCindySlot,
getGhostManager,
getGhostSessionActivityTracker,
+ interruptGhostCallsForAccountBoundary,
isGhostAvailableForActiveSession,
refreshGhostLocalization,
registerGhostIpc,
@@ -925,6 +926,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
// 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();
suspendAllGhosts();
// Personal IM channels have the same DB boundary. Relogin restarts them from
@@ -3704,6 +3706,7 @@ const registerIpcHandlers = () => {
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 --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 2a190c453d..c3abfcaec3 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -23,12 +23,10 @@ import {
type GhostTrustInfo,
type InstalledGhost,
} from '../../shared/ghost.js';
-import {
- verifyGhostZipSignatures,
- type GhostTrustRegistry,
-} from './ghostSignature.js';
+import { verifyGhostZipSignatures, type GhostTrustRegistry } from './ghostSignature.js';
import { isPathInsideDir } from './dirDeposit.js';
import {
+ classifyGhostDirEntry,
classifyGhostDirEntrySync,
collectGhostContentFiles,
hashGhostContentBuffers,
@@ -79,16 +77,26 @@ export interface GhostManagerOptions {
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;
@@ -118,6 +126,64 @@ export type UninstallRejection =
| { 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;
+ localeResources: Record<string, GhostManifestLocaleResource>;
+ iconDataUrl?: string;
+ skillContentSha256: Record<string, string>;
+}
+
+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>;
+}
+
/**
* 插件仓库的 main 端管理者:一个插件一个内容目录(rootDir/<id>/),Host
* receipt 才是 manifest / trust / enabled / revision 的授权事实。
@@ -135,7 +201,13 @@ export type UninstallRejection =
*/
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。
*
@@ -145,6 +217,8 @@ export class GhostManager {
* 隔离,始终 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 级
@@ -158,24 +232,125 @@ export class GhostManager {
}
constructor(private readonly options: GhostManagerOptions) {
- this.receiptStore = new GhostInstallReceiptStore(
- options.getStateDir ??
- (() => {
- const root = path.resolve(options.getRootDir());
- return path.join(path.dirname(root), `${path.basename(root)}-install-state`);
- }),
- );
- const contentRoot = path.resolve(options.getRootDir());
- const stateRoot = this.receiptStore.rootDir();
+ 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(contentRoot, stateRoot) ||
- isPathInsideDir(stateRoot, contentRoot)
+ 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 的启动期迁移同一先例)。
@@ -193,59 +368,166 @@ export class GhostManager {
* `.cindy-installing-*` staging 残留一律回收(从未发布)。
*/
private recoverInterruptedMutationsSync(): void {
- const root = this.options.getRootDir();
+ const root = this.contentRootDir();
// 1) 标记驱动恢复(权威)。
const handledBackupNames = new Set<string>();
- for (const id of this.receiptStore.listPendingMutationIdsSync()) {
- const marker = this.receiptStore.readPendingMutationSync(id);
+ 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) {
- // 标记读不出:它只驱动恢复,读不出就无从据它动盘,清掉(下次启动靠内容判定)。
- this.receiptStore.clearPendingMutationSync(id);
- continue;
- }
- const approval = this.receiptStore.read(id);
if (marker.kind === 'uninstall') {
// 卸载崩在半途:把批准与内容目录都删净(幂等,顺序无关)。撤批准已在卸载时
// 先行,这里兜住"receipt 或目录仍残留"的任意组合 —— 收尾后该 id 干净消失。
- this.receiptStore.removeSync(id);
- if (this.isRealDirChild(root, id)) {
- fs.rmSync(finalDir, { recursive: true, force: true });
+ 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);
}
- } else if (marker.kind === 'install') {
- // 未提交装入(无已批准 receipt)= 不完整安装,删 finalDir;有已批准 receipt = 完整
- // 安装,保留(绝不删有有效批准的插件)。只删真目录,junction/链接跳过(避免穿透)。
- if (approval.state !== 'approved' && this.isRealDirChild(root, id)) {
+ this.receiptStore.removeSync(id);
+ if (this.recoveryEntryKind(finalDir) === 'directory') {
fs.rmSync(finalDir, { recursive: true, force: true });
}
} else {
- handledBackupNames.add(marker.backupDirName);
- const backupPath = path.join(root, marker.backupDirName);
- const committed =
- approval.state === 'approved' &&
- approval.receipt.packageSha256 === marker.packageSha256;
- if (committed) {
- fs.rmSync(backupPath, { recursive: true, force: true }); // 陈旧旧字节
- } else {
- // 回滚:finalDir 可能是未提交新字节,删;backup 若在则搬回(旧字节+旧 receipt)。
- if (this.isRealDirChild(root, id)) {
+ 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 committed =
+ approval.state === 'approved' &&
+ approval.receipt.packageSha256 === marker.packageSha256;
+ if (committed && marker.clearBuiltinTombstone) {
+ if (!this.options.clearBuiltinTombstone) {
+ throw new Error('builtin install recovery has no tombstone clearer');
+ }
+ this.options.clearBuiltinTombstone(id);
+ }
+ if (!committed && this.recoveryEntryKind(finalDir) === 'directory') {
fs.rmSync(finalDir, { recursive: true, force: true });
}
- if (this.isBackupDir(backupPath)) fs.renameSync(backupPath, finalDir);
+ } else {
+ handledBackupNames.add(marker.backupDirName);
+ const backupPath = path.join(root, marker.backupDirName);
+ const committed =
+ approval.state === 'approved' &&
+ approval.receipt.packageSha256 === marker.packageSha256;
+ if (committed) {
+ const backupKind = this.recoveryEntryKind(backupPath);
+ 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)。
+ const backupKind = this.recoveryEntryKind(backupPath);
+ const finalKind = this.recoveryEntryKind(finalDir);
+ // 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) {
// 动盘失败:留着标记,下次启动幂等重试。
- (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),
- });
+ 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 {
@@ -254,13 +536,13 @@ export class GhostManager {
return; // 根目录还不存在 = 没装过任何插件
}
const backups = entries.filter(
- (entry) =>
- entry.name.startsWith('.cindy-updating-') && !handledBackupNames.has(entry.name),
+ (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;
@@ -276,33 +558,65 @@ export class GhostManager {
const otherMatch = /^\.cindy-updating-(.+)-[0-9a-f]{8}$/.exec(other.name);
return otherMatch !== null && otherMatch[1] === id;
});
- if (fs.existsSync(finalDir)) {
+ 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,
+ 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),
- });
+ (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,
+ (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) {
@@ -324,12 +638,13 @@ export class GhostManager {
}
}
- /** backup 路径是否真目录(搬回前确认,不跟随链接)。 */
- private isBackupDir(backupPath: string): boolean {
+ /** Recovery distinguishes a missing path from transiently unreadable state. */
+ private recoveryEntryKind(absPath: string): GhostDirEntryKind | 'missing' {
try {
- return classifyGhostDirEntrySync(backupPath) === 'directory';
- } catch {
- return false;
+ return classifyGhostDirEntrySync(absPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 'missing';
+ throw error;
}
}
@@ -367,7 +682,7 @@ export class GhostManager {
/** Forge 等 Host 能力必须排除的受管根(内容根 + 批准状态根)。 */
managedRootDirs(): string[] {
- return [path.resolve(this.options.getRootDir()), this.receiptStore.rootDir()];
+ return [this.contentRootDir(), this.receiptStore.rootDir()];
}
approvalStateRoot(): string {
@@ -383,7 +698,35 @@ export class GhostManager {
* setEnabled(true) 成功写 receipt 一条路),与随包对账的合并规则同向。
*/
private effectiveEnabled(dir: string, receiptEnabled: boolean): boolean {
- return receiptEnabled && !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE));
+ 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;
+ }
+ }
+
+ 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, '');
}
/**
@@ -394,6 +737,9 @@ export class GhostManager {
* 正是本 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: '批准状态已被判定不可信(撤销失败)' };
}
@@ -408,6 +754,7 @@ export class GhostManager {
* 含非普通条目或字节不符一律 false,让对账器撤掉已有链接并拒绝新建。
*/
async verifyApprovedSkillSnapshot(ghost: InstalledGhost): Promise<boolean> {
+ this.ensureCurrentOwnerContextSync();
if (
ghost.approval.state !== 'approved' ||
!ghost.manifest.skill?.items.length ||
@@ -416,10 +763,7 @@ export class GhostManager {
return false;
}
const current = this.readApproval(ghost.manifest.id);
- if (
- current.state !== 'approved' ||
- current.receipt.revision !== ghost.approval.revision
- ) {
+ if (current.state !== 'approved' || current.receipt.revision !== ghost.approval.revision) {
return false;
}
const expectedRoot = this.receiptStore.skillSnapshotRoot(
@@ -432,8 +776,17 @@ export class GhostManager {
return this.receiptStore.skillSnapshotMatchesReceipt(current.receipt, expectedRoot);
}
- /** Serialize content-directory and approval-receipt mutations as one Host transaction lane. */
- async runExclusiveMutation<T>(operation: () => Promise<T>): Promise<T> {
+ /**
+ * 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) => {
@@ -441,9 +794,60 @@ export class GhostManager {
});
this.mutationTail = previous.then(() => gate);
await previous;
+ let capabilityActive = true;
try {
- return await operation();
+ 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();
}
}
@@ -492,11 +896,11 @@ export class GhostManager {
// 1) 台账 completed(或存在但读不出)= 迁过,不再迁;in-progress = 上一轮中途
// 崩溃,按钉死的 pendingIds 续跑 —— receipt 首写自动落台账的守卫(见
// receiptStore.write)只在"完全没有台账"时动笔,不会把 in-progress 焊死。
- // 2) 首轮(无台账)时,状态根已有任何**有效** receipt = 新模型已在本机运转过,
- // 此后缺某个 receipt 只能是删除,不迁(补写 completed 台账把门关死);损坏/
- // 旧 schema 的 receipt 不算"活动过" —— 它们正是 §5 要求本轮治愈的对象。
- // 续跑轮**不适用**本判据:上一轮已写出的 receipt 就是"有效 receipt",拿它关门
- // 正是 crash 不安全的成因。续跑的防滥用由 pendingIds 白名单承担。
+ // 2) 首轮必须先扫描完整安装根,不能因**任意一个**有效 receipt 提前关门。#1080
+ // 曾经写出 receipt 却没有 migration ledger;那类历史 mixed 状态里 A 已批准、B
+ // 仍是 legacy,提前 completed 会让 B 永久失效。新代码通过 receipt 提交前先写
+ // ledger 保证不再自然产生这种状态;能删 ledger 的状态根写者本就能伪造 receipt,
+ // 不属于安装根可变这一条威胁模型新增的能力。
// 之所以"安装根为空/未诞生时不落台账":为 owner 命名空间的 legacy 恢复流程留门
// (它会在之后才把旧目录搬进来);这个留门被"装一个插件→删 receipt"利用的路由
// 第 2 道判据 + receipt 首写自动落台账挡住。
@@ -515,17 +919,8 @@ export class GhostManager {
const resumeLedger = this.receiptStore.readMigrationLedger();
const resumePending =
resumeLedger?.state === 'in-progress' ? new Set(resumeLedger.pendingIds ?? []) : null;
- if (!resumePending && this.receiptStore.hasAnyValidReceipt()) {
- await this.receiptStore.writeMigrationLedger({
- version: 1,
- migratedAt: new Date().toISOString(),
- migratedIds: [],
- state: 'completed',
- });
- return result;
- }
- const root = this.options.getRootDir();
+ const root = this.contentRootDir();
let entries: fs.Dirent[] = [];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
@@ -544,7 +939,13 @@ export class GhostManager {
// 先收候选、后动笔: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;
@@ -562,34 +963,71 @@ export class GhostManager {
result.skipped.push(id);
continue;
}
- if (this.receiptStore.read(id).state === 'approved') {
+ 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.receiptStore.readPendingMutationSync(id) !== null) {
+ const pendingMutation = this.receiptStore.readPendingMutationSync(id);
+ if (pendingMutation.state !== 'missing') {
result.skipped.push(id);
+ blockedByPendingJournal.push(id);
continue;
}
candidates.push(id);
}
- if (candidates.length === 0 && !resumePending) {
- // 一个 backfill 都不需要(空目录/只有随包目录)就不落台账 —— 留给 legacy
- // 恢复流程;防滥用由 hasAnyValidReceipt 判据 + receipt 首写自动落账挡住。
+ 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) {
+ 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: [...candidates].sort(),
+ pendingIds: [
+ ...new Set([...candidates, ...blockedByPendingJournal, ...unreadableReceiptIds]),
+ ].sort(),
});
}
@@ -597,6 +1035,7 @@ export class GhostManager {
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…,状态根写不动、文件被占等)是
@@ -609,13 +1048,18 @@ export class GhostManager {
const transient = isTransientBackfillError(err);
if (transient) {
result.retryPending.push(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),
- });
+ 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),
@@ -631,10 +1075,9 @@ export class GhostManager {
// - 全部落定(只剩确定性 failed 或全成功)→ completed;续跑轮把上一轮已记的
// failedIds 一并带上,台账始终如实反映全量。
const migratedIds = [...new Set([...result.migrated, ...preMigrated])].sort();
- const failedIds = [
- ...new Set([...result.failed, ...(resumeLedger?.failedIds ?? [])]),
- ].sort();
- const retryIds = [...result.retryPending].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(),
@@ -662,26 +1105,63 @@ export class GhostManager {
): Promise<{ migrated: string[]; failed: string[] }> {
return this.runExclusiveMutation(async () => {
const out = { migrated: [] as string[], failed: [] as string[] };
- const root = this.options.getRootDir();
- for (const id of new Set(ids)) {
- if (!isValidGhostId(id)) continue;
- if (this.options.isTrustedBundledId?.(id)) continue;
- if (this.receiptStore.read(id).state === 'approved') continue;
+ const retryIds: string[] = [];
+ const root = this.contentRootDir();
+ const prev = this.receiptStore.readMigrationLedger();
+ 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();
+ 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;
+ }
try {
if (await this.backfillLegacyApproval(path.join(root, id), id)) {
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),
@@ -689,24 +1169,22 @@ export class GhostManager {
}
}
}
- if (out.migrated.length > 0 || out.failed.length > 0) {
- const prev = this.receiptStore.readMigrationLedger();
- const failedIds = [
- ...new Set([...(prev?.failedIds ?? []), ...out.failed]),
- ].sort();
+ if (
+ 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(),
+ migratedIds: [...new Set([...(prev?.migratedIds ?? []), ...out.migrated])].sort(),
...(failedIds.length > 0 ? { failedIds } : {}),
- // 状态机透传:上一轮迁移若停在 in-progress(崩溃待续跑),恢复流程的合并
- // 写入不得把它冲成 completed,否则续跑门被焊死、剩余插件永不迁。
- state: prev?.state === 'in-progress' ? 'in-progress' : 'completed',
- ...(prev?.state === 'in-progress' && prev.pendingIds
- ? { pendingIds: prev.pendingIds }
- : {}),
+ // 旁路 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());
@@ -740,7 +1218,12 @@ export class GhostManager {
// 后者无 errno。
let rawBytes: Buffer;
try {
- rawBytes = fs.readFileSync(path.join(dir, GHOST_MANIFEST_FILE));
+ rawBytes = fs.readFileSync(
+ resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {
+ expect: 'file',
+ label: 'legacy manifest',
+ }),
+ );
} catch (err) {
throw err; // 原样抛,保留 errno(EACCES/EBUSY/EIO → 瞬时;ENOENT → 确定性)
}
@@ -754,7 +1237,7 @@ export class GhostManager {
if (!validated.ok) throw new Error(`invalid manifest: ${validated.reason}`);
if (validated.manifest.id !== id) throw new Error('manifest id != install dir name');
- const enabled = !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE));
+ const enabled = !this.isDisabledMarkerPresentSync(dir);
const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {
level: 'unverified',
publisherSigned: false,
@@ -802,27 +1285,43 @@ export class GhostManager {
* 随包插件一律拒:它们的批准由 provisioning 与种子逐字节对账后自动补,重启即恢复,
* 不走人工确认(也不能走 —— 这条路的 trust 封顶在非官方档)。
*/
- inspectInstalledReapproval(
- id: string,
- ):
+ 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 } {
+ | { 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: '插件批准状态已恢复,无需重新确认' } };
}
- const dir = path.join(this.options.getRootDir(), id);
+ 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(path.join(dir, GHOST_MANIFEST_FILE));
+ rawBytes = fs.readFileSync(
+ resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {
+ expect: 'file',
+ label: 'installed manifest',
+ }),
+ );
} catch (err) {
return {
rejection: {
@@ -866,11 +1365,36 @@ export class GhostManager {
publisherVerified: false,
reviewed: false,
};
- return {
+ let localeResources: Record<string, GhostManifestLocaleResource>;
+ let skillContentSha256: Record<string, string>;
+ 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'),
- previouslyEnabled: !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE)),
+ approvalProjectionSha256: hashInstalledReapprovalProjection(projection),
+ previouslyEnabled: !this.isDisabledMarkerPresentSync(dir),
};
}
@@ -883,14 +1407,24 @@ export class GhostManager {
*/
async reapproveInstalled(
id: string,
- opts: { enable: boolean; expectedManifestSha256: string; expectedInstalledApproval: string },
+ opts: {
+ enable: boolean;
+ expectedManifestSha256: string;
+ expectedApprovalProjectionSha256: string;
+ expectedInstalledApproval: string;
+ },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
return this.runExclusiveMutation(() => this.reapproveInstalledUnlocked(id, opts));
}
private async reapproveInstalledUnlocked(
id: string,
- opts: { enable: boolean; expectedManifestSha256: string; expectedInstalledApproval: string },
+ opts: {
+ enable: boolean;
+ expectedManifestSha256: string;
+ expectedApprovalProjectionSha256: string;
+ expectedInstalledApproval: string;
+ },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
// 确认期间批准状态不得变过:与更新流程同款前置条件(token 由 Main 现读比对)。
const currentToken = ghostInstallApprovalToken(
@@ -902,13 +1436,21 @@ export class GhostManager {
};
}
// 重走只读检查(含随包拒收/清单校验),并绑定确认卡展示时的清单字节。
- const inspected = this.inspectInstalledReapproval(id);
+ 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();
@@ -927,11 +1469,11 @@ export class GhostManager {
};
}
}
- const dir = path.join(this.options.getRootDir(), id);
+ const dir = path.join(this.contentRootDir(), id);
try {
- const localeResources = this.readApprovedLocaleResources(dir, inspected.manifest);
- const iconDataUrl = this.readInstalledIconDataUrl(dir, inspected.manifest) ?? undefined;
- const skillContentSha256 = await hashApprovedSkillContent(inspected.manifest, dir);
+ const localeResources = inspected.localeResources;
+ const iconDataUrl = inspected.iconDataUrl;
+ const skillContentSha256 = inspected.skillContentSha256;
await this.receiptStore.write(
createGhostInstallReceipt({
manifest: inspected.manifest,
@@ -971,7 +1513,8 @@ export class GhostManager {
/** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */
list(): InstalledGhost[] {
- const root = this.options.getRootDir();
+ this.ensureCurrentOwnerContextSync();
+ const root = this.contentRootDir();
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
@@ -1026,9 +1569,12 @@ export class GhostManager {
// 老安装没有 Host 批准快照,或快照损坏:只读取清单用于设置页恢复,
// 不把 live manifest / trust / enabled 当成运行授权。
- const manifestPath = path.join(dir, GHOST_MANIFEST_FILE);
let raw: unknown;
try {
+ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {
+ expect: 'file',
+ label: 'installed manifest',
+ });
raw = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
} catch (err) {
this.options.log?.warn('ghost dir skipped: unreadable manifest', {
@@ -1071,7 +1617,9 @@ export class GhostManager {
const runtimeManifest = withGhostResolvedLocale(receipt.manifest, requestedLocale);
const localePath = ghostLocalePathFor(receipt.manifest, requestedLocale);
const fallbackPath = receipt.manifest.locales?.en;
- const candidates = [...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value)))];
+ const candidates = [
+ ...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value))),
+ ];
for (const candidate of candidates) {
const resource = receipt.localeResources[candidate];
if (resource) return resolveGhostManifestLocale(runtimeManifest, resource);
@@ -1089,7 +1637,9 @@ export class GhostManager {
const localePath = ghostLocalePathFor(manifest, requestedLocale);
if (!localePath) return runtimeManifest;
const fallbackPath = manifest.locales?.en;
- const candidates = [...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value)))];
+ const candidates = [
+ ...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value))),
+ ];
for (const candidatePath of candidates) {
try {
// 逐段解析(判据与批准侧 readApprovedLocaleResources、技能目录同源)。
@@ -1144,7 +1694,7 @@ export class GhostManager {
if (!isValidGhostId(id)) {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
}
- const dir = path.join(this.options.getRootDir(), id);
+ const dir = path.join(this.contentRootDir(), id);
// pathExists(fs.access)跟随链接:`<root>/<id>` 被换成 junction 时,下面对
// `<dir>/.disabled` 的写/删会穿透到安装根之外的目标。判据改用 ghostContentTree 的
// lstat 分类(与 list()「只有真目录才算安装」同源):不存在(ENOENT→抛错)或非真目录
@@ -1167,19 +1717,39 @@ export class GhostManager {
},
};
}
+ // Re-check immediately before touching the compatibility mirror. This does not
+ // replace OS-level handle protection, but prevents a stale initial classification
+ // from authorizing a link/file target in the common race window.
+ if (!this.isRealDirChild(this.contentRootDir(), id)) {
+ return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
+ }
const marker = path.join(dir, DISABLED_MARKER_FILE);
// 回滚基准取"镜像先前是否在盘上",不是 receipt.enabled:两者可以背离(旧客户端
// 只写镜像 → receipt=true + 镜像在,读时合并 = 停用)。按 receipt 回滚会在
// "启用失败"后把镜像永久丢掉 —— 有效状态从停用静默翻成启用,还带不回来。
- const markerExisted = fs.existsSync(marker);
+ const markerExisted = this.isDisabledMarkerPresentSync(dir);
// 阶段 1:镜像。两阶段的错误必须分开 —— 镜像写失败时**什么都还没落盘**,
// 把它报成"已停用"是谎报:重启后按 receipt.enabled=true 原样复活,而用户
// 以为已经关掉了。停用方向的"必须永远能成功"指的是不被环境卡死在"既不能用
// 也不能关",不是"任何失败都谎称成功"。
try {
if (enabled) {
+ 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;
+ }
await fs.promises.rm(marker, { force: true });
} else {
+ 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;
+ }
await fs.promises.writeFile(marker, '');
}
} catch (err) {
@@ -1219,14 +1789,19 @@ export class GhostManager {
// 回滚也写不动的终态要可观测:receipt 仍是停用(读时合并 fail closed
// 不受影响),但只认镜像的旧客户端会把它看成启用 —— 状态不一致,升级
// error 级,不静默。
- (this.options.log?.error ?? this.options.log?.warn)?.call(this.options.log,
- 'ghost enable failed and mirror rollback also failed; old clients may see it enabled', {
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
+ 'ghost enable failed and mirror rollback also failed; old clients may see it enabled',
+ {
id,
error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- });
+ },
+ );
});
}
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
}
}
this.options.log?.info('ghost enabled state changed', { id, enabled });
@@ -1249,7 +1824,10 @@ export class GhostManager {
});
const stat = fs.lstatSync(iconPath);
if (stat.size > MAX_GHOST_ICON_BYTES) {
- this.options.log?.warn('ghost icon skipped: missing or oversize', { dir, icon: manifest.icon });
+ this.options.log?.warn('ghost icon skipped: missing or oversize', {
+ dir,
+ icon: manifest.icon,
+ });
return null;
}
return buildIconDataUrl(manifest.icon, fs.readFileSync(iconPath));
@@ -1264,9 +1842,7 @@ export class GhostManager {
* 零副作用。「装意识前弹确认」(README 安全原则)的数据来源 —— 三个装入
* 入口(设置页 / 拖入 / 双击)都先 inspect 给用户看明白,确认后才 install。
*/
- async inspect(
- lizFilePath: string,
- ): Promise<
+ async inspect(lizFilePath: string): Promise<
| {
manifest: GhostManifest;
trust: GhostTrustInfo;
@@ -1286,9 +1862,7 @@ export class GhostManager {
}
/** 装入的前半程(读文件 / 解包 / 校验清单),inspect 与 install 共用。 */
- private async parse(
- lizFilePath: string,
- ): Promise<
+ private async parse(lizFilePath: string): Promise<
| {
manifest: GhostManifest;
approvedManifest: GhostManifest;
@@ -1310,7 +1884,10 @@ export class GhostManager {
}
if (stat.size > MAX_NODE_CINDY_FILE_BYTES) {
return {
- rejection: { code: 'file-invalid', reason: `文件过大:${stat.size} 字节(上限 ${MAX_NODE_CINDY_FILE_BYTES})` },
+ rejection: {
+ code: 'file-invalid',
+ reason: `文件过大:${stat.size} 字节(上限 ${MAX_NODE_CINDY_FILE_BYTES})`,
+ },
};
}
buf = await fs.promises.readFile(lizFilePath);
@@ -1318,7 +1895,9 @@ export class GhostManager {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
return { rejection: { code: 'source-not-found', reason: '文件不存在' } };
}
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
}
// 2) 解析 zip + 找 ghost.json(容忍"压缩时多包了一层文件夹"的常见做法)
@@ -1334,7 +1913,10 @@ export class GhostManager {
}
if (allEntries.length > MAX_NODE_ZIP_ENTRIES) {
return {
- rejection: { code: 'file-invalid', reason: `压缩包条目过多:${allEntries.length}(上限 ${MAX_NODE_ZIP_ENTRIES})` },
+ rejection: {
+ code: 'file-invalid',
+ reason: `压缩包条目过多:${allEntries.length}(上限 ${MAX_NODE_ZIP_ENTRIES})`,
+ },
};
}
// 检查/签名/保留文件对账都按原始条目名,解压却按 canonical 路径落盘;
@@ -1386,21 +1968,27 @@ export class GhostManager {
}
const manifestEntry = zip.file(`${prefix}${GHOST_MANIFEST_FILE}`);
if (!manifestEntry) {
- return { rejection: { code: 'file-invalid', reason: `压缩包根部缺少 ${GHOST_MANIFEST_FILE}` } };
+ return {
+ rejection: { code: 'file-invalid', reason: `压缩包根部缺少 ${GHOST_MANIFEST_FILE}` },
+ };
}
// 3) 校验清单
let manifestRaw: unknown;
try {
manifestRaw = JSON.parse(
- (await readZipEntryBufferWithLimit(
- manifestEntry,
- MAX_GHOST_MANIFEST_BYTES,
- GHOST_MANIFEST_FILE,
- )).toString('utf8'),
+ (
+ await readZipEntryBufferWithLimit(
+ manifestEntry,
+ MAX_GHOST_MANIFEST_BYTES,
+ GHOST_MANIFEST_FILE,
+ )
+ ).toString('utf8'),
);
} catch {
- return { rejection: { code: 'file-invalid', reason: `${GHOST_MANIFEST_FILE} 不是合法 JSON` } };
+ return {
+ rejection: { code: 'file-invalid', reason: `${GHOST_MANIFEST_FILE} 不是合法 JSON` },
+ };
}
const v = validateGhostManifest(manifestRaw);
if (!v.ok) {
@@ -1417,7 +2005,10 @@ export class GhostManager {
const maxEntries = v.manifest.node ? MAX_NODE_ZIP_ENTRIES : MAX_BASIC_ZIP_ENTRIES;
if (allEntries.length > maxEntries) {
return {
- rejection: { code: 'file-invalid', reason: `压缩包条目过多:${allEntries.length}(上限 ${maxEntries})` },
+ rejection: {
+ code: 'file-invalid',
+ reason: `压缩包条目过多:${allEntries.length}(上限 ${maxEntries})`,
+ },
};
}
if (v.manifest.node && !zip.file(`${prefix}${v.manifest.node.entry}`)) {
@@ -1446,11 +2037,13 @@ export class GhostManager {
let localeRaw: unknown;
try {
localeRaw = JSON.parse(
- (await readZipEntryBufferWithLimit(
- localeEntry,
- GHOST_LOCALE_MAX_BYTES,
- `locale ${localePath}`,
- )).toString('utf8'),
+ (
+ await readZipEntryBufferWithLimit(
+ localeEntry,
+ GHOST_LOCALE_MAX_BYTES,
+ `locale ${localePath}`,
+ )
+ ).toString('utf8'),
);
} catch {
return {
@@ -1511,16 +2104,15 @@ export class GhostManager {
const iconEntry = zip.file(`${prefix}${v.manifest.icon}`);
if (!iconEntry) {
return {
- rejection: { code: 'file-invalid', reason: `清单声明了 icon,但压缩包内缺少 ${v.manifest.icon}` },
+ rejection: {
+ code: 'file-invalid',
+ reason: `清单声明了 icon,但压缩包内缺少 ${v.manifest.icon}`,
+ },
};
}
let iconData: Buffer;
try {
- iconData = await readZipEntryBufferWithLimit(
- iconEntry,
- MAX_GHOST_ICON_BYTES,
- 'icon',
- );
+ iconData = await readZipEntryBufferWithLimit(iconEntry, MAX_GHOST_ICON_BYTES, 'icon');
} catch {
return {
rejection: {
@@ -1541,7 +2133,10 @@ export class GhostManager {
const skillEntry = zip.file(`${prefix}${relPath}`);
if (!skillEntry) {
return {
- rejection: { code: 'file-invalid', reason: `skill 条目声明了 ${skillItem.dir},但压缩包内缺少 ${relPath}` },
+ rejection: {
+ code: 'file-invalid',
+ reason: `skill 条目声明了 ${skillItem.dir},但压缩包内缺少 ${relPath}`,
+ },
};
}
let skillMd: Buffer;
@@ -1562,7 +2157,10 @@ export class GhostManager {
const consistencyError = checkSkillMdConsistency(skillMd.toString('utf8'), skillItem);
if (consistencyError) {
return {
- rejection: { code: 'file-invalid', reason: `skill 条目 ${skillItem.dir}:${consistencyError}` },
+ rejection: {
+ code: 'file-invalid',
+ reason: `skill 条目 ${skillItem.dir}:${consistencyError}`,
+ },
};
}
}
@@ -1617,9 +2215,12 @@ export class GhostManager {
allEntries,
prefix,
} = parsed;
+ const clearBuiltinTombstoneOnCommit =
+ this.options.isTrustedBundledId?.(manifest.id) === true &&
+ this.options.clearBuiltinTombstone !== undefined;
// 4) 目标目录冲突检查
- const root = this.options.getRootDir();
+ const root = this.contentRootDir();
const finalDir = path.join(root, manifest.id);
if (await pathExists(finalDir)) {
return { rejection: { code: 'already-installed', reason: `意识 ${manifest.id} 已装入` } };
@@ -1644,7 +2245,10 @@ export class GhostManager {
}
// 5) 解压到 staging(zip-slip / zip bomb 防御),全过才切正式目录
- const stagingDir = path.join(root, `.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`);
+ const stagingDir = path.join(
+ root,
+ `.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`,
+ );
// receipt 在内容落到 finalDir 之后才创建:技能字节指纹必须从这次批准的内容
// 目录现算,不能凭空构造。
let receipt: GhostInstallReceipt | undefined;
@@ -1665,6 +2269,7 @@ export class GhostManager {
await this.receiptStore.writePendingMutation(manifest.id, {
kind: 'install',
packageSha256,
+ ...(clearBuiltinTombstoneOnCommit ? { clearBuiltinTombstone: true } : {}),
});
await fs.promises.rename(stagingDir, finalDir);
try {
@@ -1684,13 +2289,47 @@ export class GhostManager {
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
});
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
+ let tombstoneClearPending = false;
+ if (clearBuiltinTombstoneOnCommit) {
+ try {
+ this.options.clearBuiltinTombstone?.(manifest.id);
+ } catch (error) {
+ tombstoneClearPending = true;
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
+ 'builtin tombstone clear deferred to install recovery',
+ {
+ id: manifest.id,
+ error: error instanceof Error ? error.message : String(error),
+ },
+ );
+ }
+ }
// receipt 已就位 = 事务提交,清标记。清失败只多留一份标记,下轮恢复见
// receipt.packageSha256 与标记相符即判已提交、幂等清理。
- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
+ if (!tombstoneClearPending) {
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
+ }
this.untrustedApprovals.delete(this.isolationKey(manifest.id));
} catch (error) {
- await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
+ try {
+ await fs.promises.rm(finalDir, { recursive: true, force: true });
+ await this.receiptStore.clearPendingMutation(manifest.id);
+ } catch (rollbackError) {
+ // Keep the install journal whenever rollback cannot prove the published
+ // directory is gone. Migration treats that journal as a hard block, and
+ // startup recovery can finish the cleanup without re-minting approval
+ // from uncommitted mutable bytes.
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
+ 'ghost install approval failed and rollback remains pending',
+ {
+ id: manifest.id,
+ error:
+ rollbackError instanceof Error ? rollbackError.message : String(rollbackError),
+ },
+ );
+ }
throw error;
}
} catch (err) {
@@ -1698,7 +2337,9 @@ export class GhostManager {
if (err instanceof InstallExtractError) {
return { rejection: { code: 'file-invalid', reason: err.message } };
}
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
}
if (!receipt) {
return { rejection: { code: 'io', reason: '安装批准状态未能生成' } };
@@ -1761,10 +2402,12 @@ export class GhostManager {
prefix,
} = parsed;
- const root = this.options.getRootDir();
+ const root = this.contentRootDir();
const finalDir = path.join(root, manifest.id);
- if (!(await pathExists(finalDir))) {
- return { rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` } };
+ if (!this.isRealDirChild(root, manifest.id)) {
+ return {
+ rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` },
+ };
}
const approvalResult = this.readApproval(manifest.id);
const actualApproval = approvalTokenFor(approvalResult);
@@ -1780,11 +2423,11 @@ export class GhostManager {
// 采用原 `.disabled` 镜像;损坏 receipt 一律保持停用。
const enabled =
approvalResult.state === 'approved'
- // 读时合并后的有效值:receipt 可能因状态根短暂不可写而停在陈旧的 enabled=true,
- // 用户的停用镜像不能被一次更新静默冲掉。
- ? this.effectiveEnabled(finalDir, approvalResult.receipt.enabled)
+ ? // 读时合并后的有效值:receipt 可能因状态根短暂不可写而停在陈旧的 enabled=true,
+ // 用户的停用镜像不能被一次更新静默冲掉。
+ this.effectiveEnabled(finalDir, approvalResult.receipt.enabled)
: approvalResult.state === 'legacy-unapproved'
- ? !fs.existsSync(path.join(finalDir, DISABLED_MARKER_FILE))
+ ? !this.isDisabledMarkerPresentSync(finalDir)
: false;
// 指令查重同 install,但豁免自己(新版本沿用/改名自己的指令都合法)。
@@ -1822,7 +2465,9 @@ export class GhostManager {
if (err instanceof InstallExtractError) {
return { rejection: { code: 'file-invalid', reason: err.message } };
}
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
}
// 事务标记在两次 rename 动盘**之前**落:staging→final 之后、写 receipt 之前崩溃会
@@ -1834,10 +2479,16 @@ export class GhostManager {
kind: 'update',
packageSha256,
backupDirName: path.basename(backupDir),
+ phase: 'prepared',
+ ...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256
+ ? { oldPackageSha256: approvalResult.receipt.packageSha256 }
+ : {}),
});
} catch (err) {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
}
// 换目录:旧版先挪去备份位,新版 rename 失败即滚回,保证任何时刻都有一份完整版本在位。
try {
@@ -1845,25 +2496,55 @@ export class GhostManager {
} catch (err) {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
}
+ // Advance the durable phase after the old directory is safely in backup. If
+ // this write is interrupted, recovery can infer the same state from the
+ // presence of the backup and will never treat a pre-rename final as new code.
+ await this.receiptStore
+ .writePendingMutation(manifest.id, {
+ kind: 'update',
+ packageSha256,
+ backupDirName: path.basename(backupDir),
+ phase: 'backed-up',
+ ...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256
+ ? { oldPackageSha256: approvalResult.receipt.packageSha256 }
+ : {}),
+ })
+ .catch((error) => {
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
+ 'ghost update phase journal write failed; continuing with recoverable marker',
+ {
+ id: manifest.id,
+ error: error instanceof Error ? error.message : String(error),
+ },
+ );
+ });
try {
await fs.promises.rename(stagingDir, finalDir);
} catch (err) {
let rolledBack = true;
await fs.promises.rename(backupDir, finalDir).catch((rollbackErr) => {
rolledBack = false;
- (this.options.log?.error ?? this.options.log?.warn)?.call(this.options.log,
- 'ghost update rollback failed; install dir left inconsistent', {
- id: manifest.id, backupDir,
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
+ 'ghost update rollback failed; install dir left inconsistent',
+ {
+ id: manifest.id,
+ backupDir,
error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- });
+ },
+ );
});
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
- // 已回滚到 backup(或回滚也失败):无论如何这次 update 未提交,清标记 —— 回滚成功时
- // finalDir=旧字节+旧 receipt 已自洽;回滚失败时 rollbackFailed 已上报,标记留着也
- // 只会让恢复器再尝试同样已失败的回滚。
- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
+ // 只有回滚成功时才能清标记。回滚失败必须保留 journal,让下次启动继续收敛;
+ // 清掉它会让 orphan-backup 启发式把新字节与旧 receipt 固化在一起。
+ if (rolledBack) {
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
+ }
return {
rejection: {
code: 'io',
@@ -1896,13 +2577,19 @@ export class GhostManager {
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
await fs.promises.rename(backupDir, finalDir).catch((rollbackErr) => {
rolledBack = false;
- (this.options.log?.error ?? this.options.log?.warn)?.call(this.options.log,
- 'ghost update rollback failed after receipt write failure', {
- id: manifest.id, backupDir,
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
+ 'ghost update rollback failed after receipt write failure',
+ {
+ id: manifest.id,
+ backupDir,
error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- });
+ },
+ );
});
- await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
+ if (rolledBack) {
+ await this.receiptStore.clearPendingMutation(manifest.id).catch(() => undefined);
+ }
return {
rejection: {
code: 'io',
@@ -1940,20 +2627,160 @@ export class GhostManager {
* 技能链。反方向(镜像说停用、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 });
+ await fs.promises.rename(stagingDir, finalDir);
+ return;
+ }
+
+ await this.receiptStore.writePendingMutation(id, {
+ kind: 'update',
+ packageSha256,
+ backupDirName: path.basename(backupDir),
+ phase: 'prepared',
+ });
+ 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);
+ } catch {
+ // Keep the journal for startup recovery when rollback cannot complete now.
+ }
+ } else if (backupKind === null && publishedKind === null) {
+ await this.receiptStore.clearPendingMutation(id).catch(() => undefined);
+ }
+ throw error;
+ }
+ }
+
async approveTrustedBundledInstall(
manifest: GhostManifest,
markerEnabled: boolean,
+ options: { sourceDir: string },
): Promise<boolean> {
- if (this.options.isTrustedBundledId?.(manifest.id) === false) {
+ 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.options.getRootDir(), manifest.id);
- const localeResources = this.readApprovedLocaleResources(dir, manifest);
- const iconDataUrl = this.readInstalledIconDataUrl(dir, manifest) ?? undefined;
- const packageSha256 = await hashApprovedDirectory(dir);
- const skillContentSha256 = await hashApprovedSkillContent(manifest, dir);
+ 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,
@@ -1964,17 +2791,14 @@ export class GhostManager {
// 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;
+ 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 {
- fs.writeFileSync(path.join(dir, DISABLED_MARKER_FILE), '');
+ this.writeDisabledMarkerSync(dir);
} catch (err) {
this.options.log?.warn('ghost disabled mirror rewrite failed', {
id: manifest.id,
@@ -1996,9 +2820,11 @@ export class GhostManager {
...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(
@@ -2011,21 +2837,46 @@ export class GhostManager {
packageSha256,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
}),
- { skillSourceDir: dir },
+ { 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<void> {
+ 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 没实现
@@ -2036,6 +2887,7 @@ export class GhostManager {
'ghost approval could not be removed; kept untrusted in-process',
{ id, error: err instanceof Error ? err.message : String(err) },
);
+ return false;
}
}
@@ -2105,27 +2957,24 @@ export class GhostManager {
* Host 需要在内置意识卸载后先写 tombstone,再向 renderer 发布一份
* 已安装 + 可恢复相互一致的快照。notify=false 只延后广播,不改变卸载语义。
*/
- async uninstall(
- id: string,
- options: { notify?: boolean } = {},
- ) {
+ async uninstall(id: string, options: GhostUninstallOptions = {}) {
return this.runExclusiveMutation(() => this.uninstallUnlocked(id, options));
}
private async uninstallUnlocked(
id: string,
- options: { notify?: boolean } = {},
- ): Promise<{ ok: true } | { rejection: UninstallRejection }> {
+ options: GhostUninstallOptions = {},
+ ): Promise<UninstallResult> {
if (!isValidGhostId(id)) {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
}
- const root = this.options.getRootDir();
+ const root = this.contentRootDir();
const dir = path.join(root, id);
// 双保险:id 格式校验已排除路径穿越,这里再确认是 root 的直接子目录。
if (path.dirname(dir) !== path.resolve(root) && path.dirname(dir) !== root) {
return { rejection: { code: 'invalid-id', reason: '非法意识 id' } };
}
- if (!(await pathExists(dir))) {
+ if (!this.isRealDirChild(root, id)) {
return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };
}
// 顺序是安全要点:先撤批准(receipt + 快照 + 隔离),再删内容目录。反过来(旧写法)
@@ -2133,18 +2982,45 @@ export class GhostManager {
// 同权限进程新建目录时,list() 会拿这份陈旧 receipt 授权那个目录(manifest/slots/
// trust 全来自 receipt),等于卸载过的插件被"借尸还魂"。事务标记让崩溃后的启动恢复
// 把这次卸载收尾干净。
- await this.receiptStore.writePendingMutation(id, { kind: 'uninstall' });
+ const builtinTombstone =
+ options.recordBuiltinTombstone !== false && this.options.isTrustedBundledId?.(id) === true;
+ await this.receiptStore.writePendingMutation(id, {
+ kind: 'uninstall',
+ ...(builtinTombstone ? { builtinTombstone: true } : {}),
+ });
+ this.untrustedApprovals.add(this.isolationKey(id));
+ if (builtinTombstone) {
+ try {
+ if (!this.options.recordBuiltinTombstone) {
+ throw new Error('builtin uninstall has no tombstone writer');
+ }
+ this.options.recordBuiltinTombstone(id);
+ } catch (err) {
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
+ }
+ }
// 走同一个撤销入口:成功即清掉隔离记录,失败由该入口转进程内隔离并记日志。撤批准
// 在删目录之前 —— 即便随后删目录失败/崩溃,也不会留下"目录在 + 旧 receipt 授权"。
- await this.removeInstallApproval(id);
+ const approvalRemoved = await this.removeInstallApprovalUnlocked(id);
try {
await fs.promises.rm(dir, { recursive: true, force: true });
} catch (err) {
// 批准已撤、标记还在:插件此刻已 fail closed(list 无 receipt → legacy-unapproved),
// 下次启动恢复据标记把残留目录删净。如实报 io,不假装卸载完成。
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
+ }
+ // Receipt 删除失败时保留 uninstall journal,即使内容目录已经删掉;下次启动
+ // 仍需据 journal 清理孤立 receipt,不能让进程内隔离随重启丢失。
+ if (approvalRemoved) {
+ await this.receiptStore.clearPendingMutation(id).catch(() => undefined);
+ this.untrustedApprovals.delete(this.isolationKey(id));
+ } else {
+ this.options.log?.warn('ghost uninstall left journal for approval cleanup', { id });
}
- await this.receiptStore.clearPendingMutation(id).catch(() => undefined);
this.options.log?.info('ghost uninstalled', { id });
if (options.notify !== false) this.options.onChanged?.(this.list());
return { ok: true };
@@ -2262,6 +3138,22 @@ function isTransientBackfillError(err: unknown): boolean {
return typeof code === 'string' && code !== 'ENOENT';
}
+/** Copy a bundled seed without following links; dot entries are Host state and are skipped. */
+async function copyBundledSeedDirectory(from: string, to: string): Promise<void> {
+ await fs.promises.mkdir(to, { recursive: true });
+ for (const entry of await fs.promises.readdir(from, { withFileTypes: true })) {
+ const source = path.join(from, entry.name);
+ const target = path.join(to, entry.name);
+ const kind = await classifyGhostDirEntry(source);
+ if (kind !== 'directory' && kind !== 'file') {
+ throw new Error(`builtin seed rejects non-regular entry: ${entry.name}`);
+ }
+ if (entry.name.startsWith('.')) continue;
+ if (kind === 'directory') await copyBundledSeedDirectory(source, target);
+ else await fs.promises.copyFile(source, target);
+ }
+}
+
/**
* 安装目录内容指纹(`packageSha256`,审计用的漂移检测器,不作授权判据)。
*
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 554303a5eb..aac6510f2d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -20,16 +20,25 @@ let rootDir: string;
let onChanged: ReturnType<typeof vi.fn>;
let manager: GhostManager;
let hostLocale: string;
+let trustedBundledIds: Set<string>;
+let recordBuiltinTombstone: ReturnType<typeof vi.fn>;
beforeEach(async () => {
workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-ghost-test-'));
rootDir = path.join(workDir, 'ghosts');
onChanged = vi.fn();
hostLocale = 'zh-CN';
+ trustedBundledIds = new Set();
+ recordBuiltinTombstone = vi.fn();
manager = new GhostManager({
getRootDir: () => rootDir,
getLocale: () => hostLocale,
onChanged,
+ isTrustedBundledId: (id) => trustedBundledIds.has(id),
+ isTrustedBundledSource: (id, sourceDir) =>
+ trustedBundledIds.has(id) &&
+ path.resolve(sourceDir) === path.resolve(workDir, 'bundled-seeds', id),
+ recordBuiltinTombstone,
});
});
@@ -382,6 +391,37 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
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) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {
+ lstatSpy.mockRestore();
+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
+ }
+ return realLstatSync(target, options as never);
+ });
+
+ 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 重建 —— 一次内部格式变更
@@ -406,6 +446,35 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
});
});
+ 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');
+
+ // 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 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' },
+ });
+ });
+
it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
const before = await fs.promises.readFile(
@@ -435,6 +504,59 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
});
});
+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'),
+ });
+
+ 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'),
+ });
+
+ expect(fresh.list()).toEqual([]);
+ });
+
+ 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(
+ () =>
+ new GhostManager({
+ getRootDir: () => linkedRoot,
+ getStateDir: () => path.join(workDir, 'state-root'),
+ }),
+ ).toThrow(/ghost content root is not a real directory/);
+ });
+});
+
describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命名空间', () => {
it('中途崩溃后按 pendingIds 续跑:已迁的跳过、剩余补迁、台账推进到 completed', async () => {
// 复现真实崩溃现场:首轮迁移在 aaa 写完 receipt(receipt 首写自动落账被
@@ -526,6 +648,33 @@ describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命
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 在盘 → 读时合并 = 停用。
@@ -609,7 +758,7 @@ describe('GhostManager · 从已装目录重新确认(本地包第三条恢复
await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
- const inspected = manager.inspectInstalledReapproval('hello');
+ 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}$/);
@@ -617,6 +766,7 @@ describe('GhostManager · 从已装目录重新确认(本地包第三条恢复
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));
@@ -627,23 +777,82 @@ describe('GhostManager · 从已装目录重新确认(本地包第三条恢复
it('确认间隙 ghost.json 被换 → 拒(确认卡展示的与批准的必须是同一份字节)', async () => {
await writeLegacyInstall('hello', goodManifest());
- const inspected = manager.inspectInstalledReapproval('hello');
+ 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(), slots: ['tool', 'skill'], skill: { items: [{ dir: 'skills/x', name: 'x', description: 'x' }] } }),
+ 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,
@@ -651,13 +860,13 @@ describe('GhostManager · 从已装目录重新确认(本地包第三条恢复
isTrustedBundledId: (id) => id === 'hello',
});
await writeLegacyInstall('hello', goodManifest());
- const inspected = guarded.inspectInstalledReapproval('hello');
+ 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 = manager.inspectInstalledReapproval('hello');
+ const inspected = await manager.inspectInstalledReapproval('hello');
expect('rejection' in inspected && inspected.rejection.code).toBe('state-changed');
});
@@ -670,7 +879,7 @@ describe('GhostManager · 从已装目录重新确认(本地包第三条恢复
reviewed: true,
},
});
- const inspected = manager.inspectInstalledReapproval('hello');
+ const inspected = await manager.inspectInstalledReapproval('hello');
if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
expect(inspected.trust.level).toBe('unverified');
});
@@ -789,6 +998,78 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
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;
@@ -824,16 +1105,98 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
expect(byId.planted).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) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {
+ lstatSpy.mockRestore();
+ throw Object.assign(new Error('EIO: receipt temporarily unreadable'), { code: 'EIO' });
+ }
+ return realLstatSync(target, options as never);
+ });
+
+ expect(await manager.backfillRecoveredLegacyGhosts(['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']);
+ 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']);
+ 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']);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ expect(queueSeenBeforeReceipt).toBe(true);
+ });
+
it('P1-6:重新确认拒绝与已装插件撞名的指令', async () => {
await manager.install(
await makeCindy('holder.cindy', chipManifestWithCommand('holder', 'draw')),
);
await writeLegacyInstall('clasher', chipManifestWithCommand('clasher', 'Draw'));
- const inspected = manager.inspectInstalledReapproval('clasher');
+ 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');
@@ -853,66 +1216,529 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
],
},
});
- const inspected = manager.inspectInstalledReapproval('brokered');
+ 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 = manager.inspectInstalledReapproval('hello');
- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
- expect(inspected.previouslyEnabled).toBe(false);
+ 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('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {
+ it('已提交 install 的 receipt 瞬时不可读时保留 final/receipt/journal 等待重试', 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' });
+ 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[]) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath())) {
+ throw Object.assign(new Error('EACCES: receipt locked'), { code: 'EACCES' });
}
- return realRename(from as never, to as never);
- });
+ return (realReadFileSync as (...args: unknown[]) => unknown)(target, ...rest);
+ }) as typeof fs.readFileSync);
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);
+ 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);
});
-});
-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('已提交 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[]) => {
+ 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);
+ try {
+ const recovered = freshManager();
+ expect(recovered.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ } finally {
+ spy.mockRestore();
+ }
- 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 });
+ 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: 'install', packageSha256: 'a'.repeat(64) }),
+ 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();
+ }
- 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([]); // 目录已被删,迁移无对象
+ 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 () => {
@@ -1057,6 +1883,39 @@ describe('GhostManager · 装入/更新崩溃窗口恢复(事务标记)', () =>
});
});
+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 = {
@@ -1369,6 +2228,95 @@ describe('GhostManager · uninstall', () => {
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');
@@ -1429,6 +2377,22 @@ describe('GhostManager · Host approval receipt', () => {
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> => ({
@@ -1563,7 +2527,7 @@ describe('GhostManager · Host approval receipt', () => {
expect(fs.existsSync(listed.approvedSkillRoot!)).toBe(false);
});
- it('treats receipt cleanup failure after content removal as a completed uninstall', async () => {
+ 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());
@@ -1574,6 +2538,19 @@ describe('GhostManager · Host approval receipt', () => {
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 () => {
@@ -1941,20 +2918,109 @@ describe('GhostManager · Host approval receipt', () => {
await expectRejection(await manager.setEnabled('hello', true), 'approval-required');
// 下一轮启动对账重新补批准即自愈,不需要用户介入。
- expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).toBe(true);
+ 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('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)).toBe(true);
+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);
expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);
// 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。
@@ -1962,7 +3028,7 @@ describe('GhostManager · Host approval receipt', () => {
// 下一轮对账把镜像读数(启用)喂进来:不得据此翻转 receipt —— 否则用户显式
// 停用的插件被静默重新启用,无确认、无审计。重新启用只有 setEnabled 一条路。
- expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).toBe(false);
+ 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);
@@ -1973,12 +3039,13 @@ describe('GhostManager · Host approval receipt', () => {
const { manifest: approvedManifest } = JSON.parse(
await fs.promises.readFile(receiptPath(), 'utf8'),
) as { manifest: InstalledGhost['manifest'] };
- expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).toBe(true);
+ const source = await writeBundledSource(approvedManifest);
+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true, source)).toBe(true);
// 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——
// 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。
await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');
- expect(await manager.approveTrustedBundledInstall(approvedManifest, false)).toBe(true);
+ expect(await manager.approveTrustedBundledInstall(approvedManifest, false, source)).toBe(true);
expect(manager.list()[0].enabled).toBe(false);
});
@@ -1987,14 +3054,26 @@ describe('GhostManager · Host approval receipt', () => {
const { manifest: approvedManifest } = JSON.parse(
await fs.promises.readFile(receiptPath(), 'utf8'),
) as { manifest: InstalledGhost['manifest'] };
- expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).toBe(true);
+ 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)).toBe(true);
+ expect(
+ await manager.approveTrustedBundledInstall(
+ bumped,
+ true,
+ await writeBundledSource(bumped),
+ ),
+ ).toBe(true);
expect(manager.list()[0]).toMatchObject({
enabled: false,
manifest: { version: '1.0.1' },
@@ -2013,7 +3092,11 @@ describe('GhostManager · Host approval receipt', () => {
const validated = validateGhostManifest(goodManifest());
if (!validated.ok) throw new Error(validated.reason);
await expect(
- guarded.approveTrustedBundledInstall(validated.manifest, true),
+ guarded.approveTrustedBundledInstall(
+ validated.manifest,
+ true,
+ await writeBundledSource(validated.manifest),
+ ),
).rejects.toThrow(/种子清单/);
});
@@ -2099,6 +3182,60 @@ describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);
});
+ it('final 是普通文件时不删除唯一 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);
+ await fs.promises.writeFile(finalDir, 'unexpected file');
+
+ 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('final 是 junction/链接时不删除唯一 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');
+ 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 钉住。
+ }
+
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
+
+ expect((await fs.promises.lstat(finalDir)).isSymbolicLink()).toBe(true);
+ expect(fs.existsSync(path.join(backupDir, 'ghost.json'))).toBe(true);
+ });
+
+ 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(path.join(backupDir, 'ghost.json'))).toBe(true);
+ expect(fs.existsSync(finalDir)).toBe(false);
+ });
+
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 });
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
index 79c8f00829..de8205c7e5 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
@@ -4,7 +4,15 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { fingerprintDirContent, provisionBuiltinGhosts } from '../builtinGhostProvisioner.js';
+import {
+ fingerprintDirContent,
+ isTrustedBuiltinSeedSource,
+ PROVISIONING_STATE_FILE,
+ provisionBuiltinGhosts,
+ readBuiltinTombstones,
+ recordBuiltinTombstone,
+ renameBuiltinTombstone,
+} from '../builtinGhostProvisioner.js';
const tempDirs: string[] = [];
@@ -15,11 +23,246 @@ async function makeTempDir(): Promise<string> {
}
afterEach(async () => {
+ vi.restoreAllMocks();
await Promise.all(
tempDirs.splice(0).map((dir) => fs.promises.rm(dir, { recursive: true, force: true })),
);
});
+async function writeMinimalSeed(seedRoot: string, id: string): Promise<string> {
+ const seedDir = path.join(seedRoot, id);
+ await fs.promises.mkdir(seedDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(seedDir, 'ghost.json'),
+ JSON.stringify({
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'run', description: 'Run it' }],
+ }),
+ );
+ await fs.promises.writeFile(path.join(seedDir, 'main.js'), '// brain');
+ return seedDir;
+}
+
+describe('builtin provisioning durable state', () => {
+ it('writes tombstones through an atomic replacement without leaving temp files', async () => {
+ const repoRoot = await makeTempDir();
+
+ recordBuiltinTombstone(repoRoot, 'builtin-test');
+
+ expect(readBuiltinTombstones(repoRoot)).toEqual(['builtin-test']);
+ expect((await fs.promises.readdir(repoRoot)).filter((name) => name.includes('.tmp-'))).toEqual(
+ [],
+ );
+ });
+
+ it('reports tombstone replacement failure instead of claiming the uninstall intent persisted', async () => {
+ const repoRoot = await makeTempDir();
+ const rename = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
+ const error = new Error('access denied') as NodeJS.ErrnoException;
+ error.code = 'EACCES';
+ throw error;
+ });
+
+ expect(() => recordBuiltinTombstone(repoRoot, 'builtin-test')).toThrow(
+ 'builtin provisioning state write failed',
+ );
+ expect(fs.existsSync(path.join(repoRoot, PROVISIONING_STATE_FILE))).toBe(false);
+ rename.mockRestore();
+ });
+
+ it('moves renamed tombstones in one atomic state update', async () => {
+ const repoRoot = await makeTempDir();
+ recordBuiltinTombstone(repoRoot, 'builtin-old');
+
+ expect(renameBuiltinTombstone(repoRoot, 'builtin-old', 'builtin-new')).toBe(true);
+ expect(readBuiltinTombstones(repoRoot)).toEqual(['builtin-new']);
+ });
+
+ it('preserves the old tombstone when an atomic rename update cannot commit', async () => {
+ const repoRoot = await makeTempDir();
+ recordBuiltinTombstone(repoRoot, 'builtin-old');
+ const rename = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
+ const error = new Error('access denied') as NodeJS.ErrnoException;
+ error.code = 'EACCES';
+ throw error;
+ });
+
+ expect(() => renameBuiltinTombstone(repoRoot, 'builtin-old', 'builtin-new')).toThrow(
+ 'builtin provisioning state write failed',
+ );
+ expect(readBuiltinTombstones(repoRoot)).toEqual(['builtin-old']);
+ rename.mockRestore();
+ });
+
+ it('fails closed on a corrupt ledger instead of overwriting it or reseeding', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ await writeMinimalSeed(seedRoot, 'builtin-test');
+ await fs.promises.mkdir(repoRoot, { recursive: true });
+ const stateFile = path.join(repoRoot, PROVISIONING_STATE_FILE);
+ await fs.promises.writeFile(stateFile, '{broken');
+ const warn = vi.fn();
+
+ const outcome = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ log: { info: vi.fn(), warn },
+ });
+
+ expect(outcome.skipped).toEqual(['builtin-test']);
+ expect(fs.existsSync(path.join(repoRoot, 'builtin-test'))).toBe(false);
+ expect(await fs.promises.readFile(stateFile, 'utf8')).toBe('{broken');
+ expect(() => readBuiltinTombstones(repoRoot)).toThrow(
+ 'builtin provisioning state is unreadable',
+ );
+ expect(warn).toHaveBeenCalledWith(
+ 'builtin provisioning state unreadable',
+ expect.objectContaining({ file: stateFile }),
+ );
+ });
+
+ it('fails closed on path-traversal ids in the seeded ledger', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ const outside = path.join(root, 'outside');
+ await writeMinimalSeed(seedRoot, 'builtin-test');
+ await fs.promises.mkdir(repoRoot, { recursive: true });
+ const stateFile = path.join(repoRoot, PROVISIONING_STATE_FILE);
+ await fs.promises.writeFile(
+ stateFile,
+ JSON.stringify({ removed: [], seeded: ['..\\outside'] }),
+ );
+ const warn = vi.fn();
+
+ const outcome = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ log: { info: vi.fn(), warn },
+ });
+
+ expect(outcome.installed).toEqual([]);
+ expect(fs.existsSync(outside)).toBe(false);
+ expect(await fs.promises.readFile(stateFile, 'utf8')).toContain('..\\\\outside');
+ expect(warn).toHaveBeenCalledWith(
+ 'builtin provisioning state contains invalid ghost id',
+ expect.objectContaining({ file: stateFile }),
+ );
+ });
+
+ it('retains seeded ownership when audience cleanup fails so the next pass retries', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ await writeMinimalSeed(seedRoot, 'builtin-test');
+ await writeMinimalSeed(repoRoot, 'builtin-test');
+ await fs.promises.writeFile(
+ path.join(seedRoot, 'provisioning.json'),
+ JSON.stringify({
+ ghosts: { 'builtin-test': { audience: { userIds: ['allowed-user'] } } },
+ }),
+ );
+ const stateFile = path.join(repoRoot, PROVISIONING_STATE_FILE);
+ await fs.promises.writeFile(
+ stateFile,
+ JSON.stringify({ removed: [], seeded: ['builtin-test'] }),
+ );
+ const beforeRemove = vi
+ .fn<() => Promise<void>>()
+ .mockRejectedValueOnce(new Error('journal temporarily unavailable'))
+ .mockResolvedValueOnce(undefined);
+
+ const first = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ identity: { userId: 'denied-user', email: null },
+ beforeRemove,
+ });
+
+ expect(first.removed).toEqual([]);
+ expect(fs.existsSync(path.join(repoRoot, 'builtin-test'))).toBe(true);
+ expect(JSON.parse(await fs.promises.readFile(stateFile, 'utf8'))).toMatchObject({
+ seeded: ['builtin-test'],
+ });
+
+ const second = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ identity: { userId: 'denied-user', email: null },
+ beforeRemove,
+ });
+
+ expect(beforeRemove).toHaveBeenCalledTimes(2);
+ expect(second.removed).toEqual(['builtin-test']);
+ expect(fs.existsSync(path.join(repoRoot, 'builtin-test'))).toBe(false);
+ expect(JSON.parse(await fs.promises.readFile(stateFile, 'utf8'))).toMatchObject({ seeded: [] });
+ });
+
+ it('persists seeded ownership before replacing installed bytes', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ await writeMinimalSeed(seedRoot, 'builtin-test');
+ const installedDir = await writeMinimalSeed(repoRoot, 'builtin-test');
+ await fs.promises.writeFile(path.join(installedDir, 'main.js'), '// old bytes');
+ const beforeReplace = vi.fn(() => {
+ const state = JSON.parse(
+ fs.readFileSync(path.join(repoRoot, PROVISIONING_STATE_FILE), 'utf8'),
+ ) as { seeded?: string[] };
+ expect(state.seeded).toContain('builtin-test');
+ });
+
+ await provisionBuiltinGhosts({ seedRootDirs: [seedRoot], repoRootDir: repoRoot, beforeReplace });
+ expect(beforeReplace).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('builtin seed source boundary', () => {
+ it('accepts the exact link-free seed directory', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const seedDir = await writeMinimalSeed(seedRoot, 'builtin-test');
+
+ expect(isTrustedBuiltinSeedSource([seedRoot], 'builtin-test', seedDir)).toBe(true);
+ });
+
+ it('rejects a seed root reached through a symlink or junction', async () => {
+ const root = await makeTempDir();
+ const realRoot = path.join(root, 'real-seeds');
+ await writeMinimalSeed(realRoot, 'builtin-test');
+ const linkedRoot = path.join(root, 'linked-seeds');
+ try {
+ await fs.promises.symlink(
+ realRoot,
+ linkedRoot,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+
+ expect(
+ isTrustedBuiltinSeedSource(
+ [linkedRoot],
+ 'builtin-test',
+ path.join(linkedRoot, 'builtin-test'),
+ ),
+ ).toBe(false);
+ const outcome = await provisionBuiltinGhosts({
+ seedRootDirs: [linkedRoot],
+ repoRootDir: path.join(root, 'installed'),
+ });
+ expect(outcome.installed).toEqual([]);
+ });
+});
+
describe('fingerprintDirContent', () => {
/** 建链接;该环境无权限时返回 false 让调用方跳过(判定逻辑与其他平台同源)。 */
async function tryLink(target: string, linkPath: string): Promise<boolean> {
@@ -80,7 +323,8 @@ describe('fingerprintDirContent', () => {
expect(linkSide.hasNonRegularEntry).toBe(true);
// 即便两侧哈希相同也不会被误判为一致 —— 判定还要看类型状态。
expect(
- fileSide.hash === linkSide.hash && fileSide.hasNonRegularEntry === linkSide.hasNonRegularEntry,
+ fileSide.hash === linkSide.hash &&
+ fileSide.hasNonRegularEntry === linkSide.hasNonRegularEntry,
).toBe(false);
});
@@ -148,13 +392,16 @@ describe('builtinGhostProvisioner 安装目录被塞入链接时重新播种', (
return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
}
+ const beforeReplace = vi.fn();
const outcome = await provisionBuiltinGhosts({
seedRootDirs: [seedRoot],
repoRootDir: repoRoot,
+ beforeReplace,
log: { info: vi.fn(), warn: vi.fn() },
});
expect(outcome.updated.map((m) => m.id)).toContain('linked-seed');
+ expect(beforeReplace).toHaveBeenCalledWith('linked-seed');
expect(outcome.skipped).not.toContain('linked-seed');
// 重新播种后安装目录回到随包字节:链接消失,普通文件回来。
expect((await fs.promises.lstat(path.join(installedDir, 'entry'))).isFile()).toBe(true);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts
index 36769ec766..0a07a6b3de 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostGrantConfirmBridge.test.ts
@@ -133,4 +133,17 @@ describe('GhostGrantConfirmBridge', () => {
expect(bridge.resolve(requestId2, { confirmed: true })).toBe(true);
await expect(p2).resolves.toEqual({ confirmed: true, allowDirs: false });
});
+
+ it('cleanupAll fails closed every pending grant at an account boundary', async () => {
+ const broadcast = vi.fn();
+ const bridge = new GhostGrantConfirmBridge({ broadcast });
+ const p1 = bridge.request('sess-1', PAYLOAD);
+ const p2 = bridge.request('sess-2', PAYLOAD);
+
+ bridge.cleanupAll('session_aborted');
+
+ await expect(p1).resolves.toEqual({ confirmed: false, reason: 'session_aborted' });
+ await expect(p2).resolves.toEqual({ confirmed: false, reason: 'session_aborted' });
+ expect(bridge.pendingSnapshots()).toEqual([]);
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
new file mode 100644
index 0000000000..e38d3dd92e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
@@ -0,0 +1,100 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GhostInstallReceiptStore } from '../ghostInstallReceipt';
+
+describe('GhostInstallReceiptStore cleanup', () => {
+ let workDir: string;
+ let stateRoot: string;
+ let store: GhostInstallReceiptStore;
+
+ beforeEach(async () => {
+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-receipt-cleanup-'));
+ stateRoot = path.join(workDir, 'state');
+ await fs.promises.mkdir(stateRoot);
+ store = new GhostInstallReceiptStore(() => stateRoot);
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+ });
+
+ it('removes a regular receipt and managed snapshot tree', async () => {
+ const receipt = path.join(stateRoot, 'hello.json');
+ const snapshot = path.join(stateRoot, 'skill-snapshots', 'hello', 'revision');
+ await fs.promises.mkdir(snapshot, { recursive: true });
+ await fs.promises.writeFile(receipt, '{}');
+ await fs.promises.writeFile(path.join(snapshot, 'SKILL.md'), 'approved');
+
+ await store.remove('hello');
+
+ expect(fs.existsSync(receipt)).toBe(false);
+ expect(fs.existsSync(path.join(stateRoot, 'skill-snapshots', 'hello'))).toBe(false);
+ });
+
+ it('propagates transient snapshot-root IO failures so cleanup can be retried', async () => {
+ const snapshotsRoot = path.join(stateRoot, 'skill-snapshots');
+ const realLstat = fs.promises.lstat;
+ vi.spyOn(fs.promises, 'lstat').mockImplementation(async (target, options) => {
+ if (path.resolve(String(target)) === path.resolve(snapshotsRoot)) {
+ throw Object.assign(new Error('state root unreadable'), { code: 'EACCES' });
+ }
+ return realLstat(target, options as never);
+ });
+
+ await expect(store.remove('hello')).rejects.toThrow('state root unreadable');
+ });
+
+ it('propagates transient snapshot-root IO failures from synchronous recovery', () => {
+ const snapshotsRoot = path.join(stateRoot, 'skill-snapshots');
+ const realLstatSync = fs.lstatSync;
+ vi.spyOn(fs, 'lstatSync').mockImplementation((target, options) => {
+ if (path.resolve(String(target)) === path.resolve(snapshotsRoot)) {
+ throw Object.assign(new Error('state root unreadable'), { code: 'EIO' });
+ }
+ return realLstatSync(target, options as never);
+ });
+
+ expect(() => store.removeSync('hello')).toThrow('state root unreadable');
+ });
+
+ it('rejects a linked snapshot root without touching its target', async () => {
+ const external = path.join(workDir, 'external');
+ const sentinel = path.join(external, 'hello', 'sentinel.txt');
+ await fs.promises.mkdir(path.dirname(sentinel), { recursive: true });
+ await fs.promises.writeFile(sentinel, 'keep');
+ try {
+ await fs.promises.symlink(
+ external,
+ path.join(stateRoot, 'skill-snapshots'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+
+ await expect(store.remove('hello')).rejects.toThrow(
+ 'skill snapshot path segment is not a real directory',
+ );
+ expect(await fs.promises.readFile(sentinel, 'utf8')).toBe('keep');
+ });
+
+ it('rejects a linked receipt instead of treating it as cleaned', async () => {
+ const externalReceipt = path.join(workDir, 'external-receipt.json');
+ await fs.promises.writeFile(externalReceipt, '{}');
+ try {
+ await fs.promises.symlink(externalReceipt, path.join(stateRoot, 'hello.json'), 'file');
+ } catch {
+ return;
+ }
+
+ await expect(store.remove('hello')).rejects.toThrow(
+ 'ghost receipt path is not a regular file',
+ );
+ expect(await fs.promises.readFile(externalReceipt, 'utf8')).toBe('{}');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
index 2d280cae78..f054bf1d05 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts
@@ -7,6 +7,7 @@ import type {
} from '../../../shared/ghost';
import { MAKER_PUSH } from '../../maker-ipc/channels';
import { GhostSetupChangeBus } from '../ghostSetupChangeBus';
+import { GhostMutationCoordinator } from '../ghostMutationCoordinator';
import {
GhostSetupCoordinator,
type GhostSetupActionResult,
@@ -355,6 +356,51 @@ describe('GhostSetupCoordinator', () => {
await expect(waiting).resolves.toMatchObject({ ok: true });
});
+ it('keeps account-boundary action drain pending after the setup call is cancelled', async () => {
+ const h = harness(required());
+ const mutations = new GhostMutationCoordinator();
+ const releaseMutation = mutations.acquire();
+ let release!: () => void;
+ h.executeAction.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = () => resolve({ ok: true });
+ }),
+ );
+ const waiting = h.coordinator
+ .ensureReady({
+ sessionId: 'session-1',
+ ghostId: 'gmail',
+ tool: 'search',
+ })
+ .finally(releaseMutation);
+ await vi.waitFor(() => expect(h.bridge.pendingSnapshots()).toHaveLength(1));
+ const pending = h.bridge.pendingSnapshots()[0].request;
+ h.bridge.resolve(pending.requestId, {
+ kind: 'plugin_setup',
+ action: 'run_action',
+ actionId: 'oauth_connect:secret:google',
+ expectedRevision: pending.revision,
+ });
+ await vi.waitFor(() => expect(h.executeAction).toHaveBeenCalledOnce());
+
+ h.bridge.cleanupAll('session_aborted');
+ await expect(waiting).resolves.toMatchObject({ ok: false, errorCode: 'SETUP_CANCELLED' });
+
+ let drained = false;
+ const drain = (async () => {
+ await h.coordinator.waitForActionsIdle();
+ await mutations.waitForIdle();
+ drained = true;
+ })();
+ await Promise.resolve();
+ expect(drained).toBe(false);
+
+ release();
+ await drain;
+ expect(drained).toBe(true);
+ });
+
it('publishes action error codes without copying Main diagnostic messages', async () => {
const h = harness(required());
h.executeAction.mockResolvedValue({
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
index f280506190..02f256a1e5 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInteractionBridge.test.ts
@@ -155,6 +155,30 @@ describe('GhostSetupInteractionBridge', () => {
});
});
+ it('turns account-boundary cleanup into cancel commands for every session', async () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const bridge = new GhostSetupInteractionBridge({ broadcast: vi.fn() });
+ bridge.open('session-1', snapshot(4), first);
+ bridge.open('session-2', { ...snapshot(7), requestId: 'request-2' }, second);
+
+ bridge.cleanupAll('session_aborted');
+ await Promise.resolve();
+
+ expect(first).toHaveBeenCalledWith({
+ kind: 'plugin_setup',
+ action: 'cancel',
+ expectedRevision: 4,
+ cleanupReason: 'session_aborted',
+ });
+ expect(second).toHaveBeenCalledWith({
+ kind: 'plugin_setup',
+ action: 'cancel',
+ expectedRevision: 7,
+ cleanupReason: 'session_aborted',
+ });
+ });
+
it('rolls back pending state when the initial broadcast fails', () => {
const bridge = new GhostSetupInteractionBridge({
broadcast: () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index b897b7634b..8b764bde11 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -58,4 +58,16 @@ describe('market Ghost session boundary', () => {
expect(leaseIndex).toBeGreaterThan(inspectIndex);
expect(body).toContain('releaseMutation?.();');
});
+
+ it('fails owner-scoped plugin reads closed while an account boundary is pending', () => {
+ const start = source.indexOf('function availableGhosts(): InstalledGhost[] {');
+ const end = source.indexOf('\n}', start);
+ const body = source.slice(start, end);
+ expect(body).toContain('if (isAppSessionBoundaryPending()) return [];');
+ expect(source).toContain(
+ 'return availableGhosts().find((ghost) => ghost.manifest.id === id) ?? null;',
+ );
+ expect(source.match(/getGhost: findAvailableGhost/g)?.length ?? 0).toBeGreaterThanOrEqual(3);
+ expect(source).toContain('return findAvailableGhost(id)?.manifest.name ?? null;');
+ });
});
diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index 9ea4a12b28..96c38fba2c 100644
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@ -5,11 +5,13 @@ import crypto from 'node:crypto';
import {
GHOST_MANIFEST_FILE,
ghostIconMimeType,
+ isValidGhostId,
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
import {
classifyGhostDirEntry,
+ classifyGhostDirEntrySync,
collectGhostContentFiles,
hashGhostContentFiles,
resolveGhostContentPathSync,
@@ -103,6 +105,14 @@ export interface ProvisionDeps {
identity?: ProvisionIdentity | null;
/** 回收删除某个意识目录之前的钩子(index.ts 用它先熄灯沙箱,防 Windows 文件锁)。 */
beforeRemove?: (id: string) => void | Promise<void>;
+ /** Replacing existing bundled bytes must revoke the old Host receipt first. */
+ beforeReplace?: (id: string) => void | Promise<void>;
+ /** Production path publishes through GhostManager's durable pending journal. */
+ publishSeed?: (
+ id: string,
+ seedDir: string,
+ options: { disabled: boolean },
+ ) => void | Promise<void>;
/**
* 首次真实变更(装/覆盖/回收)动手前回调,整轮至多一次 —— index.ts 用它
* 广播"播种进行中"的 UI 提示;指纹全一致的 no-op 轮永不触发(不闪提示)。
@@ -114,6 +124,8 @@ export interface ProvisionDeps {
export interface ProvisionOutcome {
/** First-party seed manifests whose installed bytes reconciled successfully. */
approved: GhostManifest[];
+ /** Immutable seed source for each approved manifest; receipt baselines must use it. */
+ approvedSourceDirs: Record<string, string>;
/** 本次首装的意识(装完默认唤醒;调用方负责停靠面板 + 广播 + 常驻点火)。 */
installed: GhostManifest[];
/** 本次覆盖更新的意识(`.disabled` 已保留;调用方负责广播)。 */
@@ -132,6 +144,56 @@ interface ProvisioningState {
seeded: string[];
}
+interface ProvisioningStateRead {
+ state: ProvisioningState;
+ readable: boolean;
+}
+
+/** Managed roots must not traverse a symlink/junction in any path segment. */
+function isRealDirectoryPath(absPath: string, allowMissingLeaf = false): boolean {
+ const resolved = path.resolve(absPath);
+ const parsed = path.parse(resolved);
+ let current = parsed.root;
+ const segments = path.relative(parsed.root, resolved).split(path.sep).filter(Boolean);
+ for (const [index, segment] of segments.entries()) {
+ current = path.join(current, segment);
+ let stat: fs.Stats;
+ try {
+ stat = fs.lstatSync(current);
+ } catch (err) {
+ if (
+ allowMissingLeaf &&
+ index === segments.length - 1 &&
+ (err as NodeJS.ErrnoException).code === 'ENOENT'
+ ) {
+ return true;
+ }
+ return false;
+ }
+ if (!stat.isDirectory() || stat.isSymbolicLink()) return false;
+ }
+ return true;
+}
+
+/** Verify that an approval source is the exact, link-free bundled seed directory for an id. */
+export function isTrustedBuiltinSeedSource(
+ seedRootDirs: string[],
+ id: string,
+ sourceDir: string,
+): boolean {
+ if (!isValidGhostId(id)) return false;
+ const resolvedSource = path.resolve(sourceDir);
+ return seedRootDirs.some((root) => {
+ const resolvedRoot = path.resolve(root);
+ const expectedSource = path.join(resolvedRoot, id);
+ return (
+ resolvedSource === expectedSource &&
+ isRealDirectoryPath(resolvedRoot) &&
+ isRealDirectoryPath(expectedSource)
+ );
+ });
+}
+
/** 列出多个种子根下的意识 id 并集(去重排序)。根缺失/为空按无种子处理。 */
export function listBuiltinSeedIds(seedRootDirs: string[]): string[] {
const ids = new Set<string>();
@@ -169,6 +231,7 @@ export function listEligibleBuiltinCommands(
/** 列出单个种子根下的意识 id(= 子目录名;点开头跳过)。种子根缺失返回空。 */
function listSeedIdsInRoot(seedRootDir: string): string[] {
+ if (!isRealDirectoryPath(seedRootDir)) return [];
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(seedRootDir, { withFileTypes: true });
@@ -183,66 +246,189 @@ function listSeedIdsInRoot(seedRootDir: string): string[] {
/** 读墓碑列表(状态文件缺失 / 损坏一律当空,不阻断播种)。 */
export function readBuiltinTombstones(repoRootDir: string): string[] {
- return readState(repoRootDir).removed;
+ const result = readState(repoRootDir);
+ if (!result.readable) {
+ throw new Error('builtin provisioning state is unreadable');
+ }
+ return result.state.removed;
}
/** 记墓碑(幂等)。用户卸载内置意识时由 IPC 层调用;同时从 seeded 台账摘除。 */
-export function recordBuiltinTombstone(repoRootDir: string, id: string, log?: BuiltinProvisionerLogger): void {
- const state = readState(repoRootDir);
+export function recordBuiltinTombstone(
+ repoRootDir: string,
+ id: string,
+ log?: BuiltinProvisionerLogger,
+): void {
+ if (!isValidGhostId(id)) throw new Error('invalid builtin tombstone id');
+ const result = readState(repoRootDir, log);
+ if (!result.readable) throw new Error('builtin provisioning state is unreadable');
+ const state = result.state;
if (state.removed.includes(id) && !state.seeded.includes(id)) return;
- writeState(
+ if (!writeState(
repoRootDir,
{
removed: state.removed.includes(id) ? state.removed : [...state.removed, id],
seeded: state.seeded.filter((v) => v !== id),
},
log,
- );
+ )) {
+ throw new Error('builtin provisioning state write failed');
+ }
}
/** 清墓碑(幂等)。用户手动重装同 id 意识 = 重新跟随包内版本。 */
-export function clearBuiltinTombstone(repoRootDir: string, id: string, log?: BuiltinProvisionerLogger): void {
- const state = readState(repoRootDir);
+export function clearBuiltinTombstone(
+ repoRootDir: string,
+ id: string,
+ log?: BuiltinProvisionerLogger,
+): void {
+ if (!isValidGhostId(id)) throw new Error('invalid builtin tombstone id');
+ const result = readState(repoRootDir, log);
+ if (!result.readable) throw new Error('builtin provisioning state is unreadable');
+ const state = result.state;
if (!state.removed.includes(id)) return;
- writeState(repoRootDir, { ...state, removed: state.removed.filter((v) => v !== id) }, log);
+ if (!writeState(repoRootDir, { ...state, removed: state.removed.filter((v) => v !== id) }, log)) {
+ throw new Error('builtin provisioning state write failed');
+ }
}
-function readState(repoRootDir: string): ProvisioningState {
- const empty: ProvisioningState = { removed: [], seeded: [] };
+/** Carry a removed builtin across an id rename in one atomic state replacement. */
+export function renameBuiltinTombstone(
+ repoRootDir: string,
+ fromId: string,
+ toId: string,
+ log?: BuiltinProvisionerLogger,
+): boolean {
+ if (!isValidGhostId(fromId) || !isValidGhostId(toId)) {
+ throw new Error('invalid builtin tombstone rename');
+ }
+ const result = readState(repoRootDir, log);
+ if (!result.readable) throw new Error('builtin provisioning state is unreadable');
+ const state = result.state;
+ if (!state.removed.includes(fromId)) return false;
+ const removed = state.removed.filter((id) => id !== fromId && id !== toId);
+ removed.push(toId);
+ if (
+ !writeState(
+ repoRootDir,
+ {
+ removed,
+ seeded: state.seeded.filter((id) => id !== toId),
+ },
+ log,
+ )
+ ) {
+ throw new Error('builtin provisioning state write failed');
+ }
+ return true;
+}
+
+function readState(repoRootDir: string, log?: BuiltinProvisionerLogger): ProvisioningStateRead {
+ const empty: ProvisioningStateRead = {
+ state: { removed: [], seeded: [] },
+ readable: true,
+ };
+ const file = path.join(repoRootDir, PROVISIONING_STATE_FILE);
try {
- const raw = JSON.parse(fs.readFileSync(path.join(repoRootDir, PROVISIONING_STATE_FILE), 'utf-8')) as unknown;
- if (typeof raw !== 'object' || raw === null) return empty;
+ const stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink()) {
+ log?.warn('builtin provisioning state is not a regular file', { file });
+ return { ...empty, readable: false };
+ }
+ const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown;
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
+ log?.warn('builtin provisioning state is invalid', { file });
+ return { ...empty, readable: false };
+ }
const obj = raw as { removed?: unknown; seeded?: unknown };
+ if (
+ (obj.removed !== undefined && !Array.isArray(obj.removed)) ||
+ (obj.seeded !== undefined && !Array.isArray(obj.seeded))
+ ) {
+ log?.warn('builtin provisioning state has invalid fields', { file });
+ return { ...empty, readable: false };
+ }
+ const removed = Array.isArray(obj.removed)
+ ? obj.removed.filter((v): v is string => typeof v === 'string')
+ : [];
+ const seeded = Array.isArray(obj.seeded)
+ ? obj.seeded.filter((v): v is string => typeof v === 'string')
+ : [];
+ if (
+ (Array.isArray(obj.removed) && removed.length !== obj.removed.length) ||
+ (Array.isArray(obj.seeded) && seeded.length !== obj.seeded.length) ||
+ removed.some((id) => !isValidGhostId(id)) ||
+ seeded.some((id) => !isValidGhostId(id))
+ ) {
+ log?.warn('builtin provisioning state contains invalid ghost id', { file });
+ return { ...empty, readable: false };
+ }
return {
- removed: Array.isArray(obj.removed) ? obj.removed.filter((v): v is string => typeof v === 'string') : [],
- seeded: Array.isArray(obj.seeded) ? obj.seeded.filter((v): v is string => typeof v === 'string') : [],
+ state: { removed, seeded },
+ readable: true,
};
- } catch {
- return empty;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return empty;
+ log?.warn('builtin provisioning state unreadable', {
+ file,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return { ...empty, readable: false };
}
}
-function writeState(repoRootDir: string, state: ProvisioningState, log?: BuiltinProvisionerLogger): void {
+function writeState(
+ repoRootDir: string,
+ state: ProvisioningState,
+ log?: BuiltinProvisionerLogger,
+): boolean {
+ const file = path.join(repoRootDir, PROVISIONING_STATE_FILE);
+ const temp = path.join(
+ repoRootDir,
+ `.${PROVISIONING_STATE_FILE}.tmp-${crypto.randomBytes(8).toString('hex')}`,
+ );
try {
+ if (!isRealDirectoryPath(repoRootDir, true)) {
+ throw new Error('builtin provisioning repo root is not a real directory');
+ }
fs.mkdirSync(repoRootDir, { recursive: true });
- fs.writeFileSync(path.join(repoRootDir, PROVISIONING_STATE_FILE), `${JSON.stringify(state, null, 2)}\n`);
+ fs.writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`, {
+ encoding: 'utf8',
+ flag: 'wx',
+ });
+ const tempStat = fs.lstatSync(temp);
+ if (!tempStat.isFile() || tempStat.isSymbolicLink()) {
+ throw new Error('builtin provisioning temporary state is not a regular file');
+ }
+ fs.renameSync(temp, file);
+ return true;
} catch (err) {
// 状态写失败不致命(最坏情况:卸载的内置意识下次启动弹回来一次),warn 留痕。
log?.warn('builtin provisioning state write failed', {
error: err instanceof Error ? err.message : String(err),
});
+ try {
+ fs.rmSync(temp, { force: true });
+ } catch {
+ // Preserve the original failure; the next reconciliation retries the write.
+ }
+ return false;
}
}
/** 受众命中判定(纯函数,fail-closed:不认识的规则形态一律不命中)。 */
-export function matchesAudience(rule: AudienceRule | undefined, identity: ProvisionIdentity | null): boolean {
+export function matchesAudience(
+ rule: AudienceRule | undefined,
+ identity: ProvisionIdentity | null,
+): boolean {
if (rule === undefined || rule === 'all') return true;
if (typeof rule !== 'object' || rule === null) return false;
if (identity === null) return false;
if (Array.isArray(rule.userIds) && rule.userIds.includes(identity.userId)) return true;
if (Array.isArray(rule.emails) && identity.email !== null) {
const emailFold = identity.email.toLowerCase();
- if (rule.emails.some((e) => typeof e === 'string' && e.toLowerCase() === emailFold)) return true;
+ if (rule.emails.some((e) => typeof e === 'string' && e.toLowerCase() === emailFold))
+ return true;
}
return false;
}
@@ -275,10 +461,12 @@ function readProvisioningConfig(
if (typeof raw !== 'object' || raw === null) throw new Error('config root must be an object');
const ghosts = (raw as { ghosts?: unknown }).ghosts;
if (ghosts === undefined) return new Map();
- if (typeof ghosts !== 'object' || ghosts === null) throw new Error('"ghosts" must be an object');
+ if (typeof ghosts !== 'object' || ghosts === null)
+ throw new Error('"ghosts" must be an object');
const map = new Map<string, SeedConfigEntry>();
for (const [id, entry] of Object.entries(ghosts as Record<string, unknown>)) {
- if (typeof entry !== 'object' || entry === null) throw new Error(`ghosts["${id}"] must be an object`);
+ if (typeof entry !== 'object' || entry === null)
+ throw new Error(`ghosts["${id}"] must be an object`);
const audience = (entry as { audience?: unknown }).audience;
const tier = (entry as { tier?: unknown }).tier;
// tier 只认 'builtin' / 'enterprise'(缺省 builtin);写错整份配置按损坏
@@ -313,6 +501,7 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
const identity = deps.identity ?? null;
const outcome: ProvisionOutcome = {
approved: [],
+ approvedSourceDirs: {},
installed: [],
updated: [],
removed: [],
@@ -326,14 +515,27 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
return {
root,
ids,
- config: ids.length === 0 ? new Map<string, SeedConfigEntry>() : readProvisioningConfig(root, log),
+ config:
+ ids.length === 0 ? new Map<string, SeedConfigEntry>() : readProvisioningConfig(root, log),
};
});
const allSeedIds = new Set(rootStates.flatMap((s) => s.ids));
if (allSeedIds.size === 0) return outcome;
const hasEmptyRoot = rootStates.some((s) => s.ids.length === 0);
- const state = readState(repoRootDir);
+ if (!isRealDirectoryPath(repoRootDir, true)) {
+ log?.warn('builtin provisioning skipped: repo root is not a real directory', {
+ repoRootDir,
+ });
+ outcome.skipped.push(...allSeedIds);
+ return outcome;
+ }
+ const stateResult = readState(repoRootDir, log);
+ if (!stateResult.readable) {
+ outcome.skipped.push(...allSeedIds);
+ return outcome;
+ }
+ const state = stateResult.state;
const tombstones = new Set(state.removed);
const seeded = new Set(state.seeded);
const seededBefore = new Set(seeded);
@@ -354,6 +556,8 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
continue;
}
for (const id of ids) {
+ const ownedBeforeAttempt = seeded.has(id);
+ let ownershipClaimPersisted = false;
if (processed.has(id)) {
log?.warn('builtin seed skipped: duplicate id across seed roots', { id, root });
outcome.skipped.push(id);
@@ -378,7 +582,15 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
}
const installedDir = path.join(repoRootDir, id);
- const installedExists = fs.existsSync(path.join(installedDir, GHOST_MANIFEST_FILE));
+ const installedExists =
+ isRealDirectoryPath(installedDir) &&
+ (() => {
+ try {
+ return classifyGhostDirEntrySync(path.join(installedDir, GHOST_MANIFEST_FILE)) === 'file';
+ } catch {
+ return false;
+ }
+ })();
// 3) 受众:不命中 → 回收"播种装的"(seeded 台账内),手动装的不动。
if (!matchesAudience(config.get(id)?.audience, identity)) {
@@ -412,25 +624,57 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
seedFingerprint.hash === installedFingerprint.hash
) {
outcome.approved.push(manifest);
+ outcome.approvedSourceDirs[id] = seedDir;
outcome.skipped.push(id);
continue;
}
- const wasDisabled = fs.existsSync(path.join(installedDir, '.disabled'));
+ const wasDisabled = (() => {
+ try {
+ classifyGhostDirEntrySync(path.join(installedDir, '.disabled'));
+ return true;
+ } catch {
+ return false;
+ }
+ })();
markApplyStart();
- await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: wasDisabled });
+ // Claim seeded ownership durably before exchanging bytes. If the process
+ // dies after the swap but before the end-of-pass ledger write, the next
+ // reconciliation still knows this id is eligible for audience cleanup.
seeded.add(id);
+ if (!writeState(repoRootDir, { removed: [...tombstones], seeded: [...seeded].sort() }, log)) {
+ seeded.delete(id);
+ throw new Error('builtin seeded ledger could not be persisted before replacement');
+ }
+ ownershipClaimPersisted = true;
+ await deps.beforeReplace?.(id);
+ if (deps.publishSeed) await deps.publishSeed(id, seedDir, { disabled: wasDisabled });
+ else await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: wasDisabled });
outcome.approved.push(manifest);
+ outcome.approvedSourceDirs[id] = seedDir;
outcome.updated.push(manifest);
log?.info('builtin ghost updated to bundled content', { id, version: manifest.version });
} else {
markApplyStart();
- await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: false });
seeded.add(id);
+ if (!writeState(repoRootDir, { removed: [...tombstones], seeded: [...seeded].sort() }, log)) {
+ seeded.delete(id);
+ throw new Error('builtin seeded ledger could not be persisted before install');
+ }
+ ownershipClaimPersisted = true;
+ if (deps.publishSeed) await deps.publishSeed(id, seedDir, { disabled: false });
+ else await swapInSeed(seedDir, installedDir, repoRootDir, id, { disabled: false });
outcome.approved.push(manifest);
+ outcome.approvedSourceDirs[id] = seedDir;
outcome.installed.push(manifest);
log?.info('builtin ghost installed', { id, version: manifest.version });
}
} catch (err) {
+ // Existing ownership must survive a failed audience/orphan cleanup so the
+ // next reconciliation retries instead of permanently forgetting an
+ // installed approved plugin. Likewise, once a new ownership claim was
+ // durably committed before publish/replace, keep it: the mutation may
+ // have partially changed bytes or approval state before throwing.
+ if (!ownedBeforeAttempt && !ownershipClaimPersisted) seeded.delete(id);
outcome.skipped.push(id);
log?.warn('builtin ghost provisioning failed', {
id,
@@ -447,14 +691,30 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
// 半初始化保护(多根拆分后新增):任一根为空说明该根 submodule 很可能没
// checkout,其种子全集不可知 —— 本轮跳过孤儿回收,宁可留旧包也不误删。
if (hasEmptyRoot) {
- log?.info('builtin ghost orphan recovery skipped: empty seed root (submodule not initialized?)', {
- emptyRoots: rootStates.filter((s) => s.ids.length === 0).map((s) => s.root),
- });
+ log?.info(
+ 'builtin ghost orphan recovery skipped: empty seed root (submodule not initialized?)',
+ {
+ emptyRoots: rootStates.filter((s) => s.ids.length === 0).map((s) => s.root),
+ },
+ );
} else {
for (const id of [...seeded]) {
+ if (!isValidGhostId(id)) {
+ log?.warn('builtin ghost orphan id is invalid; skipped', { id });
+ continue;
+ }
if (allSeedIds.has(id)) continue;
const installedDir = path.join(repoRootDir, id);
- if (fs.existsSync(path.join(installedDir, GHOST_MANIFEST_FILE))) {
+ if (
+ isRealDirectoryPath(installedDir) &&
+ (() => {
+ try {
+ return classifyGhostDirEntrySync(path.join(installedDir, GHOST_MANIFEST_FILE)) === 'file';
+ } catch {
+ return false;
+ }
+ })()
+ ) {
try {
markApplyStart();
await deps.beforeRemove?.(id);
@@ -546,7 +806,10 @@ export function listRestorableBuiltinGhosts(deps: {
* 纯展示用途(设置页分组/打标),配置缺失或损坏按根降级成"全归内置组"
* 而不是报错,不影响播种主流程。
*/
-export function listEnterpriseSeedIds(seedRootDirs: string[], log?: BuiltinProvisionerLogger): string[] {
+export function listEnterpriseSeedIds(
+ seedRootDirs: string[],
+ log?: BuiltinProvisionerLogger,
+): string[] {
const ids = new Set<string>();
for (const root of seedRootDirs) {
const rootIds = listSeedIdsInRoot(root);
@@ -591,7 +854,11 @@ function setsEqual(a: Set<string>, b: Set<string>): boolean {
}
/** 读并校验种子 manifest;不合格返回 null(warn 留痕)。 */
-function readSeedManifest(seedDir: string, id: string, log?: BuiltinProvisionerLogger): GhostManifest | null {
+function readSeedManifest(
+ seedDir: string,
+ id: string,
+ log?: BuiltinProvisionerLogger,
+): GhostManifest | null {
let raw: unknown;
try {
raw = JSON.parse(fs.readFileSync(path.join(seedDir, GHOST_MANIFEST_FILE), 'utf-8'));
@@ -608,7 +875,10 @@ function readSeedManifest(seedDir: string, id: string, log?: BuiltinProvisionerL
return null;
}
if (v.manifest.id !== id) {
- log?.warn('builtin seed skipped: dir name != manifest id', { seedDir, manifestId: v.manifest.id });
+ log?.warn('builtin seed skipped: dir name != manifest id', {
+ seedDir,
+ manifestId: v.manifest.id,
+ });
return null;
}
const localeValidation = validateGhostLocaleResourcesInDirectory(seedDir, v.manifest);
diff --git a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
index 546427ba04..f9ce11393b 100644
--- a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts
@@ -174,6 +174,13 @@ export class GhostGrantConfirmBridge {
}
}
+ /** Account/data-owner boundary: fail closed every pending grant before waiting on owner leases. */
+ cleanupAll(reason: 'session_closed' | 'session_aborted'): void {
+ for (const requestId of Array.from(this.pending.keys())) {
+ this.settle(requestId, { confirmed: false, reason }, reason);
+ }
+ }
+
/** 内部统一收口:resolve + 清 pending + 广播 DISMISSED 让 renderer 关卡片。 */
private settle(
requestId: string,
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index ea7701dd75..765bc7ee5f 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -29,13 +29,13 @@ import { checkSkillMdConsistency } from './skillSlot.js';
// 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}$/;
+const ICON_DATA_URL_RE = /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/;
/**
* 一次明确批准的插件安装事实;只允许 Host 写入安装目录之外的状态根。
@@ -75,6 +75,12 @@ export type GhostInstallReceiptReadResult =
| { 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,不再触发迁移。
@@ -126,17 +132,31 @@ export interface GhostLegacyMigrationLedger {
* 不等/缺失 = 未提交。两者都是已落盘事实,判定不引入额外写窗口。
*/
export type GhostPendingMutation =
- | { kind: 'install'; packageSha256: string }
- | { kind: 'update'; packageSha256: string; backupDirName: string }
+ | { kind: 'install'; packageSha256: string; clearBuiltinTombstone?: boolean }
+ | {
+ kind: 'update';
+ packageSha256: string;
+ backupDirName: 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' };
+ | { 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 {
- /** receipt 首写后的自动落账写失败(进程内关门标志,见 migrationDoorClosed)。 */
- private autoLedgerWriteFailed = false;
-
constructor(private readonly getRootDir: () => string) {}
rootDir(): string {
@@ -144,34 +164,49 @@ export class GhostInstallReceiptStore {
}
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;
try {
stat = fs.lstatSync(receiptPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
- return { state: 'legacy-unapproved' };
+ return { state: 'missing' };
}
return {
- state: 'invalid',
+ state: 'unreadable',
reason: error instanceof Error ? error.message : String(error),
};
}
if (!stat.isFile() || stat.size > MAX_RECEIPT_BYTES) {
return { state: 'invalid', reason: 'receipt 不是普通文件或超过大小上限' };
}
+ let text: string;
try {
- const parsed = JSON.parse(fs.readFileSync(receiptPath, 'utf8')) as unknown;
- const validated = validateReceipt(parsed, id);
- return validated.ok
- ? { state: 'approved', receipt: validated.receipt }
- : { state: 'invalid', reason: validated.reason };
+ text = fs.readFileSync(receiptPath, 'utf8');
} catch (error) {
return {
- state: 'invalid',
+ 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) };
+ }
+ const validated = validateReceipt(parsed, id);
+ return validated.ok
+ ? { state: 'approved', receipt: validated.receipt }
+ : { state: 'invalid', reason: validated.reason };
}
/**
@@ -187,7 +222,8 @@ export class GhostInstallReceiptStore {
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}`);
+ 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 });
@@ -196,6 +232,19 @@ export class GhostInstallReceiptStore {
} 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,
@@ -211,46 +260,25 @@ export class GhostInstallReceiptStore {
} finally {
await fs.promises.rm(temp, { force: true }).catch(() => undefined);
}
- // 首次写 receipt 即落迁移台账,把一次性门在"新模型开始活动"那一刻关死。
- // 不落的话有一个窗口:新装 receipt 后、下一轮 reconcile 前,删掉唯一的 receipt
- // 会让 hasAnyReceipt 判据也失效(ledger 尚未写),"改 manifest → 删 receipt →
- // 骗 backfill"就能凭空铸出扩权批准。台账写失败不阻断本次批准(状态根刚写成功,
- // 失败面极窄),下一轮迁移检查的 hasAnyReceipt 判据会兜住并补写。
- // 只在**完全没有**台账时落 completed:迁移进行中(in-progress)的台账绝不能被
- // backfill 自己的 receipt 首写覆盖成"已完成",否则中途崩溃后剩余插件永不迁。
- if (!this.hasMigrationLedger()) {
- await this
- .writeMigrationLedger({
- version: 1,
- migratedAt: new Date().toISOString(),
- migratedIds: [],
- state: 'completed',
- })
- .catch(() => {
- // 不作 best-effort 吞掉:置进程内关门标志(migrationDoorClosed 优先读它),
- // 消除"落账失败 + 同会话删 receipt → 骗重铸"的窗口。批准本身不回滚 ——
- // receipt 刚写进同一目录,此处失败面极窄,且下次启动会经 hasAnyValidReceipt
- // 判据补写台账。
- this.autoLedgerWriteFailed = true;
- });
- }
await this.pruneStaleSkillSnapshots(receipt);
}
async remove(id: string): Promise<void> {
- await fs.promises.rm(this.receiptPath(id), { force: true });
- // `skill-snapshots` 段必须是真目录才能递归删 `<id>`:该段被换成 junction 时,
- // recursive rm 会穿透删外部目录内容。`<id>` 自身是链接没关系 —— rm 按 lstat
- // 语义只摘链接本体,不进目标。段可疑/缺失就跳过(receipt 已删,批准已失效)。
- const snapshotsDir = path.join(this.rootDir(), 'skill-snapshots');
- let kind: string;
- try {
- kind = await classifyGhostDirEntry(snapshotsDir);
- } catch {
- return;
+ 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 });
}
- if (kind !== 'directory') return;
- await fs.promises.rm(path.join(snapshotsDir, id), {
+ // 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,
});
@@ -258,16 +286,18 @@ export class GhostInstallReceiptStore {
/** `remove` 的同步版:启动恢复(构造期同步)收尾未完成卸载用,判据同 `remove`。 */
removeSync(id: string): void {
- fs.rmSync(this.receiptPath(id), { force: true });
- const snapshotsDir = path.join(this.rootDir(), 'skill-snapshots');
- let kind: string;
- try {
- kind = classifyGhostDirEntrySync(snapshotsDir);
- } catch {
- return;
+ 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 });
}
- if (kind !== 'directory') return;
- fs.rmSync(path.join(snapshotsDir, id), { recursive: true, 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 {
@@ -329,48 +359,71 @@ export class GhostInstallReceiptStore {
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');
}
- /**
- * 状态根里是否已有任何**有效** receipt。它是迁移门的第二道判据:有有效 receipt
- * = 新模型已在本机运转过,此后缺某个 receipt 只能是删除,不再触发迁移 ——
- * 否则"空目录首启不落 ledger"(为给 legacy 恢复流程留门)会让删 receipt 骗迁移
- * 复活。ENOENT = 状态根未诞生,按无 receipt 处理。
- *
- * 只认**有效**而不是"存在 json 文件":损坏/旧 schema 的 receipt 正是 §5 要求迁移
- * 治愈的对象(如从未发布的 v1 格式),把它当"活动过"会把治愈路径堵死。能把 receipt
- * 改坏的进程需要状态根写权限,与 §7 登记的"可伪造合法 receipt"是同一攻击者类,
- * 此判据不给它新增能力。
- */
- hasAnyValidReceipt(): boolean {
- try {
- return fs
- .readdirSync(this.rootDir(), { withFileTypes: true })
- .some((entry) => {
- if (!entry.isFile() || !entry.name.endsWith('.json')) return false;
- const id = entry.name.slice(0, -'.json'.length);
- return isValidGhostId(id) && this.read(id).state === 'approved';
- });
- } catch (error) {
- // 与 hasMigrationLedger 同一保守方向:读不动就当"有",绝不因此把迁移放开。
- return (error as NodeJS.ErrnoException).code !== 'ENOENT';
- }
- }
-
/** 读迁移台账(缺失/损坏返回 null;追加 id 时用,判定门只看 hasMigrationLedger)。 */
readMigrationLedger(): GhostLegacyMigrationLedger | null {
try {
const raw = JSON.parse(
fs.readFileSync(this.migrationLedgerPath(), 'utf8'),
) as GhostLegacyMigrationLedger;
- if (!raw || raw.version !== 1 || !Array.isArray(raw.migratedIds)) return null;
+ 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.state === 'in-progress' && !Array.isArray(raw.pendingIds)) 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;
@@ -387,11 +440,6 @@ export class GhostInstallReceiptStore {
* 给这类进程送一条重铸授权的路。调用方发现"存在但读不出"应记 error 日志。
*/
migrationDoorClosed(): boolean {
- // 进程内保险门:receipt 首写后的自动落账写失败时置位(见 write())。没有它,
- // "落账失败 + 同会话内 receipt 又被删"的组合会让 hasAnyValidReceipt 判据也
- // 失效,可变 manifest 就能骗一次重铸 —— 状态根刚成功写过 receipt,门在本进程
- // 内必须视为已关;下次启动 hasAnyValidReceipt 或补写成功的台账接棒。
- if (this.autoLedgerWriteFailed) return true;
if (!this.hasMigrationLedger()) return false;
const ledger = this.readMigrationLedger();
return ledger === null || ledger.state !== 'in-progress';
@@ -465,38 +513,132 @@ export class GhostInstallReceiptStore {
fs.rmSync(this.pendingMutationPath(id), { force: true });
}
- readPendingMutationSync(id: string): GhostPendingMutation | null {
+ readPendingMutationSync(id: string): GhostPendingMutationReadResult {
let raw: Record<string, unknown>;
+ const markerPath = this.pendingMutationPath(id);
try {
- raw = JSON.parse(fs.readFileSync(this.pendingMutationPath(id), 'utf8')) as Record<string, unknown>;
- } catch {
- return null;
+ 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 (raw.kind === 'uninstall') return { kind: 'uninstall' };
if (typeof raw.packageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(raw.packageSha256)) {
- return null;
+ return { state: 'invalid', reason: 'journal packageSha256 is invalid' };
}
- if (raw.kind === 'install') return { kind: 'install', packageSha256: raw.packageSha256 };
- if (raw.kind === 'update' && typeof raw.backupDirName === 'string') {
- return { kind: 'update', packageSha256: raw.packageSha256, backupDirName: raw.backupDirName };
+ if (raw.kind === 'install') {
+ 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,
+ ...(raw.clearBuiltinTombstone === true ? { clearBuiltinTombstone: true } : {}),
+ },
+ };
}
- return null;
+ 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;
+ 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,
+ ...(phase !== undefined ? { phase } : {}),
+ ...(oldPackageSha256 !== undefined ? { oldPackageSha256 } : {}),
+ },
+ };
+ }
+ return { state: 'invalid', reason: 'journal kind/backupDirName is invalid' };
}
/** 状态根里所有未清的事务标记 id(启动恢复用)。 */
- listPendingMutationIdsSync(): string[] {
+ listPendingMutationIdsSync(): GhostPendingMutationListResult {
let names: string[];
try {
names = fs.readdirSync(this.rootDir());
- } catch {
- return [];
+ } 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 && isValidGhostId(match[1])) ids.push(match[1]);
+ if (!match) continue;
+ if (isValidGhostId(match[1])) ids.push(match[1]);
+ else blocked = true;
}
- return ids;
+ return { state: 'ok', ids, blocked };
}
private receiptPath(id: string): string {
@@ -658,9 +800,7 @@ export class GhostInstallReceiptStore {
receipt: GhostInstallReceipt,
snapshotDir: string,
): Promise<boolean> {
- const actual = await hashApprovedSkillContent(receipt.manifest, snapshotDir).catch(
- () => null,
- );
+ 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],
@@ -706,6 +846,42 @@ export class GhostInstallReceiptStore {
}
}
+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。
@@ -851,23 +1027,23 @@ function validateReceipt(
}
if (
value.iconDataUrl !== undefined &&
- (
- typeof value.iconDataUrl !== 'string' ||
+ (typeof value.iconDataUrl !== 'string' ||
Buffer.byteLength(value.iconDataUrl, 'utf8') > MAX_ICON_DATA_URL_BYTES ||
- !ICON_DATA_URL_RE.test(value.iconDataUrl)
- )
+ !ICON_DATA_URL_RE.test(value.iconDataUrl))
) {
return { ok: false, reason: 'receipt iconDataUrl 不合法' };
}
- if (!value.localeResources || typeof value.localeResources !== 'object' || Array.isArray(value.localeResources)) {
+ 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();
+ const actualLocalePaths = Object.keys(value.localeResources as Record<string, unknown>).sort();
if (
expectedLocalePaths.length !== actualLocalePaths.length ||
expectedLocalePaths.some((localePath, index) => localePath !== actualLocalePaths[index])
@@ -896,18 +1072,14 @@ function validateReceipt(
enabled: value.enabled,
trust,
skillContentSha256,
- ...(typeof value.packageSha256 === 'string'
- ? { packageSha256: value.packageSha256 }
- : {}),
+ ...(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,
- );
+ 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> {
@@ -948,11 +1120,7 @@ function validateTrust(raw: unknown): GhostTrustInfo | null {
) {
return null;
}
- const optionalStrings = [
- 'publisherName',
- 'publisherKeyId',
- 'reviewerName',
- ] as const;
+ const optionalStrings = ['publisherName', 'publisherKeyId', 'reviewerName'] as const;
for (const key of optionalStrings) {
if (value[key] !== undefined && typeof value[key] !== 'string') return null;
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
index a932590f10..e6f2d1b8fb 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts
@@ -113,9 +113,23 @@ const DEFAULT_TERMINAL_GRACE_MS = 700;
export class GhostSetupCoordinator {
private readonly actionFlights = new Map<string, Promise<GhostSetupActionResult>>();
+ private readonly activeActions = new Set<Promise<unknown>>();
constructor(private readonly deps: GhostSetupCoordinatorDeps) {}
+ /** Account-boundary drain for Host actions that outlive a cancelled setup card. */
+ async waitForActionsIdle(): Promise<void> {
+ while (this.activeActions.size > 0) {
+ await Promise.allSettled([...this.activeActions]);
+ }
+ }
+
+ private trackAction<T>(promise: Promise<T>): Promise<T> {
+ this.activeActions.add(promise);
+ void promise.finally(() => this.activeActions.delete(promise)).catch(() => undefined);
+ return promise;
+ }
+
async ensureReady(request: GhostSetupEnsureRequest): Promise<GhostSetupEnsureResult> {
let assessment: GhostSetupAssessment;
let unsubscribe = () => {};
@@ -348,14 +362,16 @@ export class GhostSetupCoordinator {
const flightKey = `${request.ghostId}\u0000${action.id}\u0000${flightScope}`;
let flight = this.actionFlights.get(flightKey);
if (!flight) {
- flight = this.deps
- .executeAction({
- sessionId,
- ghostId: request.ghostId,
- action,
- ...(responseTarget ? { responseTarget } : {}),
- })
- .finally(() => this.actionFlights.delete(flightKey));
+ flight = this.trackAction(
+ this.deps
+ .executeAction({
+ sessionId,
+ ghostId: request.ghostId,
+ action,
+ ...(responseTarget ? { responseTarget } : {}),
+ })
+ .finally(() => this.actionFlights.delete(flightKey)),
+ );
this.actionFlights.set(flightKey, flight);
}
let result: GhostSetupActionResult;
@@ -433,12 +449,14 @@ export class GhostSetupCoordinator {
let result: GhostSetupActionResult;
try {
result = this.deps.executeInlineAction
- ? await this.deps.executeInlineAction({
- sessionId,
- ghostId: request.ghostId,
- action,
- value: submit.value,
- })
+ ? await this.trackAction(
+ this.deps.executeInlineAction({
+ sessionId,
+ ghostId: request.ghostId,
+ action,
+ value: submit.value,
+ }),
+ )
: {
ok: false,
errorCode: 'INLINE_UNAVAILABLE',
diff --git a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
index e73a423448..8b38014c3e 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts
@@ -237,6 +237,27 @@ export class GhostSetupInteractionBridge {
}
}
+ /** Account/data-owner boundary: cancel every actionable setup request before lease drain. */
+ cleanupAll(reason: 'session_closed' | 'session_aborted'): void {
+ for (const entry of Array.from(this.pending.values())) {
+ if (entry.completed) continue;
+ void Promise.resolve(
+ entry.onCommand({
+ kind: 'plugin_setup',
+ action: 'cancel',
+ expectedRevision: entry.snapshot.revision,
+ cleanupReason: reason,
+ }),
+ ).catch((error) => {
+ this.deps.logger?.warn('plugin setup account-boundary cleanup failed', {
+ requestId: entry.snapshot.requestId,
+ reason,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+ }
+
pendingSnapshots(sessionId?: string): Array<{
sessionId: string;
request: GhostSetupInteractionSnapshot;
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 40bc5d98ff..55b6a7cf56 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -39,7 +39,12 @@ import {
type ActiveAppSession,
} from '../appSessionState.js';
import { getLayoutStore } from '../layout/index.js';
-import { GhostManager, type InstallRejection, type UninstallRejection } from './GhostManager.js';
+import {
+ GhostManager,
+ type GhostExclusiveMutation,
+ type InstallRejection,
+ type UninstallRejection,
+} from './GhostManager.js';
import { exportGhostPackage } from './exportGhostPackage.js';
import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';
import { createOneShotTicketStore } from './oneShotTickets.js';
@@ -49,9 +54,11 @@ import {
listBuiltinSeedIds,
listEnterpriseSeedIds,
listRestorableBuiltinGhosts,
+ isTrustedBuiltinSeedSource,
provisionBuiltinGhosts,
readBuiltinTombstones,
recordBuiltinTombstone,
+ renameBuiltinTombstone,
type ProvisionIdentity,
} from './builtinGhostProvisioner.js';
import { getAccessToken, getAuthState, onAuthStateChange } from '../authManager.js';
@@ -87,13 +94,20 @@ import {
} from './ghostSetupStatus.js';
import { getGhostSetupChangeBus } from './ghostSetupChangeBus.js';
import { GhostSetupManifestTracker } from './ghostSetupManifestTracker.js';
-import type { GhostSetupActionResult } from './ghostSetupCoordinator.js';
-import type { GhostSetupInteractionResponseTarget } from './ghostSetupInteractionBridge.js';
+import {
+ getGhostSetupCoordinator,
+ type GhostSetupActionResult,
+} from './ghostSetupCoordinator.js';
+import {
+ getGhostSetupInteractionBridge,
+ type GhostSetupInteractionResponseTarget,
+} from './ghostSetupInteractionBridge.js';
import { executeGhostSetupInlineSubmission } from './ghostSetupInlineExecutor.js';
import { handleGhostSecretsRequest } from './runtime/ghostSecretsEndpoint.js';
import { handleGhostOauthRequest } from './runtime/ghostOauthEndpoint.js';
import { handleGhostConnectionsRequest } from './runtime/ghostConnectionsEndpoint.js';
import { GhostOauthAccountManager, type GhostOauthDecl } from './ghostOauthAccounts.js';
+import { cancelActiveGhostOauthFlow } from './ghostOauthFlow.js';
import { mapGhostOauthConnectError } from './ghostOauthSetupError.js';
import { reclaimLoopbackPort } from './portReclaim.js';
import { GhostConnectionManager } from './ghostConnections.js';
@@ -330,6 +344,15 @@ function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {
return ghostMutationCoordinator.acquire();
}
+/** MCP calls hold the same owner lease across setup, grant confirmation, and dispatch. */
+export function captureGhostMutationOwnerForMcp(): ActiveAppSession {
+ return captureGhostMutationOwner();
+}
+
+export function acquireGhostMutationLeaseForMcp(expectedOwner: ActiveAppSession): () => void {
+ return beginGhostMutation(expectedOwner);
+}
+
function isSameAppSession(a: ActiveAppSession, b: ActiveAppSession): boolean {
return a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;
}
@@ -537,7 +560,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
}
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) {
@@ -573,14 +596,23 @@ export function isGhostAvailableForActiveSession(id: string): boolean {
}
function availableGhosts(): InstalledGhost[] {
+ if (isAppSessionBoundaryPending()) return [];
return getGhostManager().list().filter((ghost) =>
isGhostAvailableForActiveSession(ghost.manifest.id),
);
}
function findAvailableGhost(id: string): InstalledGhost | null {
- if (!isGhostAvailableForActiveSession(id)) return null;
- return getGhostManager().list().find((ghost) => ghost.manifest.id === id) ?? null;
+ return availableGhosts().find((ghost) => ghost.manifest.id === id) ?? null;
+}
+
+/** Runtime-authorized lookup for integrations outside this module. */
+export function findAvailableGhostForAuthorization(id: string): InstalledGhost | null {
+ return findAvailableGhost(id);
+}
+
+export function listAvailableGhostsForAuthorization(): InstalledGhost[] {
+ return availableGhosts();
}
function requireGhostAvailableForActiveSession(id: string): void {
@@ -595,9 +627,26 @@ export function suspendCindyAccountGhosts(): void {
for (const id of CINDY_ACCOUNT_GHOST_IDS) runtimeSingleton.stop(id);
}
+/**
+ * Cancel owner-bound calls before waiting for their mutation leases.
+ *
+ * The lease itself stays held until each call unwinds, so attachment grants,
+ * setup writes, and post-dispatch cleanup cannot cross into the next owner.
+ */
+export async function interruptGhostCallsForAccountBoundary(): Promise<void> {
+ cancelActiveGhostOauthFlow();
+ getGhostSetupInteractionBridge()?.cleanupAll('session_aborted');
+ getGhostGrantConfirmBridge()?.cleanupAll('session_aborted');
+ getGhostConfirmDialogBridge()?.cancelAll();
+ runtimeSingleton?.destroyAll();
+ resetNodeRuntimeBrokerForAccountBoundary();
+ await getGhostSetupCoordinator()?.waitForActionsIdle();
+}
+
/** Stop every sandbox before changing the active data owner. */
export function suspendAllGhosts(): void {
runtimeSingleton?.destroyAll();
+ resetNodeRuntimeBrokerForAccountBoundary();
brainRootCache = null;
}
let ipcRegistered = false;
@@ -632,6 +681,20 @@ function builtinSeedRootDirs(): string[] {
return [path.join(base, 'official'), path.join(base, 'xd')];
}
+function isTrustedBundledSource(id: string, sourceDir: string): boolean {
+ return isTrustedBuiltinSeedSource(builtinSeedRootDirs(), id, sourceDir);
+}
+
+function hasDisabledMarker(dir: string): boolean {
+ try {
+ fs.lstatSync(path.join(dir, '.disabled'));
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
+ return true;
+ }
+}
+
/** 当前登录身份 → 播种受众判定的输入(登出 = null)。 */
function currentProvisionIdentity(): ProvisionIdentity | null {
const state = getAuthState();
@@ -779,8 +842,8 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {
error: err instanceof Error ? err.message : String(err),
});
}
- await manager.runExclusiveMutation(() =>
- reconcileBuiltinGhostsLocked(reason, manager),
+ await manager.runExclusiveMutation((mutation) =>
+ reconcileBuiltinGhostsLocked(reason, manager, mutation),
);
} finally {
releaseMutation();
@@ -790,6 +853,7 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {
async function reconcileBuiltinGhostsLocked(
reason: string,
manager: GhostManager,
+ mutation: GhostExclusiveMutation,
): Promise<void> {
// 改名前置:用户自主状态(墓碑=卸载过 / .disabled=停用)随改名带到新 id,
// 不能让"明确卸载/停用过"的用户在升级后被以新 id 重新装上并点亮(播种器
@@ -798,15 +862,12 @@ async function reconcileBuiltinGhostsLocked(
// 本处反复重新盖墓)。停用态:抓在播种前(孤儿回收会删旧目录),装上后补。
const renameDisabledCarry = new Map<string, boolean>();
for (const [fromId, toId] of RENAMED_BUILTIN_GHOSTS) {
- const tombstones = readBuiltinTombstones(brainRootDir());
- if (tombstones.includes(fromId)) {
- if (!tombstones.includes(toId)) recordBuiltinTombstone(brainRootDir(), toId, log);
- clearBuiltinTombstone(brainRootDir(), fromId, log);
+ if (renameBuiltinTombstone(brainRootDir(), fromId, toId, log)) {
log.info('builtin ghost tombstone carried over rename', { fromId, toId });
}
renameDisabledCarry.set(
toId,
- fs.existsSync(path.join(brainRootDir(), fromId, '.disabled')),
+ hasDisabledMarker(path.join(brainRootDir(), fromId)),
);
}
// "播种进行中"胶囊提示:只在真的动手(装/覆盖/回收)时亮起,no-op 对账
@@ -824,8 +885,29 @@ async function reconcileBuiltinGhostsLocked(
getGhostNodeRuntimeBroker().stop(id);
getGhostAgentSlot().clearGhost(id);
getGhostErrandSlot().clearGhost(id);
- await manager.removeInstallApproval(id);
+ // 内置回收也必须走 Host 的 uninstall journal;只撤 receipt 再由
+ // provisioner 直接 rm 会在 receipt 删除失败+崩溃时留下孤立批准。
+ const removal = await mutation.uninstall(id, {
+ notify: false,
+ // Audience/orphan reconciliation is Host lifecycle cleanup, not a
+ // durable user choice to keep this builtin uninstalled.
+ recordBuiltinTombstone: false,
+ });
+ if ('rejection' in removal) {
+ throw new Error(`builtin ghost uninstall failed: ${removal.rejection.reason}`);
+ }
},
+ beforeReplace: async (id) => {
+ // Revoke the old receipt before swapping mutable installed bytes. If a
+ // crash occurs during provisioning, the new bytes cannot run under the
+ // previous approval; the next reconcile mints a receipt from the
+ // immutable seed after the swap is complete.
+ if (!(await mutation.removeInstallApproval(id))) {
+ throw new Error(`builtin ghost approval revoke failed: ${id}`);
+ }
+ },
+ publishSeed: (id, seedDir, options) =>
+ mutation.publishTrustedBundledSeed(id, seedDir, options),
onApplyStart: () => {
tipShown = true;
broadcastGhostProvisioning(true);
@@ -858,7 +940,7 @@ async function reconcileBuiltinGhostsLocked(
for (const manifest of outcome.installed) {
if (!renameDisabledCarry.get(manifest.id)) continue;
try {
- fs.writeFileSync(path.join(brainRootDir(), manifest.id, '.disabled'), '');
+ mutation.writeDisabledMarker(manifest.id);
log.info('builtin ghost disabled state carried over rename', { id: manifest.id });
} catch (err) {
log.warn('builtin ghost disabled carry failed', {
@@ -871,12 +953,13 @@ async function reconcileBuiltinGhostsLocked(
for (const manifest of outcome.approved) {
try {
approvalChanged =
- (await manager.approveTrustedBundledInstall(
+ (await mutation.approveTrustedBundledInstall(
manifest,
// `.disabled` 镜像的读数只作停用方向的输入:receipt 已钉停用时,镜像被
// 外部移除不会把插件翻回启用(合并规则见 approveTrustedBundledInstall
// 头注释;重新启用只有用户显式 setEnabled 一条路)。
- !fs.existsSync(path.join(brainRootDir(), manifest.id, '.disabled')),
+ !hasDisabledMarker(path.join(brainRootDir(), manifest.id)),
+ { sourceDir: outcome.approvedSourceDirs[manifest.id] },
)) || approvalChanged;
// 本会话内被撤销熄灯的常驻实例,批准补回即恢复点火(隔离态下批准必然重写,
// approvalChanged 已为 true,不会被下面的 no-op 早退拦住)。
@@ -893,7 +976,7 @@ async function reconcileBuiltinGhostsLocked(
// 隔离。所以这里不需要、也不应该再自己判断撤销成不成功:那正是上一版在
// cleanup 失败时留下 fail-open 的地方。随包插件下一轮启动对账会重新补批准,
// 自愈,不需要用户介入。
- await manager.removeInstallApproval(manifest.id);
+ await mutation.removeInstallApproval(manifest.id);
// 撤销只让后续的 Host 能力调用与技能落链失效,不会自己结束已经跑起来的沙箱
// 进程 —— 登录触发对账时插件可能正在运行。与 beforeRemove 同款四连熄灯
// (含 errand slot:漏掉它会让节流状态与在途任务记录留到同会话的自愈之后,
@@ -961,12 +1044,16 @@ export function getGhostManager(): GhostManager {
managerSingleton = new GhostManager({
getRootDir: brainRootDir,
getStateDir: () => ownerScopedUserDataPath('ghost-install-state'),
+ getOwnerContextKey: activeOwnerScopeKey,
onChanged: broadcastGhostsChanged,
getLocale: getResolvedMainLocale,
trustRegistry: loadGhostTrustRegistry(),
// 随包批准入口的 builtin-only 边界:id 必须对应一颗随包种子。该入口不经用户
// 确认就铸出批准,不能只靠"唯一调用者是随包对账"这条纪律。
isTrustedBundledId: (id) => listBuiltinSeedIds(builtinSeedRootDirs()).includes(id),
+ isTrustedBundledSource,
+ recordBuiltinTombstone: (id) => recordBuiltinTombstone(brainRootDir(), id, log),
+ clearBuiltinTombstone: (id) => clearBuiltinTombstone(brainRootDir(), id, log),
log,
});
getGhostSetupManifestTracker().seed(managerSingleton.list());
@@ -1071,7 +1158,7 @@ let agentSlotSingleton: GhostAgentSlot | null = null;
export function getGhostAgentSlot(): GhostAgentSlot {
if (!agentSlotSingleton) {
agentSlotSingleton = new GhostAgentSlot({
- getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,
+ getGhost: findAvailableGhost,
log,
});
}
@@ -1089,7 +1176,7 @@ let errandSlotSingleton: GhostErrandSlot | null = null;
export function getGhostErrandSlot(): GhostErrandSlot {
if (!errandSlotSingleton) {
errandSlotSingleton = new GhostErrandSlot({
- getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,
+ getGhost: findAvailableGhost,
// wait 模式的署名单在途期间替管子那头的 tool-call 续命(同 cindy 槽契约)。
holdPipeCall: (ghostId, callId, budgetMs) =>
getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),
@@ -1107,16 +1194,29 @@ export function setGhostErrandRunner(runner: GhostErrandRunner | null): void {
/** 插件展示名(errand 会话默认标题等宿主侧使用;未装返回 null)。 */
export function getInstalledGhostName(id: string): string | null {
- return getGhostManager().list().find((g) => g.manifest.id === id)?.manifest.name ?? null;
+ return findAvailableGhost(id)?.manifest.name ?? null;
}
let nodeRuntimeBrokerSingleton: GhostNodeRuntimeBroker | null = null;
+/**
+ * `GhostNodeRuntimeBroker.destroyAll()` is a terminal host-exit operation. An
+ * account boundary still needs the old broker terminally stopped so delayed
+ * retries cannot cross owners, but the singleton slot must then be cleared so
+ * the next owner gets a fresh, startable broker.
+ */
+function resetNodeRuntimeBrokerForAccountBoundary(): void {
+ const broker = nodeRuntimeBrokerSingleton;
+ if (!broker) return;
+ broker.destroyAll();
+ if (nodeRuntimeBrokerSingleton === broker) nodeRuntimeBrokerSingleton = null;
+}
+
/** 随包 Node 工作进程单例:每个活跃插件一个进程,main.js 经主机中继调用。 */
export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
if (!nodeRuntimeBrokerSingleton) {
nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({
- getGhost: (id) => getGhostManager().list().find((g) => g.manifest.id === id) ?? null,
+ getGhost: findAvailableGhost,
readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),
sendToGhost: (ghostId, payload) => {
sendToGhostLogic(ghostId, payload);
@@ -2915,8 +3015,9 @@ export async function installAndDock(
: {}),
});
if ('rejection' in result) throwInstallError(result.rejection);
- // 用户手动重装同 id 的内置意识 = 重新跟随包内版本(清墓碑,播种恢复对账)。
- clearBuiltinTombstone(brainRootDir(), result.ghost.manifest.id, log);
+ // Builtin tombstone clearing is part of GhostManager's durable install
+ // journal. A transient state write failure keeps the marker for startup
+ // recovery without turning an already committed install into a false error.
// 声明了面板的意识装入后立即停进布局树(树上已有 = 重装,原位复活不动树)。
// 顺序刻意:manager.install 内已广播 ghosts:changed(renderer 先注册面板),
// 这里再 setLayout 触发 layout:changed(pane 出现时面板组件必然已就位,规则 7)。
@@ -3135,9 +3236,6 @@ export async function uninstallGhostAndCleanup(
error: err instanceof Error ? err.message : String(err),
});
}
- if (listBuiltinSeedIds(builtinSeedRootDirs()).includes(id)) {
- recordBuiltinTombstone(brainRootDir(), id, log);
- }
let recentIds: string[] | null = null;
try {
recentIds = forgetGhostRecentUsage(id);
@@ -4208,8 +4306,9 @@ export function registerGhostIpc(): void {
owner: ActiveAppSession;
id: string;
manifestSha256: string;
+ approvalProjectionSha256: string;
}>({ ttlMs: 10 * 60 * 1000, maxEntries: 64 });
- ipcMain.handle('ghosts:reapprove-inspect', (event, id: unknown) => {
+ ipcMain.handle('ghosts:reapprove-inspect', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
if (typeof id !== 'string' || id.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');
@@ -4218,14 +4317,22 @@ export function registerGhostIpc(): void {
rejectReservedGhostId(id);
// owner 在读事实**之前**捕获(边界期直接抛):票据钉的是"这份事实属于哪个 owner"。
const owner = captureGhostMutationOwner();
- const result = manager.inspectInstalledReapproval(id);
+ const result = await manager.inspectInstalledReapproval(id);
if ('rejection' in result) throwInstallError(result.rejection);
const inspectTicket = reapproveTickets.issue({
owner,
id,
manifestSha256: result.manifestSha256,
+ approvalProjectionSha256: result.approvalProjectionSha256,
});
- return { ...result, inspectTicket };
+ return {
+ manifest: result.manifest,
+ trust: result.trust,
+ manifestSha256: result.manifestSha256,
+ approvalProjectionSha256: result.approvalProjectionSha256,
+ previouslyEnabled: result.previouslyEnabled,
+ inspectTicket,
+ };
});
// 第三条恢复路径第二步:用户点过确认卡后开 receipt。expectedManifestSha256 绑定
@@ -4244,6 +4351,7 @@ export function registerGhostIpc(): void {
| {
enable?: unknown;
expectedManifestSha256?: unknown;
+ expectedApprovalProjectionSha256?: unknown;
expectedInstalledApproval?: unknown;
inspectTicket?: unknown;
}
@@ -4257,6 +4365,15 @@ export function registerGhostIpc(): void {
) {
throwIpcError('INVALID_PARAMS', 'expectedManifestSha256 must come from ghosts:reapprove-inspect');
}
+ if (
+ typeof options.expectedApprovalProjectionSha256 !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(options.expectedApprovalProjectionSha256)
+ ) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'expectedApprovalProjectionSha256 must come from ghosts:reapprove-inspect',
+ );
+ }
if (!isGhostInstallApprovalToken(options.expectedInstalledApproval)) {
throwIpcError('INVALID_PARAMS', 'expectedInstalledApproval must come from ghosts:list');
}
@@ -4268,7 +4385,8 @@ export function registerGhostIpc(): void {
if (
!ticket ||
ticket.id !== id ||
- ticket.manifestSha256 !== options.expectedManifestSha256
+ ticket.manifestSha256 !== options.expectedManifestSha256 ||
+ ticket.approvalProjectionSha256 !== options.expectedApprovalProjectionSha256
) {
throwIpcError('PRECONDITION_FAILED', '确认卡已过期或与检查时不一致,请重新打开确认');
}
@@ -4278,9 +4396,10 @@ export function registerGhostIpc(): void {
let result: Awaited<ReturnType<typeof manager.reapproveInstalled>>;
try {
result = await manager.reapproveInstalled(id, {
- enable: options.enable,
- expectedManifestSha256: options.expectedManifestSha256,
- expectedInstalledApproval: options.expectedInstalledApproval,
+ enable: options.enable,
+ expectedManifestSha256: options.expectedManifestSha256,
+ expectedApprovalProjectionSha256: options.expectedApprovalProjectionSha256,
+ expectedInstalledApproval: options.expectedInstalledApproval,
});
} finally {
releaseMutation();
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index 8f8ddc6a4c..932caaf0d6 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -59,6 +59,11 @@ const sessionSnapshotMock = vi.fn(async () => ({
}));
vi.mock('../../cindy-brain/index.js', () => ({
getGhostManager: () => ({ list: listMock }),
+ listAvailableGhostsForAuthorization: () => listMock(),
+ findAvailableGhostForAuthorization: (id: string) =>
+ listMock().find((ghost: any) => ghost.manifest?.id === id) ?? null,
+ captureGhostMutationOwnerForMcp: () => ({ mode: 'local', dataOwnerId: 'test', generation: 0 }),
+ acquireGhostMutationLeaseForMcp: () => () => {},
getGhostPipeDispatcher: () => ({ callGhostTool: dispatchMock }),
getGhostCardService: () => ({ registerCall: () => {}, finalizeCall: () => null }),
getGhostSetupAssessment: setupAssessmentMock,
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 173ca1706b..beb2ce87f8 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -57,6 +57,10 @@ import {
getGhostManager,
getGhostPipeDispatcher,
getGhostSetupAssessment,
+ acquireGhostMutationLeaseForMcp,
+ captureGhostMutationOwnerForMcp,
+ findAvailableGhostForAuthorization,
+ listAvailableGhostsForAuthorization,
isGhostAvailableForActiveSession,
} from '../cindy-brain/index.js';
import { getGhostSetupCoordinator } from '../cindy-brain/ghostSetupCoordinator.js';
@@ -148,9 +152,7 @@ async function buildGhostSessionContext(
/** 意识显示名(确认卡标题用;查不到回落 id)。 */
function ghostDisplayName(ghostId: string): string {
- const g = getGhostManager()
- .list()
- .find((x) => x.manifest.id === ghostId);
+ const g = findAvailableGhostForAuthorization(ghostId);
return g?.manifest.name ?? ghostId;
}
@@ -534,8 +536,7 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
// 描述花名册全量,运行期 ghost_list / ghost_call 仍按真实 workdir 拦)。
getRosterItems() {
const workdir = resolveSessionContext()?.workingDir ?? null;
- return getGhostManager()
- .list()
+ return listAvailableGhostsForAuthorization()
.filter(
(g) =>
g.enabled &&
@@ -558,8 +559,7 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
// 现查同样按会话 workdir 滤掉目录级禁用的意识(ALS 恢复的真实语境
// 优先)——模型主动 ghost_list 也看不到被禁用的条目,清单层面干净。
const workdir = resolveSessionContext()?.workingDir ?? null;
- return getGhostManager()
- .list()
+ return listAvailableGhostsForAuthorization()
.filter(
(g) =>
g.enabled &&
@@ -605,363 +605,467 @@ export function getCindyGhostsMcpDeps(sessionCtx?: LiziMcpSessionContext): Cindy
grantOnly,
setupPlan,
}) {
- // Check the account/session capability before granting attachments or
- // directory tickets. A stale roster from a cloud session must not let a
- // local session create durable grants or wake an account-managed Ghost.
- if (!isGhostAvailableForActiveSession(ghostId)) {
- return {
- ok: false,
- errorCode: 'GHOST_NOT_FOUND',
- // 这条 message 是 model-visible 的 tool result,会被模型读到并可能回显进对话,
- // 所以按用户可见口径写「未登录」而不是已废弃的「本地模式」(见
- // i18n/glossary.json 的 not-signed-in 条目)。句尾的「本地可用方式」保留:
- // 那个「本地」描述的是能力落在本机,不是账号状态名。
- message: '该插件需要 Cindy 账号,未登录状态不可用;不要重试,改用本地可用方式。',
- };
- }
- // 用户图片过户:attachments 里的地址逐张落媒体总仓 + 记
- // ghost-grant 引用(显式引渡 = 授权,按张、永久),指纹注入
- // args.attachments 交给意识。任何一张失败整批拒(ATTACHMENT_INVALID),
- // 不做半成品授权。全链路见 grantAttachmentUrls。
- let mergedArgs = args;
- const sessionContext = resolveSessionContext();
- const sessionIdForConfirm = sessionContext?.sessionId ?? null;
- const sessionWorkdir = sessionContext?.workingDir ?? null;
- // 目录级禁用兜底(防御线):花名册/ghost_list 已过滤,正常路径走不到
- // 这里——只有"会话开着时中途被禁"(快照已含自述)或模型凭上文记忆
- // 硬调才会命中。message 是可直达模型的人话:停手改道,不要自纠重试。
- if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return {
- ok: false,
- errorCode: 'GHOST_DISABLED_IN_WORKDIR',
- message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
- };
- }
- // Runtime setup gate: resolve the target before creating any durable
- // attachment grant, directory ticket, sandbox, card call, or dispatch.
- const target = getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId);
- if (!target) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: '目标插件不存在或已卸载' };
- }
- if (!target.enabled) {
- return {
- ok: false,
- errorCode: 'GHOST_ASLEEP',
- message: '目标插件未启用,可提示用户到主界面侧边栏「插件」中启用',
- };
- }
- // grant_only never dispatches and intentionally ignores its tool field.
- if (
- !grantOnly &&
- !(target.manifest.tools ?? []).some((candidate) => candidate.name === tool)
- ) {
- return {
- ok: false,
- errorCode: 'TOOL_NOT_FOUND',
- message: toolNotFoundMessage(ghostId, tool, target.manifest.tools),
- };
- }
- if (grantOnly && (!attachments || attachments.length === 0)) {
- return {
- ok: false,
- errorCode: 'ATTACHMENT_INVALID',
- message: 'grant_only 调用必须携带 attachments(要预授权的文件地址列表)',
- };
- }
- const setupCoordinator = getGhostSetupCoordinator();
- if (!setupCoordinator) {
- return {
- ok: false,
- errorCode: 'INTERNAL',
- message: '插件设置通道尚未就绪,本次调用未执行。',
- };
- }
- const setup = await setupCoordinator.ensureReady({
- sessionId: ghostSetupInteractionSessionId(sessionContext),
- ghostId,
- ...(!grantOnly ? { tool } : {}),
- workingDir: sessionWorkdir,
- ...(setupPlan ? { plan: setupPlan } : {}),
- });
- if (!setup.ok) return setup;
-
- // OAuth/settings may take minutes. Re-resolve mutable target facts after
- // the waiter completes and before beginning the existing side effects.
- const refreshed = getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId);
- if (!refreshed || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
- }
- if (!refreshed.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
- }
- if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return {
- ok: false,
- errorCode: 'GHOST_DISABLED_IN_WORKDIR',
- message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
- };
- }
- if (
- !grantOnly &&
- !(refreshed.manifest.tools ?? []).some((candidate) => candidate.name === tool)
- ) {
- return { ok: false, errorCode: 'TOOL_NOT_FOUND', message: toolNotFoundMessage(ghostId, tool, refreshed.manifest.tools) };
- }
- let finalAssessment;
+ let releaseMutation: (() => void) | undefined;
try {
- finalAssessment = getGhostSetupAssessment(ghostId);
+ const owner = captureGhostMutationOwnerForMcp();
+ releaseMutation = acquireGhostMutationLeaseForMcp(owner);
} catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
- }
- if (finalAssessment.state !== 'ready') {
return {
ok: false,
- errorCode: 'SETUP_REQUIRED',
- message: t('newChat.pluginSetup.setupChangedDuringResume'),
- setup: finalAssessment,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: '账号切换中,插件调用已取消;请稍后重试。',
};
}
- // 批量预授权(grant_only):只过户不派发。它与普通调用共用上面的
- // Host-authoritative setup gate,确保任何授权副作用之前插件已经 ready。
- if (grantOnly) {
- // Full pre-grant gate: confirm target, workdir, and setup readiness
- // BEFORE grantAttachmentUrls creates durable ledger entries.
- const grantTarget = getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId);
- if (!grantTarget || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
- }
- if (!grantTarget.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
+ try {
+ // Check the account/session capability before granting attachments or
+ // directory tickets. A stale roster from a cloud session must not let a
+ // local session create durable grants or wake an account-managed Ghost.
+ if (!isGhostAvailableForActiveSession(ghostId)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ // 这条 message 是 model-visible 的 tool result,会被模型读到并可能回显进对话,
+ // 所以按用户可见口径写「未登录」而不是已废弃的「本地模式」(见
+ // i18n/glossary.json 的 not-signed-in 条目)。句尾的「本地可用方式」保留:
+ // 那个「本地」描述的是能力落在本机,不是账号状态名。
+ message: '该插件需要 Cindy 账号,未登录状态不可用;不要重试,改用本地可用方式。',
+ };
}
+ // 用户图片过户:attachments 里的地址逐张落媒体总仓 + 记
+ // ghost-grant 引用(显式引渡 = 授权,按张、永久),指纹注入
+ // args.attachments 交给意识。任何一张失败整批拒(ATTACHMENT_INVALID),
+ // 不做半成品授权。全链路见 grantAttachmentUrls。
+ let mergedArgs = args;
+ const sessionContext = resolveSessionContext();
+ const sessionIdForConfirm = sessionContext?.sessionId ?? null;
+ const sessionWorkdir = sessionContext?.workingDir ?? null;
+ // 目录级禁用兜底(防御线):花名册/ghost_list 已过滤,正常路径走不到
+ // 这里——只有"会话开着时中途被禁"(快照已含自述)或模型凭上文记忆
+ // 硬调才会命中。message 是可直达模型的人话:停手改道,不要自纠重试。
if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR', message: t('newChat.pluginSetup.targetDisabledInWorkdir') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
}
- try {
- const grantOnlyAssessment = getGhostSetupAssessment(ghostId);
- if (grantOnlyAssessment.state !== 'ready') {
- return { ok: false, errorCode: 'SETUP_REQUIRED', message: t('newChat.pluginSetup.setupIncomplete'), setup: grantOnlyAssessment };
- }
- } catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ // Runtime setup gate: resolve the target before creating any durable
+ // attachment grant, directory ticket, sandbox, card call, or dispatch.
+ const target = findAvailableGhostForAuthorization(ghostId);
+ if (!target) {
+ return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: '目标插件不存在或已卸载' };
}
- const grant = await grantAttachmentUrls({
+ if (!target.enabled) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: '目标插件未启用,可提示用户到主界面侧边栏「插件」中启用',
+ };
+ }
+ // grant_only never dispatches and intentionally ignores its tool field.
+ if (
+ !grantOnly &&
+ !(target.manifest.tools ?? []).some((candidate) => candidate.name === tool)
+ ) {
+ return {
+ ok: false,
+ errorCode: 'TOOL_NOT_FOUND',
+ message: toolNotFoundMessage(ghostId, tool, target.manifest.tools),
+ };
+ }
+ if (grantOnly && (!attachments || attachments.length === 0)) {
+ return {
+ ok: false,
+ errorCode: 'ATTACHMENT_INVALID',
+ message: 'grant_only 调用必须携带 attachments(要预授权的文件地址列表)',
+ };
+ }
+ const setupCoordinator = getGhostSetupCoordinator();
+ if (!setupCoordinator) {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: '插件设置通道尚未就绪,本次调用未执行。',
+ };
+ }
+ const setup = await setupCoordinator.ensureReady({
+ sessionId: ghostSetupInteractionSessionId(sessionContext),
ghostId,
- urls: attachments!,
- workdirAbs: sessionWorkdir,
- sessionId: sessionIdForConfirm,
- maxCount: MAX_GRANT_ONLY_ATTACHMENTS,
+ ...(!grantOnly ? { tool } : {}),
+ workingDir: sessionWorkdir,
+ ...(setupPlan ? { plan: setupPlan } : {}),
});
- if (!grant.ok) {
- return { ok: false, errorCode: 'ATTACHMENT_INVALID', message: grant.message };
- }
- // Post-grant revalidation: the grant process includes an async user
- // confirmation step; re-check everything before returning success.
- const postGrant = getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId);
- if (!postGrant || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
+ if (!setup.ok) return setup;
+
+ // OAuth/settings may take minutes. Re-resolve mutable target facts after
+ // the waiter completes and before beginning the existing side effects.
+ const refreshed = findAvailableGhostForAuthorization(ghostId);
+ if (!refreshed || !isGhostAvailableForActiveSession(ghostId)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
}
- if (!postGrant.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
+ if (!refreshed.enabled) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
}
if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR', message: t('newChat.pluginSetup.targetDisabledInWorkdir') };
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
}
+ if (
+ !grantOnly &&
+ !(refreshed.manifest.tools ?? []).some((candidate) => candidate.name === tool)
+ ) {
+ return {
+ ok: false,
+ errorCode: 'TOOL_NOT_FOUND',
+ message: toolNotFoundMessage(ghostId, tool, refreshed.manifest.tools),
+ };
+ }
+ let finalAssessment;
try {
- const postGrantAssessment = getGhostSetupAssessment(ghostId);
- if (postGrantAssessment.state !== 'ready') {
- return { ok: false, errorCode: 'SETUP_REQUIRED', message: t('newChat.pluginSetup.setupChangedDuringResume'), setup: postGrantAssessment };
- }
+ finalAssessment = getGhostSetupAssessment(ghostId);
} catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
}
- log.info('ghost grant-only: batch pre-granted', { ghostId, count: grant.hashes.length });
- return {
- ok: true,
- result: {
+ if (finalAssessment.state !== 'ready') {
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupChangedDuringResume'),
+ setup: finalAssessment,
+ };
+ }
+ // 批量预授权(grant_only):只过户不派发。它与普通调用共用上面的
+ // Host-authoritative setup gate,确保任何授权副作用之前插件已经 ready。
+ if (grantOnly) {
+ // Full pre-grant gate: confirm target, workdir, and setup readiness
+ // BEFORE grantAttachmentUrls creates durable ledger entries.
+ const grantTarget = findAvailableGhostForAuthorization(ghostId);
+ if (!grantTarget || !isGhostAvailableForActiveSession(ghostId)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
+ }
+ if (!grantTarget.enabled) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
+ }
+ if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
+ }
+ try {
+ const grantOnlyAssessment = getGhostSetupAssessment(ghostId);
+ if (grantOnlyAssessment.state !== 'ready') {
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupIncomplete'),
+ setup: grantOnlyAssessment,
+ };
+ }
+ } catch {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
+ }
+ const grant = await grantAttachmentUrls({
+ ghostId,
+ urls: attachments!,
+ workdirAbs: sessionWorkdir,
+ sessionId: sessionIdForConfirm,
+ maxCount: MAX_GRANT_ONLY_ATTACHMENTS,
+ });
+ if (!grant.ok) {
+ return { ok: false, errorCode: 'ATTACHMENT_INVALID', message: grant.message };
+ }
+ // Post-grant revalidation: the grant process includes an async user
+ // confirmation step; re-check everything before returning success.
+ const postGrant = findAvailableGhostForAuthorization(ghostId);
+ if (!postGrant || !isGhostAvailableForActiveSession(ghostId)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
+ }
+ if (!postGrant.enabled) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
+ }
+ if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
+ }
+ try {
+ const postGrantAssessment = getGhostSetupAssessment(ghostId);
+ if (postGrantAssessment.state !== 'ready') {
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupChangedDuringResume'),
+ setup: postGrantAssessment,
+ };
+ }
+ } catch {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
+ }
+ log.info('ghost grant-only: batch pre-granted', { ghostId, count: grant.hashes.length });
+ return {
ok: true,
- granted_count: grant.hashes.length,
- attachments: grant.hashes,
- guidance:
- '整批文件已过户并获授权;继续逐次调用目标工具,引用原路径或这些指纹都不会再弹确认卡。不要向用户复述指纹列表。',
- },
- };
- }
- if (attachments && attachments.length > 0) {
- const grant = await grantAttachmentUrls({
- ghostId,
- urls: attachments,
- workdirAbs: sessionWorkdir,
- sessionId: sessionIdForConfirm,
- maxCount: MAX_GRANT_ATTACHMENTS,
- });
- if (!grant.ok) {
- return { ok: false, errorCode: 'ATTACHMENT_INVALID', message: grant.message };
+ result: {
+ ok: true,
+ granted_count: grant.hashes.length,
+ attachments: grant.hashes,
+ guidance:
+ '整批文件已过户并获授权;继续逐次调用目标工具,引用原路径或这些指纹都不会再弹确认卡。不要向用户复述指纹列表。',
+ },
+ };
}
- mergedArgs = { ...args, attachments: grant.hashes };
- }
- // 目录过户(xd-service 意识化二期):dir 收集文件发一次性票据,元数据
- // 注入 args.dir_deposit——意识拿到的只有票据与相对路径清单;上传时
- // networkSlot 凭票读盘代组 multipart。钳制两层策略:workdir 内直通,
- // workdir 外(含无 workdir 语境)经确认卡放行。
- if (dir !== undefined) {
- const dirConfirm = await confirmDepositOutsideWorkdir({
- ghostId,
- sessionId: sessionIdForConfirm,
- lane: 'dir',
- dirAbs: dir,
- workdirAbs: sessionWorkdir,
- });
- if (!dirConfirm.ok) {
- return { ok: false, errorCode: 'DIR_INVALID', message: dirConfirm.message };
+ if (attachments && attachments.length > 0) {
+ const grant = await grantAttachmentUrls({
+ ghostId,
+ urls: attachments,
+ workdirAbs: sessionWorkdir,
+ sessionId: sessionIdForConfirm,
+ maxCount: MAX_GRANT_ATTACHMENTS,
+ });
+ if (!grant.ok) {
+ return { ok: false, errorCode: 'ATTACHMENT_INVALID', message: grant.message };
+ }
+ mergedArgs = { ...args, attachments: grant.hashes };
}
- const deposited = getDirDepositVault().deposit({
- ghostId,
- dirAbs: dir,
- workdirAbs: sessionWorkdir,
- userGranted: dirConfirm.userGranted,
- });
- if (!deposited.ok) {
- return { ok: false, errorCode: 'DIR_INVALID', message: deposited.message };
+ // 目录过户(xd-service 意识化二期):dir 收集文件发一次性票据,元数据
+ // 注入 args.dir_deposit——意识拿到的只有票据与相对路径清单;上传时
+ // networkSlot 凭票读盘代组 multipart。钳制两层策略:workdir 内直通,
+ // workdir 外(含无 workdir 语境)经确认卡放行。
+ if (dir !== undefined) {
+ const dirConfirm = await confirmDepositOutsideWorkdir({
+ ghostId,
+ sessionId: sessionIdForConfirm,
+ lane: 'dir',
+ dirAbs: dir,
+ workdirAbs: sessionWorkdir,
+ });
+ if (!dirConfirm.ok) {
+ return { ok: false, errorCode: 'DIR_INVALID', message: dirConfirm.message };
+ }
+ const deposited = getDirDepositVault().deposit({
+ ghostId,
+ dirAbs: dir,
+ workdirAbs: sessionWorkdir,
+ userGranted: dirConfirm.userGranted,
+ });
+ if (!deposited.ok) {
+ return { ok: false, errorCode: 'DIR_INVALID', message: deposited.message };
+ }
+ mergedArgs = { ...mergedArgs, dir_deposit: deposited.receipt };
}
- mergedArgs = { ...mergedArgs, dir_deposit: deposited.receipt };
- }
- // 下行落盘过户(附件下载不降级):save_dir 发限时票据注入
- // args.save_deposit——意识 fetch as:'file' 报票据,主机把响应字节直接
- // 写进该目录,绝对路径与字节不进沙箱。钳制两层策略同 dir。
- if (saveDir !== undefined) {
- const saveConfirm = await confirmDepositOutsideWorkdir({
- ghostId,
- sessionId: sessionIdForConfirm,
- lane: 'save_dir',
- dirAbs: saveDir,
- workdirAbs: sessionWorkdir,
- });
- if (!saveConfirm.ok) {
- return { ok: false, errorCode: 'DIR_INVALID', message: saveConfirm.message };
+ // 下行落盘过户(附件下载不降级):save_dir 发限时票据注入
+ // args.save_deposit——意识 fetch as:'file' 报票据,主机把响应字节直接
+ // 写进该目录,绝对路径与字节不进沙箱。钳制两层策略同 dir。
+ if (saveDir !== undefined) {
+ const saveConfirm = await confirmDepositOutsideWorkdir({
+ ghostId,
+ sessionId: sessionIdForConfirm,
+ lane: 'save_dir',
+ dirAbs: saveDir,
+ workdirAbs: sessionWorkdir,
+ });
+ if (!saveConfirm.ok) {
+ return { ok: false, errorCode: 'DIR_INVALID', message: saveConfirm.message };
+ }
+ const saveDeposited = getSaveDepositVault().deposit({
+ ghostId,
+ dirAbs: saveDir,
+ workdirAbs: sessionWorkdir,
+ userGranted: saveConfirm.userGranted,
+ });
+ if (!saveDeposited.ok) {
+ return { ok: false, errorCode: 'DIR_INVALID', message: saveDeposited.message };
+ }
+ mergedArgs = { ...mergedArgs, save_deposit: saveDeposited.receipt };
}
- const saveDeposited = getSaveDepositVault().deposit({
- ghostId,
- dirAbs: saveDir,
- workdirAbs: sessionWorkdir,
- userGranted: saveConfirm.userGranted,
- });
- if (!saveDeposited.ok) {
- return { ok: false, errorCode: 'DIR_INVALID', message: saveDeposited.message };
+ // ── session-context 槽:注入宿主铸造的会话上下文(盖章工作单)────
+ // agent / 上游自报的同名字段一律剥除——这个字段的全部价值在于
+ // "主机铸造、不可伪造";未声明槽的插件连剥除后的空位都不给。
+ if ('session_context' in mergedArgs) {
+ const { session_context: _dropped, ...rest } = mergedArgs;
+ mergedArgs = rest;
}
- mergedArgs = { ...mergedArgs, save_deposit: saveDeposited.receipt };
- }
- // ── session-context 槽:注入宿主铸造的会话上下文(盖章工作单)────
- // agent / 上游自报的同名字段一律剥除——这个字段的全部价值在于
- // "主机铸造、不可伪造";未声明槽的插件连剥除后的空位都不给。
- if ('session_context' in mergedArgs) {
- const { session_context: _dropped, ...rest } = mergedArgs;
- mergedArgs = rest;
- }
- // Pre-dispatch revalidation: attachment grants and dir tickets may have
- // taken time; confirm the target is still available before committing the
- // callId and dispatching to the sandbox.
- const preDispatch = getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId);
- if (!preDispatch || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
- }
- if (!preDispatch.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
- }
- if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return {
- ok: false,
- errorCode: 'GHOST_DISABLED_IN_WORKDIR',
- message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
- };
- }
- if (!(preDispatch.manifest.tools ?? []).some((c) => c.name === tool)) {
- return { ok: false, errorCode: 'TOOL_NOT_FOUND', message: toolNotFoundMessage(ghostId, tool, preDispatch.manifest.tools) };
- }
- try {
- const preDispatchAssessment = getGhostSetupAssessment(ghostId);
- if (preDispatchAssessment.state !== 'ready') {
+ // Pre-dispatch revalidation: attachment grants and dir tickets may have
+ // taken time; confirm the target is still available before committing the
+ // callId and dispatching to the sandbox.
+ const preDispatch = findAvailableGhostForAuthorization(ghostId);
+ if (!preDispatch || !isGhostAvailableForActiveSession(ghostId)) {
return {
ok: false,
- errorCode: 'SETUP_REQUIRED',
- message: t('newChat.pluginSetup.setupChangedDuringResume'),
- setup: preDispatchAssessment,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
};
}
- } catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
- }
- // Session-context slot: use the revalidated manifest to decide injection.
- // Re-read manifest after the async buildGhostSessionContext to guard against
- // a same-ID plugin replacement removing the slot during the await.
- if (preDispatch.manifest.slots?.includes('session-context')) {
- const ctx = await buildGhostSessionContext(sessionIdForConfirm, sessionWorkdir);
- const postCtxManifest = getGhostManager()
- .list()
- .find((g) => g.manifest.id === ghostId)?.manifest;
- if (postCtxManifest?.slots?.includes('session-context')) {
- mergedArgs = { ...mergedArgs, session_context: ctx };
+ if (!preDispatch.enabled) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
}
- }
- // Full revalidation after session-context await (DB query may take time)
- const postCtx = getGhostManager().list().find((g) => g.manifest.id === ghostId);
- if (!postCtx || !isGhostAvailableForActiveSession(ghostId)) {
- return { ok: false, errorCode: 'GHOST_NOT_FOUND', message: t('newChat.pluginSetup.targetNotFound') };
- }
- if (!postCtx.enabled) {
- return { ok: false, errorCode: 'GHOST_ASLEEP', message: t('newChat.pluginSetup.targetDisabled') };
- }
- if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
- return { ok: false, errorCode: 'GHOST_DISABLED_IN_WORKDIR', message: t('newChat.pluginSetup.targetDisabledInWorkdir') };
- }
- if (!(postCtx.manifest.tools ?? []).some((c) => c.name === tool)) {
- return { ok: false, errorCode: 'TOOL_NOT_FOUND', message: toolNotFoundMessage(ghostId, tool, postCtx.manifest.tools) };
- }
- try {
- const postCtxAssessment = getGhostSetupAssessment(ghostId);
- if (postCtxAssessment.state !== 'ready') {
- return { ok: false, errorCode: 'SETUP_REQUIRED', message: t('newChat.pluginSetup.setupChangedDuringResume'), setup: postCtxAssessment };
+ if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
}
- } catch {
- return { ok: false, errorCode: 'INTERNAL', message: t('newChat.pluginSetup.assessmentReadFailed') };
+ if (!(preDispatch.manifest.tools ?? []).some((c) => c.name === tool)) {
+ return {
+ ok: false,
+ errorCode: 'TOOL_NOT_FOUND',
+ message: toolNotFoundMessage(ghostId, tool, preDispatch.manifest.tools),
+ };
+ }
+ try {
+ const preDispatchAssessment = getGhostSetupAssessment(ghostId);
+ if (preDispatchAssessment.state !== 'ready') {
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupChangedDuringResume'),
+ setup: preDispatchAssessment,
+ };
+ }
+ } catch {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
+ }
+ // Session-context slot: use the revalidated manifest to decide injection.
+ // Re-read manifest after the async buildGhostSessionContext to guard against
+ // a same-ID plugin replacement removing the slot during the await.
+ if (preDispatch.manifest.slots?.includes('session-context')) {
+ const ctx = await buildGhostSessionContext(sessionIdForConfirm, sessionWorkdir);
+ const postCtxManifest = findAvailableGhostForAuthorization(ghostId)?.manifest;
+ if (postCtxManifest?.slots?.includes('session-context')) {
+ mergedArgs = { ...mergedArgs, session_context: ctx };
+ }
+ }
+ // Full revalidation after session-context await (DB query may take time)
+ const postCtx = findAvailableGhostForAuthorization(ghostId);
+ if (!postCtx || !isGhostAvailableForActiveSession(ghostId)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_NOT_FOUND',
+ message: t('newChat.pluginSetup.targetNotFound'),
+ };
+ }
+ if (!postCtx.enabled) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_ASLEEP',
+ message: t('newChat.pluginSetup.targetDisabled'),
+ };
+ }
+ if (isGhostDisabledForWorkdir(ghostId, sessionWorkdir)) {
+ return {
+ ok: false,
+ errorCode: 'GHOST_DISABLED_IN_WORKDIR',
+ message: t('newChat.pluginSetup.targetDisabledInWorkdir'),
+ };
+ }
+ if (!(postCtx.manifest.tools ?? []).some((c) => c.name === tool)) {
+ return {
+ ok: false,
+ errorCode: 'TOOL_NOT_FOUND',
+ message: toolNotFoundMessage(ghostId, tool, postCtx.manifest.tools),
+ };
+ }
+ try {
+ const postCtxAssessment = getGhostSetupAssessment(ghostId);
+ if (postCtxAssessment.state !== 'ready') {
+ return {
+ ok: false,
+ errorCode: 'SETUP_REQUIRED',
+ message: t('newChat.pluginSetup.setupChangedDuringResume'),
+ setup: postCtxAssessment,
+ };
+ }
+ } catch {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: t('newChat.pluginSetup.assessmentReadFailed'),
+ };
+ }
+ // ── 卡槽③:callId 在这里预铸并登记给卡片服务 ────────────────────
+ // 时序契约:register(供片窗开)→ dispatch(意识拿到同一 callId,执行
+ // 中可 card-update)→ finalize(问"这单供过卡吗",开晚到宽限窗)→
+ // 真供过卡才把 xdt_card_id 注入 result(mcpServer 提升到顶层,renderer
+ // 据此配对取卡;没供过 = 结果零变化,模型永远看不到内部 UUID)。
+ const callId = randomUUID();
+ const cardService = getGhostCardService();
+ cardService.registerCall(callId, {
+ ghostId,
+ toolUseId: agentToolUseId ?? null,
+ // ALS 优先(codex 每单恢复)、闭包兜底(claude 建线期按 session 绑定)
+ // ——此前 claude 路径这里恒为 null,卡片只能靠 toolUseId 启发式锚定。
+ sessionId: resolveSessionContext()?.sessionId ?? null,
+ });
+ // GhostToolCallResult 与 CindyGhostCallResult 同构(错误码枚举一致),
+ // 原样透传;类型层若有漂移 tsc 会拦。
+ const result = await getGhostPipeDispatcher().callGhostTool({
+ ghostId,
+ tool,
+ args: mergedArgs,
+ callId,
+ });
+ // 收口取账(ghostMediaLedger):本次调用期间主机实际入库的媒体地址。
+ // 失败也 drain(清账防泄漏),但只在成功结果上附带——cindy-tools 层
+ // 在意识未声明媒体字段时以 xdt_media_produced 注入,兜底 IM/hook 送达。
+ const producedMedia = drainGhostCallMedia(ghostId, callId);
+ const finalized = withCardToken(result, cardService.finalizeCall(callId), callId);
+ return finalized.ok && producedMedia.length > 0
+ ? { ...finalized, producedMedia }
+ : finalized;
+ } finally {
+ releaseMutation?.();
}
- // ── 卡槽③:callId 在这里预铸并登记给卡片服务 ────────────────────
- // 时序契约:register(供片窗开)→ dispatch(意识拿到同一 callId,执行
- // 中可 card-update)→ finalize(问"这单供过卡吗",开晚到宽限窗)→
- // 真供过卡才把 xdt_card_id 注入 result(mcpServer 提升到顶层,renderer
- // 据此配对取卡;没供过 = 结果零变化,模型永远看不到内部 UUID)。
- const callId = randomUUID();
- const cardService = getGhostCardService();
- cardService.registerCall(callId, {
- ghostId,
- toolUseId: agentToolUseId ?? null,
- // ALS 优先(codex 每单恢复)、闭包兜底(claude 建线期按 session 绑定)
- // ——此前 claude 路径这里恒为 null,卡片只能靠 toolUseId 启发式锚定。
- sessionId: resolveSessionContext()?.sessionId ?? null,
- });
- // GhostToolCallResult 与 CindyGhostCallResult 同构(错误码枚举一致),
- // 原样透传;类型层若有漂移 tsc 会拦。
- const result = await getGhostPipeDispatcher().callGhostTool({
- ghostId,
- tool,
- args: mergedArgs,
- callId,
- });
- // 收口取账(ghostMediaLedger):本次调用期间主机实际入库的媒体地址。
- // 失败也 drain(清账防泄漏),但只在成功结果上附带——cindy-tools 层
- // 在意识未声明媒体字段时以 xdt_media_produced 注入,兜底 IM/hook 送达。
- const producedMedia = drainGhostCallMedia(ghostId, callId);
- const finalized = withCardToken(result, cardService.finalizeCall(callId), callId);
- return finalized.ok && producedMedia.length > 0 ? { ...finalized, producedMedia } : finalized;
},
async forgeGuide(): Promise<string> {
return FORGE_GUIDE;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 0a92a7bd37..7563674701 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -907,6 +907,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
manifest: unknown;
trust: unknown;
manifestSha256: string;
+ approvalProjectionSha256: string;
previouslyEnabled: boolean;
inspectTicket: string;
}> => ipcRenderer.invoke('ghosts:reapprove-inspect', id),
@@ -916,6 +917,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
opts: {
enable: boolean;
expectedManifestSha256: string;
+ expectedApprovalProjectionSha256: string;
expectedInstalledApproval: string;
inspectTicket: string;
},
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index a5c96ac047..494caa8245 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -247,6 +247,7 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
let manifest: GhostManifest;
let trust: GhostTrustInfo;
let manifestSha256: string;
+ let approvalProjectionSha256: string;
let previouslyEnabled: boolean;
let inspectTicket: string;
try {
@@ -254,6 +255,7 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
manifest = inspected.manifest;
trust = inspected.trust;
manifestSha256 = inspected.manifestSha256;
+ approvalProjectionSha256 = inspected.approvalProjectionSha256;
previouslyEnabled = inspected.previouslyEnabled;
inspectTicket = inspected.inspectTicket;
} catch (err) {
@@ -295,6 +297,7 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
const { ghost } = await window.electronAPI.ghosts.reapproveInstalled(ghostId, {
enable,
expectedManifestSha256: manifestSha256,
+ expectedApprovalProjectionSha256: approvalProjectionSha256,
expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
inspectTicket,
});
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 2271642867..7f036b5106 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1165,6 +1165,8 @@ interface ElectronAPI {
trust: import('../shared/ghost').GhostTrustInfo;
/** 确认卡展示时的清单字节指纹;确认时回传,防确认间隙清单被换。 */
manifestSha256: string;
+ /** 确认卡展示时的完整批准投影指纹;覆盖技能、locale、icon、trust。 */
+ approvalProjectionSha256: string;
/** 升级前的启停偏好(.disabled 镜像读数):确认卡勾选默认值。 */
previouslyEnabled: boolean;
/** 一次性票据(Host 进程内钉住 inspect 时点的 owner 与事实,confirm 原子消费)。 */
@@ -1176,6 +1178,7 @@ interface ElectronAPI {
opts: {
enable: boolean;
expectedManifestSha256: string;
+ expectedApprovalProjectionSha256: string;
expectedInstalledApproval: string;
inspectTicket: string;
},
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 5e5759d4b5..1eaa0095c0 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -283,7 +283,8 @@
改写成 `completed`;`completed`/存在但读不出 = 门关死,此后缺 receipt 一律 fail closed
——否则删 receipt 就能骗一次"从可变安装目录重建授权";`in-progress` = 上一轮中途崩溃,
续跑**只认清单内的 id**,迁移窗口期间新装再删 receipt 的 id 骗不到重铸;receipt 首写
- 自动补落的 completed 台账只在"完全没有台账"时动笔,不覆盖 in-progress。该门是充分
+ 在 receipt rename 生效**之前**先补落 completed 台账,且落账失败就拒绝本次批准;它只在
+ "完全没有台账"时动笔,不覆盖 in-progress。该门是充分
守卫,因为能删/改 ledger 的进程本就能直接写伪造 receipt,见下「批准状态根无写保护」)、**不扩权**(权限集原样取当前 `ghost.json`,等价于旧模型无条件
授权的那一组,此后任何 manifest/权限变化照旧走完整确认)、**只写状态根不动安装目录**
(三份旧文件原样保留,回滚到旧客户端时仍按安装目录判定,符合第 5 节兜底第 4 条)。核心
@@ -295,11 +296,14 @@
→ 确认卡全量权限清单 → `ghosts:reapprove-installed`,清单字节以 manifestSha256 绑定
确认间隙,trust 走与迁移同一个封顶读取器,装入侧的指令查重/tokenBroker/保留前缀
门禁照走)—— 不要求用户重新提供原始 `.cindy`,不存在不可恢复状态;随包插件不走人工
- 确认,由启动对账自动补(UI 提示「重启应用即恢复」)。一次性门的完整判据(三道,缺一
- 即漏):ledger 存在不迁;状态根有任何**有效** receipt 不迁并补写 ledger(损坏/旧
- schema 的 receipt 不算「活动过」——它们正是本条要治愈的对象,能改坏 receipt 的进程与
- §「状态根无写保护」登记的伪造者同类);**首次写任何 receipt 时自动落 ledger**(不落
- 的话,「新装 receipt 后、下一轮对账前」删 receipt 可骗一次按已扩权 manifest 的重铸)。
+ 确认,由启动对账自动补(UI 提示「重启应用即恢复」)。一次性门的完整判据:ledger
+ `completed`(或存在但读不出)永久关门;`in-progress` 只按动笔前钉死的 `pendingIds`
+ 续跑;无 ledger 时先扫描完整安装根,不能因某一个有效 receipt 提前关门——曾短暂合入
+ 后回滚的 #1080 可能留下「部分有效 receipt + 其余 legacy 安装 + 无 ledger」的历史 mixed
+ 状态,提前关门会让其余插件永久失效。新代码必须在**首次写任何 receipt 前**先原子落
+ completed ledger,落账失败则 receipt 不得生效(否则「新装 receipt 后、下一轮对账前」
+ 删 receipt 可骗一次按已扩权 manifest 的重铸);legacy migration/recovery 已先落
+ in-progress,因此首份 backfill receipt 不会覆盖迁移清单。
安装根为空/未诞生时**不落 ledger**——门要留给 owner 命名空间 legacy 恢复流程随后搬入
的旧目录;恢复流程对刚搬入的 id 走 `backfillRecoveredLegacyGhosts` 旁路(信任级与首轮
迁移等同,只作用于恢复流程自己搬动的 id)。安装根读失败(非 ENOENT)整轮放弃且不落