Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 停用镜像丢失不再翻转随包批准的启停态,随包批准门加运行期边界
Yuewei-LLac6a8127dfd3
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 5dc2d21512..fe4f689e00 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -78,6 +78,12 @@ export interface GhostManagerOptions {onChanged?: (ghosts: InstalledGhost[]) => void;/** 当前宿主语言;插件未提供时由 shared 契约固定回退英文。 */getLocale?: () => string;+ /**+ * `approveTrustedBundledInstall` 的 builtin-only 边界:id 是否对应一颗随包种子。+ * 生产接线必须提供 —— 该入口不经用户确认就铸出批准,此前这条边界只靠"唯一+ * 调用者是随包对账"的纪律,没有运行期强制。未注入时不加门(单测直接驱动)。+ */+ isTrustedBundledId?: (id: string) => boolean;/** Cindy 维护的发布者/审核公钥表;缺省为空,签名仍验完整性但不抬身份等级。 */trustRegistry?: GhostTrustRegistry;log?: GhostManagerLogger;@@ -1050,12 +1056,25 @@ export class GhostManager {/*** 随包种子已经由 provisioning 层逐字节对账后,为其建立 Host 批准状态。- * 该入口不得用于市场包或任意本地目录;它不替代用户安装确认。+ * 该入口不得用于市场包或任意本地目录;它不替代用户安装确认。id 必须落在注入的+ * 随包种子清单里(`isTrustedBundledId`)。+ *+ * `markerEnabled` 是安装目录 `.disabled` 兼容镜像的读数,**只往停用方向合并,+ * 不往启用方向翻**:receipt 才是授权事实,镜像文件可被外部因素移除(AV 隔离+ * 恢复/同步冲突解析/手动清理),拿它覆写 receipt 会让用户显式停用的插件在下一轮+ * 对账被静默重新启用 —— 无确认、无审计,且带 skill 槽的插件会随之重新挂进全局+ * 技能链。反方向(镜像说停用、receipt 说启用)必须照办:停用是安全方向,而且+ * 旧客户端只会写镜像文件。重新启用只有用户显式 `setEnabled(true)` 一条路。*/async approveTrustedBundledInstall(manifest: GhostManifest,- enabled: boolean,+ markerEnabled: boolean,): Promise<boolean> {+ if (this.options.isTrustedBundledId?.(manifest.id) === false) {+ 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;@@ -1068,6 +1087,27 @@ export class GhostManager {reviewed: true,};const current = this.readApproval(manifest.id);+ // priorEnabled 直接读盘上的 receipt 而不是 readApproval 的投影:进程内隔离态的+ // receipt 不可作授权事实,但"曾经停用"这个位只用于往下拉,是 fail closed 方向,+ // 采纳它只会更保守 —— 否则"隔离 + 镜像同时丢失"的组合会让自愈把插件带回启用。+ const persisted =+ current.state === 'approved' ? current : this.receiptStore.read(manifest.id);+ const priorEnabled =+ persisted.state === 'approved' ? persisted.receipt.enabled : undefined;+ const enabled =+ priorEnabled === undefined ? markerEnabled : markerEnabled && priorEnabled;+ if (enabled !== markerEnabled) {+ // receipt 钉着停用而镜像丢了:把 `.disabled` 补写回去,守住"回滚到旧客户端时+ // 按镜像判启停"的降级承诺。写不进不影响批准事实,receipt 仍是权威。+ try {+ fs.writeFileSync(path.join(dir, DISABLED_MARKER_FILE), '');+ } catch (err) {+ this.options.log?.warn('ghost disabled mirror rewrite failed', {+ id: manifest.id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }if (current.state === 'approved' &&isDeepStrictEqual(current.receipt.manifest, manifest) &&diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 326e69ab1f..2618dc0ef7 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -1012,6 +1012,75 @@ describe('GhostManager · Host approval receipt', () => {});});+ 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'] };+ // 随包对账首轮把安装收编成 bundled 批准(trust 归一),后续轮次走稳态分支。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).toBe(true);+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);++ // 外部因素(AV 隔离恢复 / 同步冲突解析 / 手动清理)移除了兼容镜像文件。+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));++ // 下一轮对账把镜像读数(启用)喂进来:不得据此翻转 receipt —— 否则用户显式+ // 停用的插件被静默重新启用,无确认、无审计。重新启用只有 setEnabled 一条路。+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).toBe(false);+ expect(manager.list()[0].enabled).toBe(false);+ // 镜像被补写回去:回滚到旧客户端(只认镜像文件)时仍按停用对待。+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);+ });++ it('an old-client style .disabled marker still turns a bundled receipt off', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).toBe(true);++ // 旧客户端只会写镜像文件、不会写 receipt。停用是安全方向,合并必须照办 ——+ // 非对称的另一半:镜像只能把启停态往下拉,不能往上翻。+ await fs.promises.writeFile(path.join(rootDir, 'hello', '.disabled'), '');+ expect(await manager.approveTrustedBundledInstall(approvedManifest, false)).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);+ });++ it('a bundled update keeps the receipt-pinned disable even when the marker was lost', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ const { manifest: approvedManifest } = JSON.parse(+ await fs.promises.readFile(receiptPath(), 'utf8'),+ ) as { manifest: InstalledGhost['manifest'] };+ expect(await manager.approveTrustedBundledInstall(approvedManifest, true)).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(manager.list()[0]).toMatchObject({+ enabled: false,+ manifest: { version: '1.0.1' },+ });+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(true);+ });++ it('refuses to mint a bundled approval for an id outside the seed roster', async () => {+ // 该入口不经用户确认就铸出批准;builtin-only 边界必须运行期强制,不能只靠+ // "唯一调用者是随包对账"这条纪律。+ const guarded = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: () => false,+ });+ const validated = validateGhostManifest(goodManifest());+ if (!validated.ok) throw new Error(validated.reason);+ await expect(+ guarded.approveTrustedBundledInstall(validated.manifest, true),+ ).rejects.toThrow(/种子清单/);+ });+it('invalidates a receipt whose locale snapshot keys no longer match the manifest', async () => {hostLocale = 'en';const manifest = {diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 88be838c27..82ef0f9aa8 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -15,6 +15,7 @@import fs from 'node:fs';import path from 'node:path';+import { promisify } from 'node:util';import JSZip from 'jszip';@@ -406,6 +407,13 @@ function hasFsErrorCode(err: unknown, code: string): boolean {return Boolean(err && typeof err === 'object' && 'code' in err && err.code === code);}+/**+ * realpath 一律走 `.native` 变体:与 dirDeposit / ghostLocalPathGrant 等其余钳制点+ * 同一口径(受管根判定的最终比较虽已做 win32 大小写折叠,但解析器本身也不该是+ * 全仓唯一的例外)。`fs.promises.realpath` 没有 native 变体,promisify 一次。+ */+const realpathNative = promisify(fs.realpath.native);+/*** 创建一份不覆盖任何现有内容的插件源码骨架。*@@ -440,31 +448,22 @@ export async function scaffoldGhostDir(// 就取「已存在的最深祖先」的真身再拼回剩余段。let realWorkdir: string;try {- realWorkdir = await fs.promises.realpath(path.resolve(workdir));+ realWorkdir = await realpathNative(path.resolve(workdir));} catch {return { ok: false, errorCode: 'INVALID_INPUT', message: '会话工作目录不存在,无法确定骨架输出位置' };}- let realAncestor = resolved;- const pendingSegments: string[] = [];- for (;;) {- try {- realAncestor = await fs.promises.realpath(realAncestor);- break;- } catch (err) {- if (!hasFsErrorCode(err, 'ENOENT')) {- return {- ok: false,- errorCode: 'INTERNAL',- message: err instanceof Error ? err.message : String(err),- };- }- const parent = path.dirname(realAncestor);- if (parent === realAncestor) break; // 到根了,根一定存在,防御性兜底- pendingSegments.unshift(path.basename(realAncestor));- realAncestor = parent;- }+ // 「已存在的最深祖先取真身再拼回剩余段」与打包侧受管根解析共用同一个 helper ——+ // 这段 walk 原来在这里手写了一份,同一判定两份实现正是这条链路反复出问题的形态。+ let realTarget: string;+ try {+ realTarget = await resolveThroughExistingAncestor(resolved);+ } catch (err) {+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}- const realTarget = path.join(realAncestor, ...pendingSegments);if (!realTarget.startsWith(`${realWorkdir}${path.sep}`) && realTarget !== realWorkdir) {return { ok: false, errorCode: 'INVALID_INPUT', message: 'dir 必须在当前会话工作目录内' };}@@ -597,7 +596,7 @@ export async function packGhostDir(if (!stat.isDirectory()) {return { ok: false, errorCode: 'DIR_NOT_FOUND', message: `不是目录:${dir}` };}- const realSourceDir = await fs.promises.realpath(dir);+ const realSourceDir = await realpathNative(dir);for (const forbiddenRoot of options.forbiddenRootDirs ?? []) {const resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);// 判定必须**双向**:源目录落在受管根内要拒(拿已安装插件当源码),源目录是受管根的@@ -787,7 +786,7 @@ async function resolveThroughExistingAncestor(inputPath: string): Promise<stringconst tail: string[] = [];while (true) {try {- const real = await fs.promises.realpath(cursor);+ const real = await realpathNative(cursor);return path.join(real, ...tail);} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex c837dece27..761890411e 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -791,6 +791,9 @@ async function reconcileBuiltinGhostsLocked(approvalChanged =(await manager.approveTrustedBundledInstall(manifest,+ // `.disabled` 镜像的读数只作停用方向的输入:receipt 已钉停用时,镜像被+ // 外部移除不会把插件翻回启用(合并规则见 approveTrustedBundledInstall+ // 头注释;重新启用只有用户显式 setEnabled 一条路)。!fs.existsSync(path.join(brainRootDir(), manifest.id, '.disabled')),)) || approvalChanged;} catch (err) {@@ -864,6 +867,9 @@ export function getGhostManager(): GhostManager {onChanged: broadcastGhostsChanged,getLocale: getResolvedMainLocale,trustRegistry: loadGhostTrustRegistry(),+ // 随包批准入口的 builtin-only 边界:id 必须对应一颗随包种子。该入口不经用户+ // 确认就铸出批准,不能只靠"唯一调用者是随包对账"这条纪律。+ isTrustedBundledId: (id) => listBuiltinSeedIds(builtinSeedRootDirs()).includes(id),log,});getGhostSetupManifestTracker().seed(managerSingleton.list());