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): 修复第 8 轮 review 批 B——update 崩溃恢复/包投影基线/inspect 票据绑 owner/对账租约

Yuewei-LL39753ba5c9af
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 3641f01aa6..4276a3f50d 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -31,6 +31,7 @@ import { isPathInsideDir } from './dirDeposit.js';
import {
classifyGhostDirEntrySync,
collectGhostContentFiles,
+ hashGhostContentBuffers,
hashGhostContentFiles,
resolveGhostContentPathSync,
} from './ghostContentTree.js';
@@ -171,6 +172,114 @@ export class GhostManager {
) {
throw new Error('ghost install content and approval state roots must be disjoint');
}
+ this.recoverInterruptedUpdatesSync();
+ }
+
+ /**
+ * 启动一次性:恢复更新的"两次 rename 之间"崩溃现场(§5:插件不得凭空消失)。
+ *
+ * update 的目录交换是 final→backup(.cindy-updating-*)、staging→final 两步;断电/
+ * 进程被杀落在两步之间时,final 缺位、旧版完整字节还在 backup 里 —— 而 list()
+ * 跳过点目录,插件就从 UI 与运行时**消失**了。这里在构造期同步扫一遍(目录极小,
+ * 与 resolveGhostRepoRoot 的启动期迁移同一先例):
+ * - final 缺位且该 id 只有唯一 backup → 原子搬回(receipt 未更新过,恢复后
+ * receipt/内容完全一致,等价于更新从未发生);
+ * - final 在位(崩溃发生在收尾清理前)→ backup 是已被替换的旧字节,回收;
+ * - 同 id 多个 backup(多次崩溃)→ 不猜,原样保留并记 error 供人工处理;
+ * - `.cindy-installing-*` staging 残留一律回收(从未发布过,不构成任何事实)。
+ */
+ private recoverInterruptedUpdatesSync(): void {
+ const root = this.options.getRootDir();
+ let entries: fs.Dirent[];
+ try {
+ entries = fs.readdirSync(root, { withFileTypes: true });
+ } catch {
+ return; // 根目录还不存在 = 没装过任何插件
+ }
+ const backups = entries.filter((entry) => entry.name.startsWith('.cindy-updating-'));
+ 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];
+ const backupPath = path.join(root, entry.name);
+ try {
+ if (classifyGhostDirEntrySync(backupPath) !== 'directory') continue;
+ } catch {
+ continue;
+ }
+ const finalDir = path.join(root, id);
+ const siblings = backups.filter((other) =>
+ other.name.startsWith(`.cindy-updating-${id}-`),
+ );
+ if (fs.existsSync(finalDir)) {
+ try {
+ fs.rmSync(backupPath, { recursive: true, force: true });
+ } catch (err) {
+ this.options.log?.warn('stale ghost update backup cleanup failed', {
+ id, backup: entry.name,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ continue;
+ }
+ if (siblings.length !== 1) {
+ (this.options.log?.error ?? this.options.log?.warn)?.call(this.options.log,
+ 'multiple interrupted-update backups for one ghost; left untouched for manual recovery', {
+ id, backups: siblings.map((other) => other.name),
+ });
+ continue;
+ }
+ try {
+ fs.renameSync(backupPath, finalDir);
+ this.options.log?.info('ghost restored from interrupted update backup', { id });
+ } catch (err) {
+ (this.options.log?.error ?? this.options.log?.warn)?.call(this.options.log,
+ 'ghost interrupted-update recovery failed; plugin stays missing until manual recovery', {
+ id, backup: entry.name,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ for (const entry of entries) {
+ if (!entry.name.startsWith('.cindy-installing-')) continue;
+ try {
+ fs.rmSync(path.join(root, entry.name), { recursive: true, force: true });
+ } catch {
+ // staging 残留清不掉只占磁盘,不影响正确性;下次启动再试。
+ }
+ }
+ }
+
+ /**
+ * 从 `.cindy` 包的内存投影算技能字节指纹(P0-8)。
+ *
+ * 批准基线必须取自**用户确认过、且不可再被本机进程改写**的来源。旧写法在
+ * staging→final 发布之后才从 finalDir 首读 —— publish 与首次 hash 之间被换掉的
+ * SKILL.md 正文/辅助文件会同时成为 receipt 指纹与快照,后续校验全自洽,篡改被
+ * 洗成批准事实。包投影(JSZip 内存条目)在 inspect 时已被 packageSha256 钉住、
+ * 与用户确认的是同一份字节;据它算指纹后,发布后的目录漂移会在快照落盘对账时
+ * 如实 fail closed(拒装),而不是被钉进批准。
+ */
+ private async hashSkillContentFromPackage(
+ manifest: GhostManifest,
+ allEntries: JSZip.JSZipObject[],
+ prefix: string,
+ ): Promise<Record<string, string>> {
+ const items = manifest.skill?.items ?? [];
+ if (items.length === 0) return {};
+ const result: Record<string, string> = {};
+ for (const item of items) {
+ const itemPrefix = `${item.dir}/`;
+ const files: { path: string; bytes: Buffer }[] = [];
+ for (const entry of allEntries) {
+ if (entry.dir) continue;
+ const rel = entry.name.slice(prefix.length);
+ if (!rel.startsWith(itemPrefix)) continue;
+ files.push({ path: rel.slice(itemPrefix.length), bytes: await entry.async('nodebuffer') });
+ }
+ result[item.dir] = hashGhostContentBuffers(files);
+ }
+ return result;
}
/** Forge 等 Host 能力必须排除的受管根(内容根 + 批准状态根)。 */
@@ -1434,7 +1543,13 @@ export class GhostManager {
localeResources,
enabled: initiallyEnabled,
trust,
- skillContentSha256: await hashApprovedSkillContent(approvedManifest, finalDir),
+ // 指纹取自包投影而不是刚发布的 finalDir:发布后被换的字节应当在快照
+ // 对账时被拒,而不是被首读钉成批准基线(P0-8)。
+ skillContentSha256: await this.hashSkillContentFromPackage(
+ approvedManifest,
+ allEntries,
+ prefix,
+ ),
packageSha256,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
});
@@ -1612,7 +1727,12 @@ export class GhostManager {
localeResources,
enabled,
trust,
- skillContentSha256: await hashApprovedSkillContent(approvedManifest, finalDir),
+ // 同 install:指纹取自包投影,发布后的目录漂移在快照对账时 fail closed(P0-8)。
+ skillContentSha256: await this.hashSkillContentFromPackage(
+ approvedManifest,
+ allEntries,
+ prefix,
+ ),
packageSha256,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
});
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 656b96fb7e..789c4af58c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -1840,6 +1840,83 @@ describe('GhostManager · Host approval receipt', () => {
});
});
+describe('GhostManager · 技能批准基线取自包投影(publish 后篡改必须拒装)', () => {
+ it('staging→final 发布后、首次校验前换掉 SKILL.md → 拒装,篡改字节不成为批准事实', async () => {
+ const cindy = await makeCindy('skill.cindy', {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ }, {
+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
+ });
+ // 故障注入:staging→final 的 rename 真实执行后,立刻在 finalDir 里改写 SKILL.md
+ // 正文 —— 模拟"发布与首次 hash 之间"的本机进程篡改窗口。
+ const realRename = fs.promises.rename;
+ const finalDir = path.join(rootDir, 'skilled');
+ const spy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {
+ await realRename(from, to);
+ if (String(to) === finalDir) {
+ spy.mockRestore();
+ await fs.promises.writeFile(
+ path.join(finalDir, 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',
+ );
+ }
+ });
+ try {
+ const result = await manager.install(cindy);
+ // 修复前:指纹从被篡改的 finalDir 首读,篡改字节自洽地成为 receipt 指纹与
+ // 快照,install 返回 ok。修复后:指纹来自包投影,快照对账发现字节不符 → 拒装。
+ expect('rejection' in result, JSON.stringify(result)).toBe(true);
+ } finally {
+ spy.mockRestore();
+ }
+ // 拒装收尾:不留半截安装,也没有任何批准事实落盘。
+ expect(manager.list()).toHaveLength(0);
+ expect(
+ fs.existsSync(path.join(workDir, 'ghosts-install-state', 'skilled.json')),
+ ).toBe(false);
+ });
+});
+
+describe('GhostManager · 更新崩溃恢复(两次 rename 之间)', () => {
+ it('final 缺位 + 唯一 backup → 下次启动自动搬回,插件不凭空消失', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 模拟崩溃现场:final→backup 已发生,staging→final 没来得及。
+ await fs.promises.rename(
+ path.join(rootDir, 'hello'),
+ path.join(rootDir, '.cindy-updating-hello-abcdef01'),
+ );
+ // 崩溃前 list() 视角:插件消失(点目录被跳过)—— 这正是要修的现场。
+ expect(manager.list()).toHaveLength(0);
+
+ // "重启":新建 manager,构造期恢复扫描搬回。receipt 从未更新过,恢复后
+ // receipt 与内容完全一致,等价于那次更新从未发生。
+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+ expect(restarted.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);
+ });
+
+ it('final 在位的陈旧 backup 与 staging 残留 → 回收;同 id 多个 backup 不猜、原样保留', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-abcdef01'), { recursive: true });
+ await fs.promises.mkdir(path.join(rootDir, '.cindy-installing-hello-deadbeef'), { recursive: true });
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-abcdef01'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-installing-hello-deadbeef'))).toBe(false);
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'ghost.json'))).toBe(true);
+
+ // 多 backup 且 final 缺位:不猜哪份是对的,原样保留等人工处理。
+ await fs.promises.rename(path.join(rootDir, 'hello'), path.join(rootDir, '.cindy-updating-hello-11111111'));
+ await fs.promises.mkdir(path.join(rootDir, '.cindy-updating-hello-22222222'), { recursive: true });
+ new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-11111111'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, '.cindy-updating-hello-22222222'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(false);
+ });
+});
+
describe('GhostManager · setEnabled(启用/停用)', () => {
it('停用镜像本身写失败 → 如实报错,不谎报"已停用"(此刻什么都没落盘)', async () => {
await manager.install(await makeCindy('a.cindy', goodManifest()));
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
index 6c68ef2fb8..c84fa42012 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
@@ -16,6 +16,7 @@ import {
classifyGhostDirEntry,
classifyGhostDirEntrySync,
collectGhostContentFiles,
+ hashGhostContentBuffers,
hashGhostContentFiles,
resolveGhostContentPath,
resolveGhostContentPathSync,
@@ -208,3 +209,40 @@ describe('hashGhostContentFiles', () => {
);
});
});
+
+describe('hashGhostContentBuffers', () => {
+ it('与 hashGhostContentFiles 对同一棵文件树逐字节等价(装入基线与快照对账共用判据)', async () => {
+ const root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-buf-hash-'));
+ try {
+ await fs.promises.mkdir(path.join(root, 'nested'), { recursive: true });
+ const tree: Record<string, string> = {
+ 'SKILL.md': '---\nname: x\n---\nbody',
+ '.hidden': 'dot files count',
+ 'nested/helper.txt': 'helper',
+ };
+ for (const [rel, content] of Object.entries(tree)) {
+ await fs.promises.writeFile(path.join(root, ...rel.split('/')), content);
+ }
+ const { files } = await collectGhostContentFiles(root, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'test',
+ });
+ const fromDisk = await hashGhostContentFiles(root, files);
+ const fromMemory = hashGhostContentBuffers(
+ Object.entries(tree).map(([p2, c]) => ({ path: p2, bytes: Buffer.from(c) })),
+ );
+ expect(fromMemory).toBe(fromDisk);
+ // 内容差一个字节即不同。
+ const drifted = hashGhostContentBuffers(
+ Object.entries({ ...tree, 'SKILL.md': tree['SKILL.md'] + '!' }).map(([p2, c]) => ({
+ path: p2,
+ bytes: Buffer.from(c),
+ })),
+ );
+ expect(drifted).not.toBe(fromDisk);
+ } finally {
+ await fs.promises.rm(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
index 07964c6de4..3497f6ac94 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts
@@ -25,7 +25,6 @@ const MUTATING_GHOST_CHANNELS = [
'ghosts:install',
'ghosts:update',
'ghosts:set-enabled',
- 'ghosts:reapprove-installed',
] as const;
function handlerBlock(source: string, channel: string): string {
@@ -53,6 +52,22 @@ describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {
});
}
+ it('ghosts:reapprove-installed 持租约,owner 以 inspect 时点的一次性票据为准(更强于 handler 内 capture)', () => {
+ // 第 8 轮 P0-2:owner 在 confirm 入口才 capture 绑不住"读事实那一刻"——确认卡
+ // 停留期间切号,A 看的确认可以给 B 的同 id 目录铸批准。现在 inspect 发一次性
+ // 票据(钉 owner + id + manifestSha256),confirm 原子消费并以**票据里的 owner**
+ // 起租约:generation 不等直接拒。handler 内不该再出现 captureGhostMutationOwner
+ // (那会退化回"用确认时刻的 owner",正是要消掉的形态)。
+ const block = handlerBlock(source, 'ghosts:reapprove-installed');
+ expect(block).toContain('reapproveTickets.consume(');
+ expect(block).toContain('beginGhostMutation(ticket.owner)');
+ expect(block).not.toContain('captureGhostMutationOwner()');
+ // inspect 侧必须在读事实之前捕获 owner 并发票。
+ const inspectBlock = handlerBlock(source, 'ghosts:reapprove-inspect');
+ expect(inspectBlock).toContain('captureGhostMutationOwner()');
+ expect(inspectBlock).toContain('reapproveTickets.issue(');
+ });
+
it('ghosts:uninstall 经 uninstallGhostAndCleanup 持租约(入口同步取,无异步窗口故无需 capture)', () => {
const block = handlerBlock(source, 'ghosts:uninstall');
expect(block).toContain('uninstallGhostAndCleanup(');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/oneShotTickets.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/oneShotTickets.test.ts
new file mode 100644
index 0000000000..04ba897a28
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/oneShotTickets.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { createOneShotTicketStore } from '../oneShotTickets';
+
+describe('oneShotTickets(inspect→confirm 的 owner/事实绑定载体)', () => {
+ it('原子消费:一张票只能用一次,重放拿不到值', () => {
+ const store = createOneShotTicketStore<{ id: string }>({ ttlMs: 1000, maxEntries: 4 });
+ const token = store.issue({ id: 'hello' });
+ expect(store.consume(token)).toEqual({ id: 'hello' });
+ // 重放:同一 token 第二次消费必须失败 —— 否则 confirm 可被重复落盘。
+ expect(store.consume(token)).toBeNull();
+ expect(store.consume('not-a-token')).toBeNull();
+ });
+
+ it('过期票拿不到值(确认卡长时间停留后必须重新 inspect)', () => {
+ let clock = 0;
+ const store = createOneShotTicketStore<number>({ ttlMs: 100, maxEntries: 4, now: () => clock });
+ const token = store.issue(42);
+ clock = 99;
+ const fresh = store.issue(43);
+ clock = 100; // 第一张到期,第二张(99+100)未到期
+ expect(store.consume(token)).toBeNull();
+ expect(store.consume(fresh)).toBe(43);
+ });
+
+ it('超容量先驱逐最早签发的票,不无界增长', () => {
+ const store = createOneShotTicketStore<number>({ ttlMs: 10_000, maxEntries: 2 });
+ const first = store.issue(1);
+ const second = store.issue(2);
+ const third = store.issue(3); // 容量 2:签发第三张时驱逐第一张
+ expect(store.consume(first)).toBeNull();
+ expect(store.consume(second)).toBe(2);
+ expect(store.consume(third)).toBe(3);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
index 76dfebb2e4..9f2fef581c 100644
--- a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
@@ -208,6 +208,29 @@ export async function collectGhostContentFiles(
* 文件仍然流式读取,不整份进内存 —— 插件目录里除 SKILL.md 之外的文件没有尺寸
* 上限,整份 readFile 会让一个塞进来的超大文件把 Host 撑爆。
*/
+/**
+ * `hashGhostContentFiles` 的内存版:对"路径 + 字节"的内存投影算同一 framing 的
+ * 指纹(逐字节等价,有回归钉住)。用途:装入/更新时从 **.cindy 包本体**(不可变的
+ * JSZip 投影)算批准基线,而不是从已公开的可变安装目录首读 —— 后者在 publish 与
+ * 首次 hash 之间被换过的字节会自洽地成为批准事实(权威判据被污染源初始化)。
+ */
+export function hashGhostContentBuffers(
+ files: readonly { path: string; bytes: Buffer }[],
+): string {
+ const hash = crypto.createHash('sha256');
+ hash.update('cindy-ghost-content-v2');
+ const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+ for (const file of sorted) {
+ const pathBytes = Buffer.from(file.path, 'utf8');
+ const pathLength = Buffer.allocUnsafe(8);
+ pathLength.writeBigUInt64BE(BigInt(pathBytes.byteLength));
+ hash.update(pathLength);
+ hash.update(pathBytes);
+ hash.update(crypto.createHash('sha256').update(file.bytes).digest());
+ }
+ return hash.digest('hex');
+}
+
export async function hashGhostContentFiles(
rootDir: string,
files: readonly string[],
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 94ea5483cc..4b24ed4cae 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -42,6 +42,7 @@ import { getLayoutStore } from '../layout/index.js';
import { GhostManager, type InstallRejection, type UninstallRejection } from './GhostManager.js';
import { exportGhostPackage } from './exportGhostPackage.js';
import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';
+import { createOneShotTicketStore } from './oneShotTickets.js';
import {
clearBuiltinTombstone,
listEligibleBuiltinCommands,
@@ -4200,6 +4201,14 @@ export function registerGhostIpc(): void {
// 本地包第三条恢复路径第一步:从**已装目录**读出确认卡事实,零副作用。
// 批准丢失(迁移后 receipt 又损坏/被删)时不用用户翻出原始 .cindy —— 字节从安装
// 目录读,权限清单全量展示,确认后由 ghosts:reapprove-installed 开 receipt。
+ // inspect 时点的 owner 与事实用一次性票据钉死,confirm 原子消费(P0-2):只回传
+ // manifestSha256 绑不住 owner —— 多账号下确认卡停留期间切号,A 看的确认可以给 B
+ // 的同 id 目录铸批准。票据 Host 进程内持有,renderer 只透传 opaque token。
+ const reapproveTickets = createOneShotTicketStore<{
+ owner: ActiveAppSession;
+ id: string;
+ manifestSha256: string;
+ }>({ ttlMs: 10 * 60 * 1000, maxEntries: 64 });
ipcMain.handle('ghosts:reapprove-inspect', (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
if (typeof id !== 'string' || id.trim().length === 0) {
@@ -4207,9 +4216,16 @@ export function registerGhostIpc(): void {
}
requireGhostAvailableForActiveSession(id);
rejectReservedGhostId(id);
+ // owner 在读事实**之前**捕获(边界期直接抛):票据钉的是"这份事实属于哪个 owner"。
+ const owner = captureGhostMutationOwner();
const result = manager.inspectInstalledReapproval(id);
if ('rejection' in result) throwInstallError(result.rejection);
- return result;
+ const inspectTicket = reapproveTickets.issue({
+ owner,
+ id,
+ manifestSha256: result.manifestSha256,
+ });
+ return { ...result, inspectTicket };
});
// 第三条恢复路径第二步:用户点过确认卡后开 receipt。expectedManifestSha256 绑定
@@ -4225,7 +4241,12 @@ export function registerGhostIpc(): void {
// 种子清单检查拒掉,这里拦的是冒充官方前缀的目录)。
rejectReservedGhostId(id);
const options = opts as
- | { enable?: unknown; expectedManifestSha256?: unknown; expectedInstalledApproval?: unknown }
+ | {
+ enable?: unknown;
+ expectedManifestSha256?: unknown;
+ expectedInstalledApproval?: unknown;
+ inspectTicket?: unknown;
+ }
| undefined;
if (typeof options?.enable !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'enable must be a boolean');
@@ -4239,9 +4260,21 @@ export function registerGhostIpc(): void {
if (!isGhostInstallApprovalToken(options.expectedInstalledApproval)) {
throwIpcError('INVALID_PARAMS', 'expectedInstalledApproval must come from ghosts:list');
}
- // 开 receipt 是 owner 绑定的状态根写路径:确认卡停留期间账号可能已切换,
- // 与装入/更新同一套租约与边界拒绝(beginGhostMutation 在边界期直接抛)。
- const releaseMutation = beginGhostMutation(captureGhostMutationOwner());
+ if (typeof options.inspectTicket !== 'string' || options.inspectTicket.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'inspectTicket must come from ghosts:reapprove-inspect');
+ }
+ // 原子消费票据:重放/过期/跨票一律 PRECONDITION_FAILED,让 UI 重开确认卡。
+ const ticket = reapproveTickets.consume(options.inspectTicket);
+ if (
+ !ticket ||
+ ticket.id !== id ||
+ ticket.manifestSha256 !== options.expectedManifestSha256
+ ) {
+ throwIpcError('PRECONDITION_FAILED', '确认卡已过期或与检查时不一致,请重新打开确认');
+ }
+ // 开 receipt 是 owner 绑定的状态根写路径:租约以**票据里 inspect 时点的 owner**
+ // 为期望值 —— 确认卡停留期间切了号,generation 不等直接拒,A 的确认给不了 B。
+ const releaseMutation = beginGhostMutation(ticket.owner);
let result: Awaited<ReturnType<typeof manager.reapproveInstalled>>;
try {
result = await manager.reapproveInstalled(id, {
@@ -4645,7 +4678,14 @@ function scheduleGhostSkillReconcile(): void {
try {
while (skillReconcilePending) {
skillReconcilePending = false;
+ // 每轮 capture owner + 持租约到本轮全部校验/删/建/扇出完成:全局技能根写的是
+ // owner-scoped 受管根的投影,不持租约时账号切换可以落在"A 的快照校验通过后、
+ // 链接创建前",把全局 ~/.agents/skills 指向 A 的批准快照 —— B 生效后主 Agent
+ // 有跨 owner 读取窗口。租约让 session teardown 的 waitForIdle 等本轮收尾;
+ // 边界期开轮直接抛,pending 保留,换号完成后的 ghosts:changed 广播重跑。
+ let releaseLease: (() => void) | null = null;
try {
+ releaseLease = beginGhostMutation(captureGhostMutationOwner());
const result = await reconcileGhostSkillLinks({
ghosts: getGhostManager().list(),
brainRoot: brainRootDir(),
@@ -4662,9 +4702,16 @@ function scheduleGhostSkillReconcile(): void {
});
}
} catch (err) {
+ if (isAppSessionBoundaryPending()) {
+ // 账号边界期:本轮不动盘,保留 pending 等换号完成后的广播重跑。
+ skillReconcilePending = true;
+ break;
+ }
log.warn('ghost skill reconcile failed', {
error: err instanceof Error ? err.message : String(err),
});
+ } finally {
+ releaseLease?.();
}
}
} finally {
diff --git a/apps/desktop/src/main/cindy-brain/oneShotTickets.ts b/apps/desktop/src/main/cindy-brain/oneShotTickets.ts
new file mode 100644
index 0000000000..ff71451548
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/oneShotTickets.ts
@@ -0,0 +1,53 @@
+import { randomUUID } from 'node:crypto';
+
+/**
+ * oneShotTickets —— Host 侧一次性票据(inspect → confirm 两段式 IPC 的绑定载体)。
+ *
+ * 存在的原因(P0-2):「inspect 读事实 → 用户确认 → confirm 落盘」跨两次 IPC,
+ * 只回传事实指纹(如 manifestSha256)绑不住**读事实那一刻的 owner**。多账号下
+ * A 在确认卡停留期间切到 B,若两边同 id/同指纹/同批准态 token,A 看的确认可以
+ * 给 B 的当前目录铸出批准。票据由 Host 进程内持有(opaque,renderer 只透传),
+ * 值里钉 inspect 时点的全部事实,confirm **原子消费**(取即删):重放、跨票、
+ * 过期一律拿不到值,fail closed。
+ *
+ * 进程内 Map 即可:票据只服务同进程内的一次 UI 往返,不落盘、不跨进程。
+ */
+export interface OneShotTicketStore<T> {
+ /** 发一张票,返回 opaque token。超容量时先驱逐最早签发的票。 */
+ issue(value: T): string;
+ /** 原子消费:取出即删除。不存在/已消费/已过期一律返回 null。 */
+ consume(token: string): T | null;
+}
+
+export function createOneShotTicketStore<T>(options: {
+ ttlMs: number;
+ maxEntries: number;
+ /** 时钟注入(仅测试)。 */
+ now?: () => number;
+}): OneShotTicketStore<T> {
+ const now = options.now ?? Date.now;
+ // Map 迭代序 = 插入序,驱逐最旧即删第一个键。
+ const tickets = new Map<string, { value: T; expiresAt: number }>();
+ return {
+ issue(value: T): string {
+ const current = now();
+ for (const [token, entry] of tickets) {
+ if (entry.expiresAt <= current) tickets.delete(token);
+ }
+ while (tickets.size >= options.maxEntries) {
+ const oldest = tickets.keys().next().value;
+ if (oldest === undefined) break;
+ tickets.delete(oldest);
+ }
+ const token = randomUUID();
+ tickets.set(token, { value, expiresAt: current + options.ttlMs });
+ return token;
+ },
+ consume(token: string): T | null {
+ const entry = tickets.get(token);
+ tickets.delete(token);
+ if (!entry || entry.expiresAt <= now()) return null;
+ return entry.value;
+ },
+ };
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 50813517fc..0a92a7bd37 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -908,11 +908,17 @@ contextBridge.exposeInMainWorld('electronAPI', {
trust: unknown;
manifestSha256: string;
previouslyEnabled: boolean;
+ inspectTicket: string;
}> => ipcRenderer.invoke('ghosts:reapprove-inspect', id),
- /** 确认卡点过同意后开 receipt;sha 绑定确认卡展示时的清单字节。 */
+ /** 确认卡点过同意后开 receipt;sha + 一次性票据绑定确认时的事实与 owner。 */
reapproveInstalled: (
id: string,
- opts: { enable: boolean; expectedManifestSha256: string; expectedInstalledApproval: string },
+ opts: {
+ enable: boolean;
+ expectedManifestSha256: string;
+ expectedInstalledApproval: string;
+ inspectTicket: string;
+ },
): Promise<{ ghost: unknown }> =>
ipcRenderer.invoke('ghosts:reapprove-installed', id, opts),
uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index 77bcf9338c..a5c96ac047 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -248,12 +248,14 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
let trust: GhostTrustInfo;
let manifestSha256: string;
let previouslyEnabled: boolean;
+ let inspectTicket: string;
try {
const inspected = await window.electronAPI.ghosts.reapproveInspect(ghostId);
manifest = inspected.manifest;
trust = inspected.trust;
manifestSha256 = inspected.manifestSha256;
previouslyEnabled = inspected.previouslyEnabled;
+ inspectTicket = inspected.inspectTicket;
} catch (err) {
// 安装目录读不出清单 = 只剩"重新选包"一条路;如实降级,不吞掉恢复机会。
installFlowLog.warn('reapprove-inspect failed; falling back to file picker', {
@@ -294,6 +296,7 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
enable,
expectedManifestSha256: manifestSha256,
expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
+ inspectTicket,
});
toast.success(t('settings.ghosts.toast.reapproved', { name: ghost.manifest.name }));
} catch (err) {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 90ae37ea0e..2271642867 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1167,11 +1167,18 @@ interface ElectronAPI {
manifestSha256: string;
/** 升级前的启停偏好(.disabled 镜像读数):确认卡勾选默认值。 */
previouslyEnabled: boolean;
+ /** 一次性票据(Host 进程内钉住 inspect 时点的 owner 与事实,confirm 原子消费)。 */
+ inspectTicket: string;
}>;
/** 第三条恢复路径第二步:用户点过确认卡后开 receipt。 */
reapproveInstalled: (
id: string,
- opts: { enable: boolean; expectedManifestSha256: string; expectedInstalledApproval: string },
+ opts: {
+ enable: boolean;
+ expectedManifestSha256: string;
+ expectedInstalledApproval: string;
+ inspectTicket: string;
+ },
) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
uninstall: (id: string) => Promise<{ ok: true }>;
/** 详情页「导出 .cindy」:打包安装目录 → 保存对话框落盘。 */
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index fdb60bd613..5e5759d4b5 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -104,7 +104,10 @@
校验 frontmatter 的 name/description,正文与辅助文件不在它的判据里)+
**批准快照与字节指纹**(确认时把技能目录逐字节拷进
`<状态根>/skill-snapshots/<id>/<revision>`,只收普通文件,同时把逐 item 的内容
- 指纹钉进 receipt 的 `skillContentSha256`;确认框看到的 SKILL.md 必须就是 Agent 之后
+ 指纹钉进 receipt 的 `skillContentSha256`——装入/更新时该指纹取自 **`.cindy` 包的
+ 内存投影**(inspect 时已被 `packageSha256` 钉住的那份字节),不从已发布的可变安装
+ 目录首读:publish 与首次 hash 之间被换的字节应当在快照对账时被拒,而不是被首读钉成
+ 批准基线;确认框看到的 SKILL.md 必须就是 Agent 之后
读到的那份,所以共享技能根的链接指快照而不是可被改写的 `cindy-brain/<id>/<dir>`。
快照缺失需要从安装目录重建时,**顺序本身就是安全性质**:先把字节复制进状态根的
临时目录,再对**临时目录里那份即将成为快照的字节**做全部权威校验(尺寸上限 →