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。

fix(desktop): 修复第 7 轮 review——本地写路径 owner 租约、迁移崩溃安全状态机

Yuewei-LL194b80fc16d9
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 2798e2e8bb..4904e4bfea 100644
Binary files a/apps/desktop/src/main/cindy-brain/GhostManager.ts and b/apps/desktop/src/main/cindy-brain/GhostManager.ts differ
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 48ad96c941..323c8d52a9 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -368,6 +368,171 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
});
});
+describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命名空间', () => {
+ it('中途崩溃后按 pendingIds 续跑:已迁的跳过、剩余补迁、台账推进到 completed', async () => {
+ // 复现真实崩溃现场:首轮迁移在 aaa 写完 receipt(receipt 首写自动落账被
+ // in-progress 台账挡住)、bbb 还没动笔时进程死掉。
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await writeLegacyInstall('bbb', goodManifest('bbb'));
+ await manager.migrateLegacyApprovalsOnce();
+ // 手工把状态倒回"崩溃时刻":台账退回 in-progress、bbb 的 receipt 消失。
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['aaa', 'bbb'],
+ }),
+ );
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'bbb.json'));
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ // bbb 被续跑补迁;aaa 已有 receipt,计入 migrated(它就是迁移铸出的)。
+ expect(outcome.migrated).toEqual(['bbb']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId).toEqual({ aaa: 'approved', bbb: 'approved' });
+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ migratedIds: string[];
+ };
+ expect(ledger.state).toBe('completed');
+ expect(ledger.migratedIds).toEqual(['aaa', 'bbb']);
+ });
+
+ it('续跑只认动笔前钉死的清单:清单外的无 receipt 目录不被重铸', async () => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ // 迁移窗口期间新装再删 receipt 的插件(不在 pendingIds 里)骗不到续跑。
+ await writeLegacyInstall('ccc', goodManifest('ccc'));
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['aaa'],
+ }),
+ );
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['aaa']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId.aaa).toBe('approved');
+ expect(byId.ccc).toBe('legacy-unapproved');
+ expect(
+ (JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as { state?: string })
+ .state,
+ ).toBe('completed');
+ });
+
+ it('receipt 首写的自动落账不覆盖 in-progress 台账(崩溃门不被焊死)', async () => {
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(
+ migrationLedgerPath(),
+ JSON.stringify({
+ version: 1,
+ migratedAt: '2026-08-01T00:00:00.000Z',
+ migratedIds: [],
+ state: 'in-progress',
+ pendingIds: ['zzz'],
+ }),
+ );
+ // 迁移窗口内经正常装入流程写 receipt(内部有"缺台账即补写 completed"的守卫)。
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {
+ state?: string;
+ };
+ expect(ledger.state).toBe('in-progress');
+ });
+
+ it('台账存在但读不出:门保守关死,不迁也不重写', async () => {
+ await writeLegacyInstall('aaa', goodManifest('aaa'));
+ await fs.promises.mkdir(path.join(workDir, 'ghosts-install-state'), { recursive: true });
+ await fs.promises.writeFile(migrationLedgerPath(), '{ not valid json');
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [] });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{ not valid json');
+ });
+
+ it('启用失败的回滚按"镜像先前是否在盘上",不吞掉旧客户端的停用决定', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 旧客户端只写镜像:receipt.enabled=true + .disabled 在盘 → 读时合并 = 停用。
+ const marker = path.join(rootDir, 'hello', '.disabled');
+ await fs.promises.writeFile(marker, '');
+ expect(manager.list()[0].enabled).toBe(false);
+
+ // receipt 落盘的 rename 失败(状态根抖动):启用必须整体失败且镜像原样放回。
+ const realRename = fs.promises.rename;
+ const spy = vi
+ .spyOn(fs.promises, 'rename')
+ .mockImplementation(async (from, to) => {
+ if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');
+ return realRename(from, to);
+ });
+ try {
+ const result = await manager.setEnabled('hello', true);
+ expect('rejection' in result && result.rejection.code).toBe('io');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(fs.existsSync(marker)).toBe(true);
+ expect(manager.list()[0].enabled).toBe(false);
+ });
+
+ it('进程内隔离按状态根命名空间:A 账号的隔离不污染 B,切回 A 仍生效', async () => {
+ let stateDir = path.join(workDir, 'owner-a-state');
+ const owned = new GhostManager({
+ getRootDir: () => rootDir,
+ getStateDir: () => stateDir,
+ getLocale: () => hostLocale,
+ });
+ await owned.install(await makeCindy('a.cindy', goodManifest()));
+ // 撤销失败 → A 的进程内隔离。
+ const realRm = fs.promises.rm;
+ const spy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, opts) => {
+ if (String(target).endsWith('hello.json')) throw new Error('EACCES');
+ return realRm(target as never, opts as never);
+ });
+ try {
+ await owned.removeInstallApproval('hello');
+ } finally {
+ spy.mockRestore();
+ }
+ expect(owned.list()[0].approval.state).toBe('invalid');
+
+ // 切到 B 账号(状态根变了):同 id 不被 A 的隔离污染 —— B 没有 receipt,
+ // 如实是 legacy-unapproved 而不是 invalid。
+ stateDir = path.join(workDir, 'owner-b-state');
+ expect(owned.list()[0].approval.state).toBe('legacy-unapproved');
+
+ // 切回 A:隔离仍在(盘上那份陈旧 receipt 不得复活)。
+ stateDir = path.join(workDir, 'owner-a-state');
+ expect(owned.list()[0].approval.state).toBe('invalid');
+ });
+
+ it('安装根下的 junction 不算已装插件:迁移不迁它,list 不列它', async () => {
+ await writeLegacyInstall('real', goodManifest('real'));
+ const outside = path.join(workDir, 'outside-plugin');
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'ghost.json'), JSON.stringify(goodManifest('planted')));
+ try {
+ fs.symlinkSync(outside, path.join(rootDir, 'planted'), 'junction');
+ } catch {
+ return; // 环境建不了链接则跳过;判据逻辑平台无关。
+ }
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['real']);
+ expect(manager.list().map((g) => g.manifest.id)).toEqual(['real']);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'planted.json'))).toBe(false);
+ });
+});
+
describe('GhostManager · 从已装目录重新确认(本地包第三条恢复路径)', () => {
it('批准丢失后不用原始 .cindy:inspect 出全量清单,确认后开 receipt、恢复可用', async () => {
// 场景:迁移已跑过(ledger 在),之后 receipt 又被删 —— 一次性门不再迁移,
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
new file mode 100644
index 0000000000..07964c6de4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
@@ -0,0 +1,72 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+/**
+ * 源码契约测试:所有会改写插件世界(内容根/状态根/运行时)的 IPC 写路径,
+ * handler 体内必须持 GhostMutationCoordinator 租约。
+ *
+ * 背景:GhostManager 与 ReceiptStore 的根路径都是调用时现解析的
+ * (ownerScopedUserDataPath),账号切换边界只等待 coordinator
+ * (bootstrap-electron 的 waitForGhostMutations)。写路径不持租约,异步窗口
+ * (inspect/parse/hash)里切号落定,后半段写入就会漏进新 owner 的命名空间 ——
+ * A 发起的安装落进 B、A 的内容目录配上 B 的 receipt。第 7 轮 review 实锤了
+ * 本地 install/update/set-enabled 三条正是这么漏的(市场路径一直有租约)。
+ *
+ * index.ts 拉起整张 main 进程单例图,handler 无法脱离 electron 直测,所以用
+ * 源码扫描钉契约:每个列出的 handler 块里必须出现 beginGhostMutation(取租约)
+ * 与 captureGhostMutationOwner(入口同步捕获 owner,防"用切换后的 owner 取租约
+ * 照样通过"——租约要核对的是发起时刻的 owner)。新增写路径 handler 时把名字加进
+ * 清单;想移除租约必须先改掉 owner 动态解析这个前提。
+ */
+
+const MUTATING_GHOST_CHANNELS = [
+ 'ghosts:install',
+ 'ghosts:update',
+ 'ghosts:set-enabled',
+ 'ghosts:reapprove-installed',
+] as const;
+
+function handlerBlock(source: string, channel: string): string {
+ const start = source.indexOf(`ipcMain.handle('${channel}'`);
+ expect(start, `handler for ${channel} not found`).toBeGreaterThan(-1);
+ // handler 以两空格缩进的 `});` 收尾(仓库排版惯例);取到那里足够覆盖整个闭包。
+ const end = source.indexOf('\n });', start);
+ expect(end, `handler block for ${channel} has no terminator`).toBeGreaterThan(start);
+ return source.slice(start, end);
+}
+
+describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {
+ const source = fs.readFileSync(
+ path.join(__dirname, '..', 'index.ts'),
+ 'utf8',
+ );
+
+ for (const channel of MUTATING_GHOST_CHANNELS) {
+ it(`${channel} 持租约且入口同步捕获 owner`, () => {
+ const block = handlerBlock(source, channel);
+ expect(block, `${channel} 缺 beginGhostMutation`).toContain('beginGhostMutation(');
+ expect(block, `${channel} 缺 captureGhostMutationOwner`).toContain(
+ 'captureGhostMutationOwner()',
+ );
+ });
+ }
+
+ it('ghosts:uninstall 经 uninstallGhostAndCleanup 持租约(入口同步取,无异步窗口故无需 capture)', () => {
+ const block = handlerBlock(source, 'ghosts:uninstall');
+ expect(block).toContain('uninstallGhostAndCleanup(');
+ const start = source.indexOf('export async function uninstallGhostAndCleanup');
+ expect(start).toBeGreaterThan(-1);
+ const fn = source.slice(start, source.indexOf('\n}', start));
+ expect(fn).toContain('beginGhostMutation(');
+ });
+
+ it('市场装入/更新持租约(installOrUpdateMarketGhostPackage)', () => {
+ const start = source.indexOf('export async function installOrUpdateMarketGhostPackage');
+ expect(start).toBeGreaterThan(-1);
+ const block = source.slice(start, source.indexOf('\n}', start));
+ expect(block).toContain('captureGhostMutationOwner()');
+ expect(block).toContain('beginGhostMutation(');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 2f35877a4c..97fe4dc073 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -93,6 +93,19 @@ export interface GhostLegacyMigrationLedger {
* 记进台账供支持排查与 UI 提示;这些 id 走每插件的重新确认恢复入口。
*/
failedIds?: string[];
+ /**
+ * 迁移状态机,缺省按 `completed` 读(与旧台账兼容)。
+ *
+ * `in-progress` 在**首个 backfill 动笔之前**原子落盘,记下本轮要迁的完整 id 清单
+ * (`pendingIds`)。这是崩溃安全的关键:迁移中途崩溃/断电时,receipt 首写自动落
+ * 台账的守卫(见 `write`)不会把门焊死 —— 下次启动看到 `in-progress` 就按
+ * `pendingIds` 续跑,已写出 receipt 的 id 自然跳过,全部处理完才原子改写成
+ * `completed`。清单钉死在动笔前,续跑**只认清单内的 id**:迁移窗口期间新装再删
+ * receipt 的 id 不在清单里,骗不到续跑重铸。
+ */
+ state?: 'in-progress' | 'completed';
+ /** 仅 `in-progress`:本轮待迁 id 全集(动笔前钉死)。 */
+ pendingIds?: string[];
}
/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */
@@ -176,12 +189,15 @@ export class GhostInstallReceiptStore {
// 会让 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(() => undefined);
}
@@ -240,12 +256,32 @@ export class GhostInstallReceiptStore {
const raw = JSON.parse(
fs.readFileSync(this.migrationLedgerPath(), 'utf8'),
) as GhostLegacyMigrationLedger;
- return raw && raw.version === 1 && Array.isArray(raw.migratedIds) ? raw : null;
+ if (!raw || raw.version !== 1 || !Array.isArray(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;
+ return raw;
} catch {
return null;
}
}
+ /**
+ * 迁移门是否已关死。三种情况:
+ * - 无台账 → 开(首轮迁移 / legacy 恢复流程的留门);
+ * - 台账 `in-progress` → 开(上一轮中途崩溃,按 pendingIds 续跑);
+ * - 台账 `completed` / 无 state(旧格式)/ **存在但读不出** → 关。
+ * 损坏台账按"关"处理是刻意的保守方向:台账由原子 temp+rename 写出,自然损坏面
+ * 趋近于零;能改坏它的进程与 §7「可直接伪造合法 receipt」同类,把门放开反而是
+ * 给这类进程送一条重铸授权的路。调用方发现"存在但读不出"应记 error 日志。
+ */
+ migrationDoorClosed(): boolean {
+ if (!this.hasMigrationLedger()) return false;
+ const ledger = this.readMigrationLedger();
+ return ledger === null || ledger.state !== 'in-progress';
+ }
+
/** 是否已跑过一轮 legacy 迁移(全局一次性门;读不动按"存在"处理,宁可不再迁)。 */
hasMigrationLedger(): boolean {
try {
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 684a10806a..cadf561024 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -4055,6 +4055,10 @@ export function registerGhostIpc(): void {
ipcMain.handle('ghosts:install', async (event, lizFilePath: unknown, opts: unknown) => {
assertTrustedAppRendererEvent(event);
+ // 与市场路径同款 owner 租约:入口处同步捕获 owner,异步 inspect 之后、真正动
+ // 文件系统之前取租约并核对 owner 未变 —— manager 的内容根/状态根都是调用时
+ // 现解析的,异步窗口里账号切换落定会让后半段写进新 owner 的命名空间。
+ const mutationOwner = captureGhostMutationOwner();
if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'lizFilePath must be a non-empty string');
}
@@ -4077,12 +4081,17 @@ export function registerGhostIpc(): void {
// Node 高风险提示在 renderer 装入确认卡的权限清单里如实展示;
// 2026-07-24 Lizi 定案:不再追加 Main 原生二次确认弹窗。
const enable = installOpts.enable === true;
- return {
- ghost: await installAndDock(manager, lizFilePath, {
- enable,
- expectedPackageSha256: installOpts.expectedPackageSha256,
- }),
- };
+ const releaseMutation = beginGhostMutation(mutationOwner);
+ try {
+ return {
+ ghost: await installAndDock(manager, lizFilePath, {
+ enable,
+ expectedPackageSha256: installOpts.expectedPackageSha256,
+ }),
+ };
+ } finally {
+ releaseMutation();
+ }
});
// 原位更新(同 id 换版):先熄灯沙箱(新代码由下一次派活/面板重挂拉起),
@@ -4090,6 +4099,8 @@ export function registerGhostIpc(): void {
// 停靠(新版本首次声明面板时补位;已停靠则不动树)。
ipcMain.handle('ghosts:update', async (event, lizFilePath: unknown, opts: unknown) => {
assertTrustedAppRendererEvent(event);
+ // 同 ghosts:install:入口同步捕获 owner,异步 inspect 后、熄灯与换版之前取租约。
+ const mutationOwner = captureGhostMutationOwner();
if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'lizFilePath must be a non-empty string');
}
@@ -4121,42 +4132,49 @@ export function registerGhostIpc(): void {
rejectReservedGhostId(inspected.manifest.id);
rejectUnauthorizedTokenBroker(inspected.manifest);
const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
- runtime.stop(inspected.manifest.id);
- getGhostNodeRuntimeBroker().stop(inspected.manifest.id);
- getGhostAgentSlot().clearGhost(inspected.manifest.id);
- getGhostErrandSlot().clearGhost(inspected.manifest.id);
- let result: Awaited<ReturnType<typeof manager.update>>;
+ // 从熄灯到换版收尾整段持租约:熄灯之后的每一步都在改"当前 owner"的插件世界,
+ // 中途 owner 切换落定会把后半段(update 落盘/停靠/点火)写进新 owner。
+ const releaseMutation = beginGhostMutation(mutationOwner);
try {
- result = await manager.update(lizFilePath, {
- expectedPackageSha256,
- expectedInstalledApproval,
- });
- } catch (err) {
- // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)
- if (previousGhost) spawnIfResident(previousGhost);
- throw err;
- }
- if ('rejection' in result) {
- // 回滚失败时安装目录状态未知(可能是新字节/缺失),不按"旧版本还在"重启。
- if (
- previousGhost &&
- !(result.rejection.code === 'io' && result.rejection.rollbackFailed)
- ) {
- spawnIfResident(previousGhost);
+ runtime.stop(inspected.manifest.id);
+ getGhostNodeRuntimeBroker().stop(inspected.manifest.id);
+ getGhostAgentSlot().clearGhost(inspected.manifest.id);
+ getGhostErrandSlot().clearGhost(inspected.manifest.id);
+ let result: Awaited<ReturnType<typeof manager.update>>;
+ try {
+ result = await manager.update(lizFilePath, {
+ expectedPackageSha256,
+ expectedInstalledApproval,
+ });
+ } catch (err) {
+ // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)
+ if (previousGhost) spawnIfResident(previousGhost);
+ throw err;
}
- throwInstallError(result.rejection);
- }
- runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账
- const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
- if (docked) {
- const applied = store.setLayout(docked);
- if ('rejection' in applied) {
- log.warn('ghost panel dock rejected', { id: result.ghost.manifest.id, reason: applied.rejection });
+ if ('rejection' in result) {
+ // 回滚失败时安装目录状态未知(可能是新字节/缺失),不按"旧版本还在"重启。
+ if (
+ previousGhost &&
+ !(result.rejection.code === 'io' && result.rejection.rollbackFailed)
+ ) {
+ spawnIfResident(previousGhost);
+ }
+ throwInstallError(result.rejection);
}
+ runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账
+ const store = getLayoutStore();
+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
+ if (docked) {
+ const applied = store.setLayout(docked);
+ if ('rejection' in applied) {
+ log.warn('ghost panel dock rejected', { id: result.ghost.manifest.id, reason: applied.rejection });
+ }
+ }
+ spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火
+ return { ghost: result.ghost };
+ } finally {
+ releaseMutation();
}
- spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火
- return { ghost: result.ghost };
});
// 设置页「装入意识…」第一步:系统文件选择框(按 .cindy 过滤),只选不装。
@@ -4389,23 +4407,31 @@ export function registerGhostIpc(): void {
if (typeof enabled !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'enabled must be a boolean');
}
- if (!enabled) {
- runtime.stop(id); // 沉睡立即熄灯
- getGhostNodeRuntimeBroker().stop(id); // 随包 Node 也立即关闭
- getGhostSubscriptionGateway().dropGhost(id); // 订阅态清零(缓冲/熔断/seq)
- // 与更新/撤销路径同款:agent 工具授权与 errand 节流/在途记录不跨停用存活,
- // 重新启用后从干净状态开始。
- getGhostAgentSlot().clearGhost(id);
- getGhostErrandSlot().clearGhost(id);
- }
- const result = await manager.setEnabled(id, enabled);
- if ('rejection' in result) throwUninstallError(result.rejection);
- if (enabled) {
- runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起
- const ghost = findAvailableGhost(id);
- if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动
+ // 同 install/update 的 owner 租约:setEnabled 先 await pathExists(旧 owner 的
+ // 安装目录)再动态写 receipt —— 不持租约,这个异步窗口里切号落定会拿 A 的镜像
+ // 状态改 B 的 receipt(启停同时落在两个 owner 的两半)。
+ const releaseMutation = beginGhostMutation(captureGhostMutationOwner());
+ try {
+ if (!enabled) {
+ runtime.stop(id); // 沉睡立即熄灯
+ getGhostNodeRuntimeBroker().stop(id); // 随包 Node 也立即关闭
+ getGhostSubscriptionGateway().dropGhost(id); // 订阅态清零(缓冲/熔断/seq)
+ // 与更新/撤销路径同款:agent 工具授权与 errand 节流/在途记录不跨停用存活,
+ // 重新启用后从干净状态开始。
+ getGhostAgentSlot().clearGhost(id);
+ getGhostErrandSlot().clearGhost(id);
+ }
+ const result = await manager.setEnabled(id, enabled);
+ if ('rejection' in result) throwUninstallError(result.rejection);
+ if (enabled) {
+ runtime.resetFuse(id); // 重新唤醒 = 清熔断记账,可再拉起
+ const ghost = findAvailableGhost(id);
+ if (ghost) spawnIfResident(ghost); // 常驻意识:唤醒即启动
+ }
+ return { ok: true };
+ } finally {
+ releaseMutation();
}
- return { ok: true };
});
// 运行时状态快照(面板错误接管态的首帧数据源;广播只覆盖后续变化)。
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 14d9d80716..fdb60bd613 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -275,10 +275,13 @@
之后凭迁移 ledger 瞬时 no-op),从旧的三份事实源(`ghost.json` / `.cindy-trust.json` /
`.disabled`)重建等价 receipt,让市场与本地安装升级后无感可用;随包内置插件仍走
provisioning 的 `approveTrustedBundledInstall`(有权威字节可比,是更强的迁移形态),不
- 重复迁移。三条不变量:**全局一次性**(状态根有 `.legacy-migration.json` ledger 即视为已
- 迁过,此后缺 receipt 一律 fail closed,不再迁——否则删 receipt 就能骗一次"从可变安装
- 目录重建授权";该门是充分守卫,因为能删 ledger 的进程本就能直接写伪造 receipt,见下
- 「批准状态根无写保护」)、**不扩权**(权限集原样取当前 `ghost.json`,等价于旧模型无条件
+ 重复迁移。三条不变量:**全局一次性且崩溃安全**(ledger 是 in-progress→completed 两态状态机:
+ 首个 backfill 动笔前先原子落 `in-progress` 并钉死本轮 `pendingIds`,全部处理完才原子
+ 改写成 `completed`;`completed`/存在但读不出 = 门关死,此后缺 receipt 一律 fail closed
+ ——否则删 receipt 就能骗一次"从可变安装目录重建授权";`in-progress` = 上一轮中途崩溃,
+ 续跑**只认清单内的 id**,迁移窗口期间新装再删 receipt 的 id 骗不到重铸;receipt 首写
+ 自动补落的 completed 台账只在"完全没有台账"时动笔,不覆盖 in-progress。该门是充分
+ 守卫,因为能删/改 ledger 的进程本就能直接写伪造 receipt,见下「批准状态根无写保护」)、**不扩权**(权限集原样取当前 `ghost.json`,等价于旧模型无条件
授权的那一组,此后任何 manifest/权限变化照旧走完整确认)、**只写状态根不动安装目录**
(三份旧文件原样保留,回滚到旧客户端时仍按安装目录判定,符合第 5 节兜底第 4 条)。核心
授权事实读不出(manifest 不合法、技能目录含链接、声明的 locale 装入后损坏)才对该插件