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。

feat(desktop): 存量插件一次性 legacy 迁移,升级无感(§5 红线)

Yuewei-LLcd3b170ec173
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index fe4f689e00..f51efcc267 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -37,6 +37,7 @@ import {
createGhostInstallReceipt,
GhostInstallReceiptStore,
hashApprovedSkillContent,
+ readLegacyInstallTrust,
type GhostInstallReceipt,
type GhostInstallReceiptReadResult,
} from './ghostInstallReceipt.js';
@@ -222,6 +223,148 @@ export class GhostManager {
}
}
+ /**
+ * 一次性 legacy backfill 迁移(docs/dev-rules/plugin-security-and-authoring.md 第 5 节
+ * 红线的落地)。#1080 把授权事实从可变安装目录搬到 Host receipt,升级前装的插件没有
+ * receipt —— 若不迁移,它们会一律落到 `legacy-unapproved`、被列停用、要用户逐个重新
+ * 确认(这正是 #1080 被回滚的原因)。这里从旧的三份事实源(`ghost.json` /
+ * `.cindy-trust.json` / `.disabled`)重建等价 receipt,让存量插件升级后**无感可用**。
+ *
+ * 三条不变量:
+ * - **全局一次性**:状态根有迁移 ledger 即视为已迁过,此后缺 receipt 一律 fail closed,
+ * 不再迁。理由见 `GhostLegacyMigrationLedger` 头注释(否则删 receipt 就能骗一次
+ * "从可变安装目录重建授权")。
+ * - **不扩权、不等于新确认**:receipt 权限集 = 当前 `ghost.json` 声明,等价于旧模型
+ * 无条件授权的那一组;此后任何 manifest/权限变化照旧走完整确认(update 流程不变)。
+ * - **只写状态根、绝不动安装目录**:三份旧文件原样保留,因此回滚到旧客户端时它照旧
+ * 从安装目录判定启停,不会错位(§5 兜底第 4 条 回滚余地)。
+ *
+ * 随包种子 id 跳过 —— 它们走 provisioning 的 `approveTrustedBundledInstall`(有权威
+ * 字节可比,是更强的迁移形态)。
+ */
+ async migrateLegacyApprovalsOnce(): Promise<{
+ migrated: string[];
+ skipped: string[];
+ failed: string[];
+ }> {
+ return this.runExclusiveMutation(() => this.migrateLegacyApprovalsUnlocked());
+ }
+
+ private async migrateLegacyApprovalsUnlocked(): Promise<{
+ migrated: string[];
+ skipped: string[];
+ failed: string[];
+ }> {
+ const result = { migrated: [] as string[], skipped: [] as string[], failed: [] as string[] };
+ // 全局一次性门:已迁过就再也不迁(读不动 ledger 同样当作"已迁",宁可少迁不可
+ // 把"从可变安装目录重建授权"再放开一次)。
+ if (this.receiptStore.hasMigrationLedger()) return result;
+
+ const root = this.options.getRootDir();
+ let entries: fs.Dirent[] = [];
+ try {
+ entries = fs.readdirSync(root, { withFileTypes: true });
+ } catch {
+ // 安装根还不存在 = 没装过任何插件(全新用户)。仍写 ledger 落一道门:让
+ // "ledger 存在 ⟺ 迁移已跑过"这个不变量成立,今后新装的插件走正常装入流程。
+ }
+
+ for (const entry of entries) {
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
+ const id = entry.name;
+ if (!isValidGhostId(id)) continue;
+ // 随包种子交给 provisioning,不在迁移范围。
+ if (this.options.isTrustedBundledId?.(id)) {
+ result.skipped.push(id);
+ continue;
+ }
+ // 已经有有效 receipt(迁移前理论上不该出现,防御性跳过,绝不覆盖既有批准)。
+ if (this.receiptStore.read(id).state === 'approved') {
+ result.skipped.push(id);
+ continue;
+ }
+ try {
+ const migrated = await this.backfillLegacyApproval(path.join(root, id), id);
+ (migrated ? result.migrated : result.skipped).push(id);
+ } catch (err) {
+ // 核心授权事实读不出(manifest 不合法、技能目录含链接等)才落到这里:该插件
+ // 保持 legacy-unapproved(list() 本就跳过不合法 manifest),走现有恢复 UI。
+ result.failed.push(id);
+ this.options.log?.warn('legacy ghost approval migration failed; kept fail-closed', {
+ id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ await this.receiptStore.writeMigrationLedger({
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [...result.migrated].sort(),
+ });
+ if (result.migrated.length > 0) this.options.onChanged?.(this.list());
+ return result;
+ }
+
+ /**
+ * 从旧安装目录的三份事实源重建一份等价 receipt。返回是否真的写了 receipt。
+ *
+ * 分级 fail 策略(对齐 §5"读不出核心事实才 fail closed,展示元数据缺失则降级"):
+ * - `ghost.json` 读不出/不合法 → 抛错 → 调用方计入 failed、保持 fail closed;
+ * - `.disabled` 镜像 → 旧模型的启停事实(不存在=启用);
+ * - `.cindy-trust.json` 缺失/损坏 → 保守 `unverified`(展示信号,能力由 slot 授予);
+ * - locale 声明存在但文件损坏 → 抛错 → fail closed。装入流程本就逐个校验声明的
+ * locale、不合格拒装(见 `install` 里 `locale 文件不合格` 分支),所以旧安装天然不含
+ * 坏 locale;迁移时读到坏 locale 只可能是**装入后被损坏**,属 §5 的"自相矛盾即
+ * fail closed",也与 receipt「localeResources 键集必须等于 manifest.locales」的
+ * 不变量一致(跳过坏 locale 会写出被 validateReceipt 拒绝的 receipt);
+ * - `packageSha256` **不算**(它是 audit-only、运行期不消费,见 §7);省掉它让迁移更快、
+ * 更不会因安装目录里的异常条目误伤——真正的运行期判据 `skillContentSha256` 仍逐字节算,
+ * 技能目录含链接等异常会在那里如实 fail closed。
+ */
+ private async backfillLegacyApproval(dir: string, id: string): Promise<boolean> {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(fs.readFileSync(path.join(dir, GHOST_MANIFEST_FILE), 'utf-8'));
+ } catch (err) {
+ throw new Error(`unreadable manifest: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ const validated = validateGhostManifest(raw);
+ if (!validated.ok) throw new Error(`invalid manifest: ${validated.reason}`);
+ if (validated.manifest.id !== id) throw new Error('manifest id != install dir name');
+
+ const enabled = !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE));
+ const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ };
+ const localeResources = this.readApprovedLocaleResources(dir, validated.manifest);
+ const iconDataUrl = this.readInstalledIconDataUrl(dir, validated.manifest) ?? undefined;
+ // skillContentSha256 是运行期判据,必须现算;技能目录异常(链接等)在此如实抛错。
+ const skillContentSha256 = await hashApprovedSkillContent(validated.manifest, dir);
+
+ await this.receiptStore.write(
+ createGhostInstallReceipt({
+ manifest: validated.manifest,
+ localeResources,
+ enabled,
+ trust,
+ skillContentSha256,
+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ }),
+ { skillSourceDir: dir },
+ );
+ this.options.log?.info('legacy ghost approval migrated', {
+ id,
+ enabled,
+ trustLevel: trust.level,
+ origin: 'legacy-migration',
+ });
+ return true;
+ }
+
/** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */
list(): InstalledGhost[] {
const root = this.options.getRootDir();
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 2618dc0ef7..c36e8007b4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -81,6 +81,51 @@ async function makeCindy(
return out;
}
+/**
+ * 造一份**旧布局**安装(#1080 之前的形态):直接把文件写进 rootDir/<id>/,不经
+ * manager.install() —— 因此状态根里**没有** receipt。用于「从旧状态升级」的迁移回归。
+ * 三份旧事实源:ghost.json(必)、.disabled(停用镜像,可选)、.cindy-trust.json(信任镜像,可选)。
+ */
+async function writeLegacyInstall(
+ id: string,
+ manifest: Record<string, unknown>,
+ opts: {
+ disabled?: boolean;
+ trust?: Record<string, unknown> | 'omit';
+ files?: Record<string, string>;
+ } = {},
+): Promise<string> {
+ const dir = path.join(rootDir, id);
+ await fs.promises.mkdir(dir, { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), JSON.stringify(manifest));
+ await fs.promises.writeFile(path.join(dir, 'main.js'), 'console.log("legacy")');
+ for (const [rel, content] of Object.entries(opts.files ?? {})) {
+ const abs = path.join(dir, ...rel.split('/'));
+ await fs.promises.mkdir(path.dirname(abs), { recursive: true });
+ await fs.promises.writeFile(abs, content);
+ }
+ if (opts.disabled) await fs.promises.writeFile(path.join(dir, '.disabled'), '');
+ if (opts.trust !== 'omit') {
+ await fs.promises.writeFile(
+ path.join(dir, '.cindy-trust.json'),
+ JSON.stringify(
+ opts.trust ?? {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ ),
+ );
+ }
+ return dir;
+}
+
+/** 迁移台账路径(默认状态根 = <workDir>/ghosts-install-state)。 */
+function migrationLedgerPath(): string {
+ return path.join(workDir, 'ghosts-install-state', '.legacy-migration.json');
+}
+
async function expectRejection(
result: unknown,
code: string,
@@ -152,6 +197,153 @@ describe('hashApprovedSkillContent · item.dir 路径段校验', () => {
});
});
+describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {
+ /** 带 skill 槽的旧布局清单 + 配套 SKILL.md(frontmatter 与声明逐字一致)。 */
+ const legacySkillManifest = (id = 'skilled'): Record<string, unknown> => ({
+ ...goodManifest(id),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ });
+ const legacySkillFiles = (): Record<string, string> => ({
+ 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
+ });
+
+ it('市场/本地旧安装无感迁移:升级后仍启用、列 approved、写下迁移台账', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ // 迁移前:没有 receipt → 一律 fail closed(这正是 #1080 被回滚的现场)。
+ expect(manager.list()[0]).toMatchObject({ enabled: false, approval: { state: 'legacy-unapproved' } });
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['hello']);
+ // 迁移后:用户什么都没做,插件照旧可用。
+ expect(manager.list()[0]).toMatchObject({
+ enabled: true,
+ approval: { state: 'approved' },
+ });
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ });
+
+ it('旧安装的停用态被保留:.disabled 镜像 → receipt.enabled=false', async () => {
+ await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ await manager.migrateLegacyApprovalsOnce();
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'approved' },
+ });
+ });
+
+ it('信任镜像被保留;缺失时保守降级为 unverified 而不是让迁移失败', async () => {
+ await writeLegacyInstall('trusted', goodManifest('trusted'), {
+ trust: {
+ level: 'verified-publisher',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: false,
+ publisherName: 'Acme',
+ },
+ });
+ await writeLegacyInstall('bare', goodManifest('bare'), { trust: 'omit' });
+ await manager.migrateLegacyApprovalsOnce();
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g]));
+ expect(byId.trusted.trust).toMatchObject({ level: 'verified-publisher', publisherName: 'Acme' });
+ expect(byId.trusted.enabled).toBe(true);
+ // 信任文件缺失不阻断迁移:插件照旧可用,只是展示为 unverified(旧模型读同一文件也如此)。
+ expect(byId.bare.trust).toMatchObject({ level: 'unverified' });
+ expect(byId.bare.enabled).toBe(true);
+ });
+
+ it('skill 槽旧安装迁移后:快照建好、字节指纹钉住、对账认可挂链', async () => {
+ await writeLegacyInstall('skilled', legacySkillManifest(), { files: legacySkillFiles() });
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['skilled']);
+ const ghost = manager.list()[0];
+ expect(ghost).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ expect(ghost.approvedSkillRoot).toBeTruthy();
+ // 迁移出的快照必须能被技能对账认可(字节与 receipt 指纹逐字节对上),否则技能链断。
+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);
+ });
+
+ it('全局一次性:台账落地后,新出现的无 receipt 目录不再被迁移(fail closed)', async () => {
+ await writeLegacyInstall('first', goodManifest('first'));
+ await manager.migrateLegacyApprovalsOnce();
+ expect(manager.list().find((g) => g.manifest.id === 'first')?.approval.state).toBe('approved');
+
+ // 台账已在。此后再冒出一个没有 receipt 的目录(可能是删了 receipt 想骗迁移,或
+ // 真的新拷进来的旧目录)——迁移不再触发,它保持 fail closed。删 receipt 想"从可变
+ // 安装目录重建授权"这条路被这道门堵死。
+ await writeLegacyInstall('second', goodManifest('second'));
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [] });
+ expect(manager.list().find((g) => g.manifest.id === 'second')?.approval.state).toBe(
+ 'legacy-unapproved',
+ );
+ });
+
+ it('迁移绝不改动安装目录三文件(回滚到旧客户端仍按安装目录判定,§5 兜底第 4 条)', async () => {
+ const dir = await writeLegacyInstall('hello', goodManifest(), { disabled: true });
+ const before = {
+ manifest: await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'),
+ disabled: fs.existsSync(path.join(dir, '.disabled')),
+ trust: await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8'),
+ };
+ await manager.migrateLegacyApprovalsOnce();
+ expect(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8')).toBe(before.manifest);
+ expect(fs.existsSync(path.join(dir, '.disabled'))).toBe(before.disabled);
+ expect(await fs.promises.readFile(path.join(dir, '.cindy-trust.json'), 'utf8')).toBe(before.trust);
+ });
+
+ it('manifest 不合法的旧目录不迁移,保持 fail closed,不写出坏 receipt', async () => {
+ const dir = path.join(rootDir, 'broken');
+ await fs.promises.mkdir(dir, { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), '{ not valid json');
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.failed).toEqual(['broken']);
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'broken.json'))).toBe(false);
+ });
+
+ it('随包种子 id 跳过迁移(交给 provisioning 的逐字节对账补批准)', async () => {
+ const seededManager = new GhostManager({
+ getRootDir: () => rootDir,
+ getLocale: () => hostLocale,
+ onChanged,
+ isTrustedBundledId: (id) => id === 'hello',
+ });
+ await writeLegacyInstall('hello', goodManifest());
+ const outcome = await seededManager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [] });
+ // 没有替它写 receipt:provisioning 才是随包插件的批准入口。
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ });
+
+ it('已有 receipt 的安装不被迁移覆盖(迁移只补,不改既有批准)', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ const before = await fs.promises.readFile(
+ path.join(workDir, 'ghosts-install-state', 'hello.json'),
+ 'utf8',
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual([]);
+ expect(await fs.promises.readFile(path.join(workDir, 'ghosts-install-state', 'hello.json'), 'utf8')).toBe(
+ before,
+ );
+ });
+
+ it('声明的 locale 文件损坏 → fail closed(装入天然不含坏 locale,读到即装入后损坏)', async () => {
+ hostLocale = 'en';
+ await writeLegacyInstall(
+ 'hello',
+ { ...goodManifest(), name: 'Base', locales: { en: 'locales/en.json' } },
+ { files: { 'locales/en.json': '{ broken json' } },
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ // 装入流程逐个校验声明的 locale、不合格拒装,所以旧安装不会带坏 locale;迁移时
+ // 读到坏 locale 只能是装入后损坏,属 §5 的"自相矛盾 → fail closed",不写坏 receipt。
+ expect(outcome.failed).toEqual(['hello']);
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);
+ });
+});
+
describe('GhostManager · install', () => {
it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
const manifest = {
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 606abf4779..b8443fa55e 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -73,6 +73,23 @@ export type GhostInstallReceiptReadResult =
| { state: 'legacy-unapproved' }
| { state: 'invalid'; reason: string };
+/**
+ * 一次性 legacy 迁移的落地台账。存在即表示"本机已跑过一轮从旧安装布局 backfill
+ * receipt 的迁移"——此后任何缺失 receipt 都按删除/损坏 fail closed,不再触发迁移。
+ *
+ * 它是迁移的**全局一次性门**(见 `GhostManager.migrateLegacyApprovalsOnce`):没有
+ * 这道门,删掉某个 receipt 就能骗一次"从当前可变安装目录重建授权",而安装目录可被
+ * 同权限进程改写。ledger 门是充分守卫——能删 ledger 的进程本就能直接往状态根写一份
+ * 结构合法的伪造 receipt(§7 已登记"状态根无写保护"缺口),迁移路径严格弱于它。
+ */
+export interface GhostLegacyMigrationLedger {
+ version: 1;
+ /** 迁移完成时刻(ISO)。仅审计,不参与判定。 */
+ migratedAt: string;
+ /** 实际 backfill 出 receipt 的 id 清单,便于事后分辨"用户确认过"与"迁移来的"。 */
+ migratedIds: string[];
+}
+
/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */
export class GhostInstallReceiptStore {
constructor(private readonly getRootDir: () => string) {}
@@ -167,6 +184,42 @@ export class GhostInstallReceiptStore {
return path.join(this.rootDir(), 'skill-snapshots', id, revision);
}
+ /** 迁移台账路径。点开头,不会与任何合法 ghost id 的 `<id>.json` receipt 撞名。 */
+ private migrationLedgerPath(): string {
+ return path.join(this.rootDir(), '.legacy-migration.json');
+ }
+
+ /** 是否已跑过一轮 legacy 迁移(全局一次性门;读不动按"存在"处理,宁可不再迁)。 */
+ hasMigrationLedger(): boolean {
+ try {
+ return fs.lstatSync(this.migrationLedgerPath()).isFile();
+ } catch (error) {
+ // ENOENT = 从未迁过,可以迁;其它错误(权限等)= 状态未知,保守当作"已迁",
+ // 绝不因为读不动 ledger 就把迁移(=从可变安装目录重建授权)再放开一次。
+ return (error as NodeJS.ErrnoException).code !== 'ENOENT';
+ }
+ }
+
+ async writeMigrationLedger(ledger: GhostLegacyMigrationLedger): Promise<void> {
+ const root = this.rootDir();
+ await fs.promises.mkdir(root, { recursive: true });
+ const target = this.migrationLedgerPath();
+ const temp = path.join(
+ root,
+ `.legacy-migration-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,
+ );
+ try {
+ await fs.promises.writeFile(temp, `${JSON.stringify(ledger, null, 2)}\n`, {
+ encoding: 'utf8',
+ flag: 'wx',
+ mode: 0o600,
+ });
+ await fs.promises.rename(temp, target);
+ } finally {
+ await fs.promises.rm(temp, { force: true }).catch(() => undefined);
+ }
+ }
+
private receiptPath(id: string): string {
if (!isValidGhostId(id)) throw new Error('invalid ghost id for receipt path');
return path.join(this.rootDir(), `${id}.json`);
@@ -348,6 +401,25 @@ export class GhostInstallReceiptStore {
}
}
+/**
+ * 迁移专用:读旧安装目录里的 `.cindy-trust.json` 信任镜像。#1080 之前授权事实就散在
+ * 安装目录三文件里,升级迁移要从它们重建等价 receipt。
+ *
+ * 缺失/损坏/非普通文件一律返回 `null` —— trust 只是**展示与来源信号**(能力由 manifest
+ * slot 授予,不由 trust 等级授予),读不出时调用方用保守默认(`unverified`)而不是让整个
+ * 迁移失败:旧模型读的也是同一个文件,缺了同样显示不出 verified,不比旧模型少展示什么。
+ */
+export function readLegacyInstallTrust(dir: string): GhostTrustInfo | null {
+ const file = path.join(dir, '.cindy-trust.json');
+ try {
+ const stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.size > MAX_RECEIPT_BYTES) return null;
+ return validateTrust(JSON.parse(fs.readFileSync(file, 'utf8')));
+ } catch {
+ return null;
+ }
+}
+
export function createGhostInstallReceipt(input: {
manifest: GhostManifest;
localeResources: Record<string, GhostManifestLocaleResource>;
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index d340c669bf..efc169f784 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -714,9 +714,23 @@ function migrateGhostKvOnRename(fromId: string, toId: string): void {
}
}
-/** 单轮对账:播种 → (有变化时)广播 + 首装停靠 + 常驻点火。 */
+/** 单轮对账:一次性 legacy 迁移 → 播种 → (有变化时)广播 + 首装停靠 + 常驻点火。 */
async function reconcileBuiltinGhosts(reason: string): Promise<void> {
const manager = getGhostManager();
+ // 存量插件迁移必须先于播种与授权消费:#1080 之前装的插件没有 receipt,这里从旧安装
+ // 布局 backfill 出等价批准,让它们升级后无感可用(docs §5 红线)。全局一次性 —— 首次
+ // 之后 ledger 存在即瞬时 no-op,所以放在每轮 reconcile 前都安全。它自己取事务锁,因此
+ // 必须在下面 runExclusiveMutation **之外**调用(锁内再取锁会死锁),两次顺序取锁。
+ try {
+ await manager.migrateLegacyApprovalsOnce();
+ } catch (err) {
+ // 迁移整体失败(如状态根不可写)不能挡住播种与后续对账:随包插件仍要能装/更新,
+ // 存量插件保持 fail-closed(列停用、走恢复 UI),下一轮启动再尝试迁移。
+ log.warn('legacy ghost approval migration pass failed', {
+ reason,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
await manager.runExclusiveMutation(() =>
reconcileBuiltinGhostsLocked(reason, manager),
);
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index d9e8388a6c..ab18b17c8e 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -259,16 +259,21 @@
以下缺口在触及相关链路时必须一并修复,或在 PR 中保留明确的正式跟踪,不得静默丢弃:
-- **【未修复|违反第 5 节红线】存量安装没有 receipt backfill。** 现状(2026-08-01 核对
- `ghostInstallReceipt.readApproval` 与 `GhostManager`):receipt 机制上线前装的插件一律
- 落到 `legacy-unapproved`,被列为停用、不许启用、不落技能链,唯一出路是**逐个**完整
- 重新确认;安装目录里的 `.disabled` 镜像也只在重新确认之后才被采用。因此升级到该版本的
- 用户会看到**全部非随包插件同时失效**(随包内置插件由 provisioning 在逐字节对账后走
- `approveTrustedBundledInstall` 自动补批准,不受影响——那条路有权威字节可比,正是本节
- 要求的迁移形态,缺的是把同样的思路覆盖到市场与本地安装)。缺的是第 5 节要求的一次性迁移:从
- `ghost.json` / `.cindy-trust.json` / `.disabled` 重建等价 receipt(只在从未有过 receipt
- 时、权限原样不扩权、来源记日志),以及自动迁移不成时的批量恢复入口。改动装入/批准
- 链路时必须一并补上,不得再往上叠新的必填校验。
+- **【已修复|第 5 节红线迁移】存量安装的 receipt backfill。** receipt 机制上线前装的
+ 插件没有 receipt,`GhostManager.migrateLegacyApprovalsOnce()` 在每轮对账前跑一次(首次
+ 之后凭迁移 ledger 瞬时 no-op),从旧的三份事实源(`ghost.json` / `.cindy-trust.json` /
+ `.disabled`)重建等价 receipt,让市场与本地安装升级后无感可用;随包内置插件仍走
+ provisioning 的 `approveTrustedBundledInstall`(有权威字节可比,是更强的迁移形态),不
+ 重复迁移。三条不变量:**全局一次性**(状态根有 `.legacy-migration.json` ledger 即视为已
+ 迁过,此后缺 receipt 一律 fail closed,不再迁——否则删 receipt 就能骗一次"从可变安装
+ 目录重建授权";该门是充分守卫,因为能删 ledger 的进程本就能直接写伪造 receipt,见下
+ 「批准状态根无写保护」)、**不扩权**(权限集原样取当前 `ghost.json`,等价于旧模型无条件
+ 授权的那一组,此后任何 manifest/权限变化照旧走完整确认)、**只写状态根不动安装目录**
+ (三份旧文件原样保留,回滚到旧客户端时仍按安装目录判定,符合第 5 节兜底第 4 条)。核心
+ 授权事实读不出(manifest 不合法、技能目录含链接、声明的 locale 装入后损坏)才对该插件
+ fail closed、走恢复 UI;trust 镜像缺失降级为 `unverified`、`packageSha256` audit-only
+ 故省略。改动装入/迁移链路时保持这些不变量,尤其不得把迁移改成"每次缺 receipt 就补"
+ (那就是把授权事实重新交给可变安装目录,等于回到 #636)。
- `networkSlot.ts` 的 `as: 'media'` 不能只信任 Content-Type(GLB 常见
`application/octet-stream`),需要安全的 magic-byte/扩展名嗅探。
- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机
diff --git a/package.json b/package.json
index fcef218ae7..2fc1c96004 100644
--- a/package.json
+++ b/package.json
@@ -99,6 +99,7 @@
"benchmark:browser": "node --import tsx scripts/browser-capability-benchmark.mjs",
"benchmark:desktop-workers": "node scripts/desktop-worker-benchmark.mjs",
"dev:embed:search": "node scripts/dev-embed-search.mjs",
+ "demo:legacy-migration": "tsx scripts/dev-legacy-migration-demo.mts",
"build": "node scripts/ensure-deps.mjs && pnpm --filter desktop build",
"release:package": "node scripts/ensure-deps.mjs && node apps/desktop/scripts/package-desktop.mjs",
"check:i18n": "node scripts/check-i18n.mjs",
diff --git a/scripts/dev-legacy-migration-demo.mts b/scripts/dev-legacy-migration-demo.mts
new file mode 100644
index 0000000000..dda19ceb1f
--- /dev/null
+++ b/scripts/dev-legacy-migration-demo.mts
@@ -0,0 +1,188 @@
+/**
+ * dev-legacy-migration-demo — 本地体验「存量插件升级无感迁移」(docs §5 红线)。
+ *
+ * 为什么存在:插件运行授权改由 Host receipt 持有(#636 修复)后,升级前装的插件没有
+ * receipt。本脚本用**真实的 `GhostManager` 生产代码**,在一个临时目录里造出「旧布局
+ * 已装插件」(#1080 之前的形态:ghost.json / .cindy-trust.json / .disabled,没有 receipt),
+ * 跑一次迁移,把迁移前后的 `list()` 打出来,让你亲眼看到:
+ * 迁移前 = 全部 legacy-unapproved、停用(这正是被回滚的故障现场)
+ * 迁移后 = 用户什么都没做,插件照旧 approved、启用态被保留、技能链可挂
+ * 全程在 os.tmpdir 里进行,**不触碰你的真实插件与数据**。
+ *
+ * 运行:
+ * node_modules/.bin/tsx scripts/dev-legacy-migration-demo.mts
+ * (或 pnpm demo:legacy-migration)
+ *
+ * 想在**真实 app** 里眼见为实,见文件末尾打印的「在真实 app 中体验」步骤。
+ */
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { GhostManager } from '../apps/desktop/src/main/cindy-brain/GhostManager.ts';
+
+const GREEN = '\x1b[32m';
+const YELLOW = '\x1b[33m';
+const DIM = '\x1b[2m';
+const BOLD = '\x1b[1m';
+const RESET = '\x1b[0m';
+
+function manifest(id: string, extra: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'do_thing', description: 'demo' }],
+ ...extra,
+ };
+}
+
+/** 造一份 #1080 之前的旧布局安装:只写安装目录三文件,不写任何 receipt。 */
+async function plantLegacyInstall(
+ root: string,
+ id: string,
+ m: Record<string, unknown>,
+ opts: { disabled?: boolean; trust?: Record<string, unknown>; files?: Record<string, string> } = {},
+): Promise<void> {
+ const dir = path.join(root, id);
+ await fs.promises.mkdir(dir, { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), JSON.stringify(m, null, 2));
+ await fs.promises.writeFile(path.join(dir, 'main.js'), 'console.log("legacy demo")');
+ for (const [rel, content] of Object.entries(opts.files ?? {})) {
+ const abs = path.join(dir, ...rel.split('/'));
+ await fs.promises.mkdir(path.dirname(abs), { recursive: true });
+ await fs.promises.writeFile(abs, content);
+ }
+ if (opts.disabled) await fs.promises.writeFile(path.join(dir, '.disabled'), '');
+ await fs.promises.writeFile(
+ path.join(dir, '.cindy-trust.json'),
+ JSON.stringify(
+ opts.trust ?? {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ ),
+ );
+}
+
+function printList(label: string, manager: GhostManager): void {
+ console.log(`\n${BOLD}${label}${RESET}`);
+ for (const g of manager.list()) {
+ const ok = g.approval.state === 'approved' && g.enabled;
+ const color = ok ? GREEN : YELLOW;
+ console.log(
+ ` ${color}${g.manifest.id.padEnd(16)}${RESET} ` +
+ `approval=${g.approval.state.padEnd(18)} ` +
+ `enabled=${String(g.enabled).padEnd(6)} ` +
+ `trust=${g.trust?.level ?? '-'}`,
+ );
+ }
+}
+
+async function main(): Promise<void> {
+ const workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-legacy-migration-demo-'));
+ const installRoot = path.join(workDir, 'cindy-brain');
+ const stateRoot = path.join(workDir, 'ghost-install-state');
+ await fs.promises.mkdir(installRoot, { recursive: true });
+
+ console.log(`${DIM}临时安装根: ${installRoot}${RESET}`);
+ console.log(`${DIM}临时状态根: ${stateRoot}${RESET}`);
+
+ // 三种典型的旧布局安装(市场/本地包场景 —— 随包内置插件走 provisioning,不在此列)。
+ await plantLegacyInstall(installRoot, 'market-plugin', manifest('market-plugin'), {
+ trust: {
+ level: 'verified-publisher',
+ publisherSigned: true,
+ publisherVerified: true,
+ reviewed: false,
+ publisherName: 'Acme',
+ },
+ });
+ await plantLegacyInstall(installRoot, 'user-disabled', manifest('user-disabled'), {
+ disabled: true, // 用户之前手动停用过 —— 迁移必须保留这个决定
+ });
+ await plantLegacyInstall(
+ installRoot,
+ 'skill-plugin',
+ manifest('skill-plugin', {
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ }),
+ { files: { 'skills/demo/SKILL.md': '---\nname: demo\ndescription: Demo skill\n---\n\ndemo\n' } },
+ );
+
+ const manager = new GhostManager({
+ getRootDir: () => installRoot,
+ getStateDir: () => stateRoot,
+ getLocale: () => 'zh-CN',
+ // 生产接线用 isTrustedBundledId 把随包种子挡在迁移之外;demo 里没有随包种子。
+ });
+
+ printList('迁移前(升级刚发生,还没有任何 receipt —— 这就是 #1080 被回滚时用户看到的):', manager);
+ console.log(`${DIM} ↑ 全部 legacy-unapproved + 停用:开关点不动、要用户逐个重新确认。${RESET}`);
+
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ console.log(
+ `\n${BOLD}迁移结果${RESET}: migrated=[${outcome.migrated.join(', ')}] ` +
+ `skipped=[${outcome.skipped.join(', ')}] failed=[${outcome.failed.join(', ')}]`,
+ );
+
+ printList('迁移后(用户什么都没做):', manager);
+ console.log(
+ `${DIM} ↑ market-plugin 恢复启用且保留 verified-publisher;user-disabled 保留停用;` +
+ `skill-plugin 启用且快照已建。${RESET}`,
+ );
+
+ // 技能快照字节指纹校验(对账挂链的前置):迁移出的快照能被认可 = 技能链不会断。
+ const skill = manager.list().find((g) => g.manifest.id === 'skill-plugin');
+ if (skill) {
+ const ok = await manager.verifyApprovedSkillSnapshot(skill);
+ console.log(`\n技能快照校验 verifyApprovedSkillSnapshot(skill-plugin) = ${ok ? GREEN : YELLOW}${ok}${RESET}`);
+ }
+
+ const ledgerPath = path.join(stateRoot, '.legacy-migration.json');
+ console.log(`\n${BOLD}迁移台账${RESET} ${DIM}${ledgerPath}${RESET}`);
+ console.log(fs.readFileSync(ledgerPath, 'utf8').trimEnd());
+
+ // 全局一次性门:台账落地后,再冒出一个没有 receipt 的目录不会被迁移(fail closed)。
+ // 这道门挡住"删掉 receipt 骗一次从可变安装目录重建授权"。
+ await plantLegacyInstall(installRoot, 'planted-after', manifest('planted-after'));
+ const second = await manager.migrateLegacyApprovalsOnce();
+ const planted = manager.list().find((g) => g.manifest.id === 'planted-after');
+ console.log(
+ `\n${BOLD}一次性门验证${RESET}: 台账已在 → 再次迁移 migrated=[${second.migrated.join(', ')}] ` +
+ `(应为空);planted-after 状态 = ${planted?.approval.state} (应为 legacy-unapproved)`,
+ );
+
+ // 回滚余地:迁移只写状态根,安装目录三文件原样保留 —— 回滚到旧客户端仍可用。
+ const marketGhostJson = fs.readFileSync(path.join(installRoot, 'market-plugin', 'ghost.json'), 'utf8');
+ console.log(
+ `\n${BOLD}回滚余地${RESET}: 安装目录 ghost.json 未被迁移改动 = ${
+ marketGhostJson.includes('"market-plugin"') ? `${GREEN}true${RESET}` : `${YELLOW}false${RESET}`
+ } (旧客户端回滚后仍从安装目录判定,不错位)`,
+ );
+
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+
+ console.log(
+ `\n${BOLD}在真实 app 中体验(可选,眼见 UI):${RESET}\n` +
+ ` 1. 用当前构建装一个市场插件或本地 .cindy,确认它可用;\n` +
+ ` 2. 退出 app;\n` +
+ ` 3. 到 owner-scoped 状态根 <userData>/owners/<你的 ownerKey>/ghost-install-state/,\n` +
+ ` 删掉该插件的 <id>.json 与 .legacy-migration.json(模拟"从没有 receipt 的旧版本升上来");\n` +
+ ` (Windows: %APPDATA%\\Cindy\\owners\\... macOS: ~/Library/Application Support/Cindy/owners/...)\n` +
+ ` 4. 重新启动 app —— 插件应当照旧可用,不出现"需要重新确认权限",不用你做任何操作。\n` +
+ ` ${DIM}删 receipt 是安全的:安装目录与你的配置/凭证都不动,下次启动迁移会重建 receipt。${RESET}`,
+ );
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});