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): 修复第 6 轮 review 的 5 项 P0 与 5 项 P1(迁移门/停用失效/市场绑定/嵌套技能/owner 租约)

Yuewei-LLcf2dc9c4ba3e
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index a01c9703cd..2798e2e8bb 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -12,6 +12,7 @@ import {
ghostLocalePathFor,
ghostInstallApprovalToken,
ghostIconMimeType,
+ isOfficialGhostId,
isValidGhostId,
resolveGhostManifestLocale,
validateGhostManifest,
@@ -98,7 +99,15 @@ export type InstallRejection =
| { code: 'not-installed'; reason: string }
| { code: 'command-conflict'; reason: string }
| { code: 'state-changed'; reason: string }
- | { code: 'io'; reason: string };
+ | {
+ code: 'io';
+ reason: string;
+ /**
+ * 更新失败后连旧版本目录都没能滚回原位(Windows 文件锁/AV 等):此时安装目录
+ * 可能是新字节或缺失,调用方**不得**按"旧版本还在"重启运行时。
+ */
+ rollbackFailed?: boolean;
+ };
export type UninstallRejection =
| { code: 'invalid-id'; reason: string }
@@ -161,6 +170,18 @@ export class GhostManager {
return this.receiptStore.rootDir();
}
+ /**
+ * 启停投影:receipt 为主,安装目录 `.disabled` 镜像**只往停用方向覆盖**(读时合并)。
+ *
+ * 为什么在读侧合并而不是只信 receipt:停用必须永远能成功(规则 §3 收敛方向不对称)。
+ * 状态根不可写时 `setEnabled(false)` 仍能写镜像;若 list() 只读 receipt,那次停用会在
+ * 重启后静默复活 —— fail open。镜像只能把启停态往下拉,不能往上翻(重新启用只有
+ * setEnabled(true) 成功写 receipt 一条路),与随包对账的合并规则同向。
+ */
+ private effectiveEnabled(dir: string, receiptEnabled: boolean): boolean {
+ return receiptEnabled && !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE));
+ }
+
/**
* 读批准状态的**唯一入口**:进程内隔离优先于磁盘上的 receipt。
*
@@ -256,17 +277,38 @@ export class GhostManager {
failed: string[];
}> {
const result = { migrated: [] as string[], skipped: [] as string[], failed: [] as string[] };
- // 全局一次性门:已迁过就再也不迁(读不动 ledger 同样当作"已迁",宁可少迁不可
- // 把"从可变安装目录重建授权"再放开一次)。
+ // 一次性门,两道判据缺一不可:
+ // 1) ledger 存在 = 迁过,不再迁;
+ // 2) 状态根已有任何**有效** receipt = 新模型已在本机运转过,此后缺某个 receipt
+ // 只能是删除,同样不迁(补写 ledger 把门关死);损坏/旧 schema 的 receipt 不算
+ // "活动过" —— 它们正是 §5 要求本轮治愈的对象。
+ // 之所以要第 2 道:下面"安装根为空/未诞生时不落 ledger"是为 owner 命名空间的
+ // legacy 恢复流程留门(它会在之后才把旧目录搬进来),没有第 2 道,这个留门会被
+ // "装一个插件→删 receipt"利用成从可变安装目录重建授权(receipt 首写自动落
+ // ledger 把这个窗口进一步压到零,见 receiptStore.write)。
if (this.receiptStore.hasMigrationLedger()) return result;
+ if (this.receiptStore.hasAnyValidReceipt()) {
+ await this.receiptStore.writeMigrationLedger({
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [],
+ });
+ return result;
+ }
const root = this.options.getRootDir();
let entries: fs.Dirent[] = [];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
- } catch {
- // 安装根还不存在 = 没装过任何插件(全新用户)。仍写 ledger 落一道门:让
- // "ledger 存在 ⟺ 迁移已跑过"这个不变量成立,今后新装的插件走正常装入流程。
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
+ // 安装根未诞生:全新用户,或 legacy 恢复流程还没把旧目录搬进来。没有可迁
+ // 对象,也**不写 ledger** —— 门要给随后搬入的旧目录留着(见上第 2 道判据)。
+ return result;
+ }
+ // EACCES/EIO 等真实故障:本轮放弃且不写 ledger,下次启动重试。吞掉错误照写
+ // ledger 会把迁移永久封死在一次环境抖动上。
+ throw err;
}
for (const entry of entries) {
@@ -297,15 +339,71 @@ export class GhostManager {
}
}
- await this.receiptStore.writeMigrationLedger({
- version: 1,
- migratedAt: new Date().toISOString(),
- migratedIds: [...result.migrated].sort(),
- });
+ // 一个 backfill 都没尝试过(空目录/只有随包目录)就不落 ledger —— 留给 legacy
+ // 恢复流程;删 receipt 骗迁移由 hasAnyValidReceipt 判据 + receipt 首写自动落
+ // ledger(见 receiptStore.write)两道一起挡住。
+ if (result.migrated.length > 0 || result.failed.length > 0) {
+ await this.receiptStore.writeMigrationLedger({
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [...result.migrated].sort(),
+ ...(result.failed.length > 0 ? { failedIds: [...result.failed].sort() } : {}),
+ });
+ }
if (result.migrated.length > 0) this.options.onChanged?.(this.list());
return result;
}
+ /**
+ * legacy 恢复流程(owner 命名空间认领旧布局目录)专用的 backfill 旁路。
+ *
+ * 为什么允许绕过一次性 ledger 门:`ids` 来自恢复流程**刚从旧布局根搬进安装根**的
+ * 目录 —— 这个来源本身就是旧世界的授权事实(与首轮迁移同一信任级),不是可变安装
+ * 目录里凭空冒出来的目录。调用方只传本次恢复实际搬动/新增的 id;逐 id 仍然只在
+ * 没有有效 receipt 时 backfill,随包 id 照旧交给 provisioning。结果并进 ledger,
+ * 事后可分辨来源。
+ */
+ async backfillRecoveredLegacyGhosts(
+ ids: readonly string[],
+ ): 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;
+ try {
+ if (await this.backfillLegacyApproval(path.join(root, id), id)) {
+ out.migrated.push(id);
+ }
+ } catch (err) {
+ out.failed.push(id);
+ this.options.log?.warn('recovered legacy ghost backfill failed; kept fail-closed', {
+ id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ if (out.migrated.length > 0 || out.failed.length > 0) {
+ const prev = this.receiptStore.readMigrationLedger();
+ 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(),
+ ...(failedIds.length > 0 ? { failedIds } : {}),
+ });
+ }
+ if (out.migrated.length > 0) this.options.onChanged?.(this.list());
+ return out;
+ });
+ }
+
/**
* 从旧安装目录的三份事实源重建一份等价 receipt。返回是否真的写了 receipt。
*
@@ -384,7 +482,13 @@ export class GhostManager {
inspectInstalledReapproval(
id: string,
):
- | { manifest: GhostManifest; trust: GhostTrustInfo; manifestSha256: string }
+ | {
+ manifest: GhostManifest;
+ trust: GhostTrustInfo;
+ manifestSha256: string;
+ /** `.disabled` 镜像的读数:确认卡"立即开启"勾选的默认值,不重置用户停用偏好。 */
+ previouslyEnabled: boolean;
+ }
| { rejection: InstallRejection } {
if (!isValidGhostId(id) || this.options.isTrustedBundledId?.(id)) {
return { rejection: { code: 'file-invalid', reason: '该插件不支持从安装目录重新确认' } };
@@ -420,6 +524,19 @@ export class GhostManager {
if (validated.manifest.id !== id) {
return { rejection: { code: 'file-invalid', reason: '清单 id 与安装目录不一致' } };
}
+ // tokenBroker 门控与装入侧同一条规则(XDT 授权 broker 仅第一方官方插件可用,
+ // 不区分 dev/packaged):走已装目录重新确认的都不是随包插件,声明即拒。
+ if (
+ !isOfficialGhostId(id) &&
+ (validated.manifest.network?.secrets ?? []).some((s) => s.oauth?.tokenBroker !== undefined)
+ ) {
+ return {
+ rejection: {
+ code: 'file-invalid',
+ reason: `id "${id}" 声明了 oauth.tokenBroker——XDT 授权 broker 仅第一方官方插件可用`,
+ },
+ };
+ }
const trust: GhostTrustInfo = readLegacyInstallTrust(dir) ?? {
level: 'unverified',
publisherSigned: false,
@@ -430,6 +547,7 @@ export class GhostManager {
manifest: validated.manifest,
trust,
manifestSha256: crypto.createHash('sha256').update(rawBytes).digest('hex'),
+ previouslyEnabled: !fs.existsSync(path.join(dir, DISABLED_MARKER_FILE)),
};
}
@@ -468,6 +586,24 @@ export class GhostManager {
rejection: { code: 'state-changed', reason: '插件清单在确认后发生了变化,请重新确认' },
};
}
+ // 指令查重与装入/更新同一条规则(豁免自己):重新确认不是给撞名指令开的后门。
+ if (inspected.manifest.command !== undefined) {
+ const commandFold = inspected.manifest.command.toLowerCase();
+ const holder = this.list().find(
+ (g) =>
+ g.manifest.id !== id &&
+ g.manifest.command !== undefined &&
+ g.manifest.command.toLowerCase() === commandFold,
+ );
+ if (holder) {
+ return {
+ rejection: {
+ code: 'command-conflict',
+ reason: `指令 /${inspected.manifest.command} 已被已装意识「${holder.manifest.name}」(${holder.manifest.id})占用`,
+ },
+ };
+ }
+ }
const dir = path.join(this.options.getRootDir(), id);
try {
const localeResources = this.readApprovedLocaleResources(dir, inspected.manifest);
@@ -536,7 +672,7 @@ export class GhostManager {
result.push({
manifest: localizedManifest,
dir,
- enabled: receipt.enabled,
+ enabled: this.effectiveEnabled(dir, receipt.enabled),
approval: { state: 'approved', revision: receipt.revision },
trust: receipt.trust,
...(receipt.manifest.skill?.items.length
@@ -711,11 +847,20 @@ export class GhostManager {
);
}
} catch (err) {
- // `.disabled` 是旧版本兼容镜像;receipt 写失败时尽力把镜像回滚,
- // 避免降级运行旧客户端时看到与批准状态相反的启用态。
- if (previousEnabled) {
- await fs.promises.rm(marker, { force: true }).catch(() => undefined);
- } else {
+ if (!enabled) {
+ // 停用必须永远能成功(§3 收敛方向不对称):receipt 写失败时镜像已就位,
+ // list() 的读时合并会把启停态压成停用(重启后依然,镜像在盘上),旧客户端
+ // 也按镜像判 —— 停用已经生效,如实返回 ok,receipt 留待下次成功写入收敛。
+ this.options.log?.warn('ghost disable persisted via mirror only; receipt write failed', {
+ id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ this.options.onChanged?.(this.list());
+ return { ok: true };
+ }
+ // 启用方向 fail closed:receipt 没写成就不算启用,把镜像回滚回停用态,
+ // 避免"receipt 说停用、镜像却被删了"让旧客户端看到相反的启用态。
+ if (!previousEnabled) {
await fs.promises.writeFile(marker, '').catch(() => undefined);
}
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
@@ -1253,7 +1398,9 @@ export class GhostManager {
// 采用原 `.disabled` 镜像;损坏 receipt 一律保持停用。
const enabled =
approvalResult.state === 'approved'
- ? approvalResult.receipt.enabled
+ // 读时合并后的有效值:receipt 可能因状态根短暂不可写而停在陈旧的 enabled=true,
+ // 用户的停用镜像不能被一次更新静默冲掉。
+ ? this.effectiveEnabled(finalDir, approvalResult.receipt.enabled)
: approvalResult.state === 'legacy-unapproved'
? !fs.existsSync(path.join(finalDir, DISABLED_MARKER_FILE))
: false;
@@ -1306,9 +1453,23 @@ export class GhostManager {
try {
await fs.promises.rename(stagingDir, finalDir);
} catch (err) {
- await fs.promises.rename(backupDir, finalDir).catch(() => {});
+ 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,
+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
+ });
+ });
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),
+ ...(rolledBack ? {} : { rollbackFailed: true }),
+ },
+ };
}
// 与 install 同理:技能字节指纹从这次换入的内容目录现算。
let receipt: GhostInstallReceipt;
@@ -1325,9 +1486,23 @@ export class GhostManager {
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
this.untrustedApprovals.delete(manifest.id);
} catch (err) {
+ let rolledBack = true;
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
- await fs.promises.rename(backupDir, finalDir).catch(() => undefined);
- return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
+ 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,
+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
+ });
+ });
+ return {
+ rejection: {
+ code: 'io',
+ reason: err instanceof Error ? err.message : String(err),
+ ...(rolledBack ? {} : { rollbackFailed: true }),
+ },
+ };
}
await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => {});
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 491cde2e6c..48ad96c941 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -444,6 +444,217 @@ describe('GhostManager · 从已装目录重新确认(本地包第三条恢复
});
});
+describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {
+ it('P0-3:停用在 receipt 写失败时仍然生效,且跨实例(重启)持久', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ expect(manager.list()[0].enabled).toBe(true);
+
+ // 状态根不可写(AV/权限/磁盘故障):receipt 的 rename 提交失败。
+ const realRename = fs.promises.rename;
+ const renameSpy = vi
+ .spyOn(fs.promises, 'rename')
+ .mockImplementation(async (from, to) => {
+ if (String(to).includes('ghosts-install-state')) {
+ throw Object.assign(new Error('EACCES: state root locked'), { code: 'EACCES' });
+ }
+ return realRename(from as never, to as never);
+ });
+ try {
+ // 停用必须永远能成功:镜像已落盘,如实返回 ok,而不是 io + 回滚镜像(fail open)。
+ expect(await manager.setEnabled('hello', false)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(false);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ // "重启"(新实例,内存态清零):镜像在盘上,停用不复活。
+ const restarted = new GhostManager({ getRootDir: () => rootDir, getLocale: () => hostLocale });
+ expect(restarted.list()[0].enabled).toBe(false);
+ // 启用方向照旧要求 receipt 写成功(此时状态根已恢复可写)。
+ expect(await manager.setEnabled('hello', true)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(true);
+ });
+
+ it('P0-5:嵌套 skill dir(祖先包含子项)装入/快照/校验全通,不撞 COPYFILE_EXCL', async () => {
+ const nested = {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [
+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },
+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },
+ ],
+ },
+ };
+ const files = {
+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',
+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',
+ };
+ const result = await manager.install(await makeCindy('nested.cindy', nested, files));
+ if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));
+ const ghost = manager.list()[0];
+ expect(ghost.approval.state).toBe('approved');
+ // 两个 item 的字节指纹都能对上(嵌套项的根就在祖先拷出的快照树里)。
+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(true);
+ });
+
+ it('P0-5:嵌套 skill dir 的旧安装迁移同样成功(存量兼容红线)', async () => {
+ await writeLegacyInstall(
+ 'skilled',
+ {
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: {
+ items: [
+ { dir: 'skills/foo/bar', name: 'bar', description: 'Bar skill' },
+ { dir: 'skills/foo', name: 'foo', description: 'Foo skill' },
+ ],
+ },
+ },
+ {
+ files: {
+ 'skills/foo/SKILL.md': '---\nname: foo\ndescription: Foo skill\n---\n\nfoo\n',
+ 'skills/foo/bar/SKILL.md': '---\nname: bar\ndescription: Bar skill\n---\n\nbar\n',
+ },
+ },
+ );
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['skilled']);
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ });
+
+ it('P0-2:安装根为空/未诞生时不落台账,legacy 恢复流程随后搬入仍可迁移', async () => {
+ // 首轮:根目录还不存在(owner 命名空间刚建立,旧目录尚未被恢复流程搬入)。
+ expect(await manager.migrateLegacyApprovalsOnce()).toEqual({
+ migrated: [],
+ skipped: [],
+ failed: [],
+ });
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+ // 恢复流程把旧布局目录搬进来 → 门还开着,照常迁移。
+ await writeLegacyInstall('hello', goodManifest());
+ const second = await manager.migrateLegacyApprovalsOnce();
+ expect(second.migrated).toEqual(['hello']);
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ });
+
+ it('P0-2:首个 receipt 写入即自动落台账 —— "装插件→删 receipt"骗不到迁移', async () => {
+ await manager.install(await makeCindy('a.cindy', goodManifest()));
+ // 新模型首次活动(装入写 receipt)时台账已经落了,不等下一轮 reconcile。
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ // 攻击:改写安装目录 manifest 扩权,再删掉 receipt,指望迁移按新 manifest 重铸批准。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'hello', 'ghost.json'),
+ JSON.stringify({
+ ...goodManifest(),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 's', name: 's', description: 's' }] },
+ }),
+ );
+ await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [] });
+ expect(manager.list()[0].approval.state).toBe('legacy-unapproved');
+ });
+
+ it('P0-2:安装根读失败(EACCES 类)本轮放弃且不落台账,不把迁移永久封死', async () => {
+ await writeLegacyInstall('hello', goodManifest());
+ const realReaddir = fs.readdirSync;
+ const spy = vi.spyOn(fs, 'readdirSync').mockImplementation(((dir: never, opts: never) => {
+ if (String(dir) === rootDir) {
+ throw Object.assign(new Error('EACCES: install root locked'), { code: 'EACCES' });
+ }
+ return realReaddir(dir, opts);
+ }) as never);
+ try {
+ await expect(manager.migrateLegacyApprovalsOnce()).rejects.toThrow(/EACCES/);
+ } finally {
+ spy.mockRestore();
+ }
+ expect(fs.existsSync(migrationLedgerPath())).toBe(false);
+ // 环境恢复后下一轮照常迁移。
+ const outcome = await manager.migrateLegacyApprovalsOnce();
+ expect(outcome.migrated).toEqual(['hello']);
+ });
+
+ it('P0-2:恢复旁路只补给定 id,台账门对其余目录照常生效', async () => {
+ // 台账已落(首轮迁移空跑一个插件)。
+ await writeLegacyInstall('first', goodManifest('first'));
+ await manager.migrateLegacyApprovalsOnce();
+ expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ // 恢复流程搬入两个目录,但只把 recovered 声明为其中一个。
+ await writeLegacyInstall('recovered', goodManifest('recovered'));
+ await writeLegacyInstall('planted', goodManifest('planted'));
+ const out = await manager.backfillRecoveredLegacyGhosts(['recovered']);
+ expect(out.migrated).toEqual(['recovered']);
+ const byId = Object.fromEntries(manager.list().map((g) => [g.manifest.id, g.approval.state]));
+ expect(byId.recovered).toBe('approved');
+ expect(byId.planted).toBe('legacy-unapproved');
+ });
+
+ 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');
+ if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));
+ const result = await manager.reapproveInstalled('clasher', {
+ enable: true,
+ expectedManifestSha256: inspected.manifestSha256,
+ expectedInstalledApproval: 'legacy-unapproved',
+ });
+ expect('rejection' in result && result.rejection.code).toBe('command-conflict');
+ });
+
+ it('P1-6:声明 tokenBroker 的目录拒走已装目录重新确认', async () => {
+ await writeLegacyInstall('brokered', {
+ ...goodManifest('brokered'),
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: 'token',
+ source: 'oauth',
+ oauth: { tokenBroker: 'github' },
+ },
+ ],
+ },
+ });
+ const inspected = 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-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);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
+
describe('GhostManager · install', () => {
it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
const manifest = {
@@ -858,9 +1069,16 @@ describe('GhostManager · Host approval receipt', () => {
const after = manager.list()[0];
expect(after.manifest).toEqual(before.manifest);
- expect(after.enabled).toBe(true);
+ // 启停是**非对称**的例外:`.disabled` 镜像允许把启停态往下拉(停用必须永远能
+ // 成功,状态根不可写时镜像是唯一落点),但 manifest/trust/批准态不受安装目录
+ // 影响,镜像也不能把插件往"启用"方向翻。
+ expect(after.enabled).toBe(false);
expect(after.trust).toEqual(before.trust);
expect(after.approval.state).toBe('approved');
+
+ // 移除镜像 → 回到 receipt 的授权事实(enabled=true 是用户确认装入时的决定)。
+ await fs.promises.rm(path.join(rootDir, 'hello', '.disabled'));
+ expect(manager.list()[0].enabled).toBe(true);
});
it('fails legacy and corrupt receipts closed until a fully reviewed update replaces them', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 7ab6665ea7..2f35877a4c 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -88,6 +88,11 @@ export interface GhostLegacyMigrationLedger {
migratedAt: string;
/** 实际 backfill 出 receipt 的 id 清单,便于事后分辨"用户确认过"与"迁移来的"。 */
migratedIds: string[];
+ /**
+ * 迁移读不出核心事实而 fail closed 的 id(坏 manifest / 技能目录含链接等)。
+ * 记进台账供支持排查与 UI 提示;这些 id 走每插件的重新确认恢复入口。
+ */
+ failedIds?: string[];
}
/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */
@@ -166,6 +171,20 @@ export class GhostInstallReceiptStore {
} finally {
await fs.promises.rm(temp, { force: true }).catch(() => undefined);
}
+ // 首次写 receipt 即落迁移台账,把一次性门在"新模型开始活动"那一刻关死。
+ // 不落的话有一个窗口:新装 receipt 后、下一轮 reconcile 前,删掉唯一的 receipt
+ // 会让 hasAnyReceipt 判据也失效(ledger 尚未写),"改 manifest → 删 receipt →
+ // 骗 backfill"就能凭空铸出扩权批准。台账写失败不阻断本次批准(状态根刚写成功,
+ // 失败面极窄),下一轮迁移检查的 hasAnyReceipt 判据会兜住并补写。
+ if (!this.hasMigrationLedger()) {
+ await this
+ .writeMigrationLedger({
+ version: 1,
+ migratedAt: new Date().toISOString(),
+ migratedIds: [],
+ })
+ .catch(() => undefined);
+ }
await this.pruneStaleSkillSnapshots(receipt);
}
@@ -189,6 +208,44 @@ export class GhostInstallReceiptStore {
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;
+ return raw && raw.version === 1 && Array.isArray(raw.migratedIds) ? raw : null;
+ } catch {
+ return null;
+ }
+ }
+
/** 是否已跑过一轮 legacy 迁移(全局一次性门;读不动按"存在"处理,宁可不再迁)。 */
hasMigrationLedger(): boolean {
try {
@@ -267,7 +324,21 @@ export class GhostInstallReceiptStore {
// 改写,校验和复制各读一次就有一个可换字节的窗口,复制出来的快照可能不是被
// 校验过的那一份。因此**先复制到 temp,再对 temp 里(即将成为快照的)那份字节
// 做全部权威校验**,校验通过才 rename 就位。
- for (const item of items) {
+ // 清单允许嵌套的 skill dir(如 skills/foo 与 skills/foo/bar —— 校验只拒重复,
+ // 不拒前缀嵌套)。祖先目录的整树复制已经带上了嵌套项的字节,再按嵌套项复制一次
+ // 会撞上 COPYFILE_EXCL 直接失败 —— 那会让一份合法清单在装入/更新/迁移/重新确认
+ // 四条路上全军覆没(§5 红线)。按深度排序、祖先先复制,已覆盖的嵌套项跳过复制;
+ // 指纹校验仍逐 item 进行(嵌套项的根就在祖先拷出的树里)。大小写折叠比较,
+ // 与清单查重同口径。
+ const copiedRoots: string[] = [];
+ const itemsByDepth = [...items].sort(
+ (a, b) => a.dir.split('/').length - b.dir.split('/').length,
+ );
+ for (const item of itemsByDepth) {
+ const dirFold = item.dir.toLowerCase();
+ if (copiedRoots.some((root) => dirFold === root || dirFold.startsWith(`${root}/`))) {
+ continue;
+ }
// 与算指纹同一个解析入口:逐段确认真目录,挡住"中间段被换成链接"这条从技能
// 目录之外取字节的路子。两侧必须共用,否则一侧穿透、一侧不穿透,复制的和
// 算指纹的就不是同一组字节。
@@ -290,6 +361,7 @@ export class GhostInstallReceiptStore {
);
}
await copyRegularDirectory(source, path.join(temp, ...item.dir.split('/')));
+ copiedRoots.push(dirFold);
}
// 权威校验一律针对 temp:此刻这些字节已经脱离可变安装目录,复制期间被换过也
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index bb669c1c84..684a10806a 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -17,6 +17,7 @@ import {
ghostWebviewEntryPaths,
isCindyAccountGhostId,
isOfficialGhostId,
+ ghostPermissionItems,
isValidGhostId,
layoutWithGhostPanel,
type GhostHostNoticeKey,
@@ -513,6 +514,25 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
getGhostNodeRuntimeBroker().stop(ghost.manifest.id);
}
}
+ // 恢复搬进来的旧布局目录补 backfill:首轮迁移可能早已跑过并落了一次性 ledger
+ // (当时安装根还是空的),不补的话这批旧插件会全部卡在 legacy-unapproved,违反
+ // §5 升级无感红线。旁路只作用于本次恢复实际搬动/新增的 id(信任级与首轮迁移
+ // 等同:来源是恢复流程刚认领的旧世界布局,不是安装根里凭空冒出的目录)。
+ const recoveredLegacyIds = [
+ ...movedGhostIds,
+ ...restoredBeforeReconcile
+ .filter((ghost) => !existingGhostDirs.has(ghost.manifest.id))
+ .map((ghost) => ghost.manifest.id),
+ ];
+ if (recoveredLegacyIds.length > 0) {
+ await getGhostManager()
+ .backfillRecoveredLegacyGhosts(recoveredLegacyIds)
+ .catch((err) =>
+ log.warn('recovered legacy ghost backfill pass failed', {
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
+ }
const builtinReconcileSucceeded =
result.deferredReason !== 'concurrent-live-instances' &&
await scheduleBuiltinReconcile('legacy-recovery');
@@ -728,24 +748,41 @@ 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 **之外**调用(锁内再取锁会死锁),两次顺序取锁。
+ // 整轮对账(迁移 backfill + 播种换目录 + 批准 receipt 写入)都是 owner 绑定的
+ // 文件系统写路径,但 GhostManager/ReceiptStore 的根目录是**每次调用现解析**的:
+ // 异步 hash/copy 中途账号切换落定,后半段写入就会漏进新 owner 的状态根(拿 A 的
+ // 安装目录字节给 B 的同 id 插件铸批准)。与市场装入同一套约束:开工前捕获 owner、
+ // 全程持 mutation 租约(账号 teardown 会等租约),边界期一律整轮跳过 —— 对账是
+ // 幂等的,下一次触发(startup/auth-change)会补上。
+ let releaseMutation: () => void;
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),
- });
+ releaseMutation = beginGhostMutation(captureGhostMutationOwner());
+ } catch {
+ log.info('builtin ghost reconcile skipped: app session boundary', { reason });
+ return;
+ }
+ try {
+ 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),
+ );
+ } finally {
+ releaseMutation();
}
- await manager.runExclusiveMutation(() =>
- reconcileBuiltinGhostsLocked(reason, manager),
- );
}
async function reconcileBuiltinGhostsLocked(
@@ -2906,6 +2943,12 @@ export async function installOrUpdateMarketGhostPackage(
ghostId: string;
version: string;
expectedInstalledApproval?: string;
+ /**
+ * 用户在确认卡上审阅过的市场清单(服务端 release.manifest)。下载包的清单必须与
+ * 它在**权限投影与指令**上逐项一致 —— 权限 diff 是拿它算的,不绑定的话服务端记录
+ * 与包内 ghost.json 不一致时,用户看到 A 权限、批准并运行的却是 B 权限。
+ */
+ expectedManifest?: GhostManifest;
},
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
@@ -2925,6 +2968,26 @@ export async function installOrUpdateMarketGhostPackage(
}
requireGhostAvailableForActiveSession(expected.ghostId);
rejectUnauthorizedTokenBroker(inspected.manifest);
+ if (expected.expectedManifest) {
+ // 权限投影 + 指令逐项比对,而不是整卡 deep-equal:服务端清单允许存在展示性
+ // 差异(字段顺序/补充元数据),但用户批准的权限集与指令名必须就是包里的那份。
+ const wanted = ghostPermissionItems(expected.expectedManifest)
+ .map((item) => item.key)
+ .sort();
+ const got = ghostPermissionItems(inspected.manifest)
+ .map((item) => item.key)
+ .sort();
+ const sameProjection =
+ wanted.length === got.length &&
+ wanted.every((key, index) => key === got[index]) &&
+ (expected.expectedManifest.command ?? null) === (inspected.manifest.command ?? null);
+ if (!sameProjection) {
+ throwIpcError(
+ 'GHOST_FILE_INVALID',
+ '下载包的权限声明与确认时审阅的市场清单不一致,已中止安装',
+ );
+ }
+ }
const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
// Node 高风险条目由 renderer 装入确认卡权限清单如实展示;
@@ -2939,7 +3002,12 @@ export async function installOrUpdateMarketGhostPackage(
// 校验下载),且确认框如实展示权限清单,确认安装即授权运行;本地 .cindy
// 文件装入的初始启用态仍由确认框勾选决定(勾选默认开启,main 侧
// installAndDock 缺省不启用,授权判断始终来自 UI 显式值)。
- return installAndDock(manager, cindyFilePath, { enable: true });
+ // sha 绑定与本地入口同形:inspect 与真正装入各读一次文件,不绑就有一个
+ // temp 文件可被换字节的窗口。
+ return installAndDock(manager, cindyFilePath, {
+ enable: true,
+ expectedPackageSha256: inspected.packageSha256,
+ });
}
const runtime = getGhostRuntime();
@@ -2956,6 +3024,7 @@ export async function installOrUpdateMarketGhostPackage(
);
}
result = await manager.update(cindyFilePath, {
+ expectedPackageSha256: inspected.packageSha256,
expectedInstalledApproval: expected.expectedInstalledApproval,
});
} catch (error) {
@@ -2963,7 +3032,11 @@ export async function installOrUpdateMarketGhostPackage(
throw error;
}
if ('rejection' in result) {
- spawnIfResident(installed);
+ // 回滚失败 = 安装目录可能已是新字节或缺失,"旧版本还在"不成立,不得按旧
+ // InstalledGhost 重启运行时(P1:那会拿旧批准跑未知字节)。
+ if (!(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {
+ spawnIfResident(installed);
+ }
throwInstallError(result.rejection);
}
runtime.resetFuse(expected.ghostId);
@@ -4064,7 +4137,13 @@ export function registerGhostIpc(): void {
throw err;
}
if ('rejection' in result) {
- if (previousGhost) spawnIfResident(previousGhost);
+ // 回滚失败时安装目录状态未知(可能是新字节/缺失),不按"旧版本还在"重启。
+ if (
+ previousGhost &&
+ !(result.rejection.code === 'io' && result.rejection.rollbackFailed)
+ ) {
+ spawnIfResident(previousGhost);
+ }
throwInstallError(result.rejection);
}
runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账
@@ -4110,6 +4189,8 @@ export function registerGhostIpc(): void {
if (typeof id !== 'string' || id.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');
}
+ requireGhostAvailableForActiveSession(id);
+ rejectReservedGhostId(id);
const result = manager.inspectInstalledReapproval(id);
if ('rejection' in result) throwInstallError(result.rejection);
return result;
@@ -4123,6 +4204,10 @@ export function registerGhostIpc(): void {
if (typeof id !== 'string' || id.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');
}
+ requireGhostAvailableForActiveSession(id);
+ // 与本地装入同一道门:官方保留前缀不走用户通道(真随包 id 已被 manager 的
+ // 种子清单检查拒掉,这里拦的是冒充官方前缀的目录)。
+ rejectReservedGhostId(id);
const options = opts as
| { enable?: unknown; expectedManifestSha256?: unknown; expectedInstalledApproval?: unknown }
| undefined;
@@ -4138,11 +4223,19 @@ export function registerGhostIpc(): void {
if (!isGhostInstallApprovalToken(options.expectedInstalledApproval)) {
throwIpcError('INVALID_PARAMS', 'expectedInstalledApproval must come from ghosts:list');
}
- const result = await manager.reapproveInstalled(id, {
- enable: options.enable,
- expectedManifestSha256: options.expectedManifestSha256,
- expectedInstalledApproval: options.expectedInstalledApproval,
- });
+ // 开 receipt 是 owner 绑定的状态根写路径:确认卡停留期间账号可能已切换,
+ // 与装入/更新同一套租约与边界拒绝(beginGhostMutation 在边界期直接抛)。
+ const releaseMutation = beginGhostMutation(captureGhostMutationOwner());
+ let result: Awaited<ReturnType<typeof manager.reapproveInstalled>>;
+ try {
+ result = await manager.reapproveInstalled(id, {
+ enable: options.enable,
+ expectedManifestSha256: options.expectedManifestSha256,
+ expectedInstalledApproval: options.expectedInstalledApproval,
+ });
+ } finally {
+ releaseMutation();
+ }
if ('rejection' in result) throwInstallError(result.rejection);
// 与装入/更新同款收尾:面板停靠(已有位置则 no-op)+ 常驻点火。
const store = getLayoutStore();
@@ -4300,6 +4393,10 @@ export function registerGhostIpc(): void {
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);
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index a9a5171108..47359606e0 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -388,6 +388,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: 'cindy-test',
version: '1.0.0',
+ expectedManifest: expect.objectContaining({ id: 'cindy-test' }),
},
);
expect(snapshot.items[0]).toMatchObject({
@@ -418,6 +419,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: 'cindy-test',
version: '1.0.0',
+ expectedManifest: expect.objectContaining({ id: 'cindy-test' }),
},
);
// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。
@@ -449,6 +451,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
{
ghostId: item.ghostId,
version: item.currentRelease.version,
+ // 权限绑定:用户确认的服务端清单必须随包传给装入侧比对(P0:服务端记录与
+ // 包内 ghost.json 不一致时,不能让"看到 A 权限、批准 B 权限"发生)。
+ expectedManifest: expect.objectContaining({ id: item.ghostId }),
},
);
expect(snapshot.items[0]).toMatchObject({
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index adb3f1aeda..db99e458c3 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -446,6 +446,10 @@ export class PluginMarketService {
const ghost = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: plugin.ghostId,
version: plugin.currentRelease.version,
+ // 用户在确认卡上审阅的权限 diff 是拿服务端 release.manifest 算的;把它一并
+ // 传下去,由装入侧比对下载包清单的权限投影与指令 —— 服务端记录与包内
+ // ghost.json 不一致时中止,不让"看到 A 权限、批准 B 权限"发生。
+ expectedManifest: compatible.manifest,
...(options.expectedInstalledApproval
? { expectedInstalledApproval: options.expectedInstalledApproval }
: {}),
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b2695461fa..50813517fc 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;
+ previouslyEnabled: boolean;
}> => ipcRenderer.invoke('ghosts:reapprove-inspect', id),
/** 确认卡点过同意后开 receipt;sha 绑定确认卡展示时的清单字节。 */
reapproveInstalled: (
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index 86d5f28407..77bcf9338c 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -247,11 +247,13 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
let manifest: GhostManifest;
let trust: GhostTrustInfo;
let manifestSha256: string;
+ let previouslyEnabled: boolean;
try {
const inspected = await window.electronAPI.ghosts.reapproveInspect(ghostId);
manifest = inspected.manifest;
trust = inspected.trust;
manifestSha256 = inspected.manifestSha256;
+ previouslyEnabled = inspected.previouslyEnabled;
} catch (err) {
// 安装目录读不出清单 = 只剩"重新选包"一条路;如实降级,不吞掉恢复机会。
installFlowLog.warn('reapprove-inspect failed; falling back to file picker', {
@@ -282,7 +284,9 @@ export async function reapproveInstalledGhost(ghostId: string, deps: InstallFlow
confirmText: t('settings.ghosts.reapproveConfirm.confirm'),
cancelText: t('settings.ghosts.installConfirm.cancel'),
checkboxLabel: t('settings.ghosts.installConfirm.enableNow'),
- checkboxDefaultChecked: true,
+ // 默认值取用户升级前的启停偏好(.disabled 镜像):恢复权限 ≠ 替用户把停用的
+ // 插件重新点亮。
+ checkboxDefaultChecked: previouslyEnabled,
});
if (!ok) return;
try {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index e2e722d3c3..90ae37ea0e 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;
+ /** 升级前的启停偏好(.disabled 镜像读数):确认卡勾选默认值。 */
+ previouslyEnabled: boolean;
}>;
/** 第三条恢复路径第二步:用户点过确认卡后开 receipt。 */
reapproveInstalled: (
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 1d9bbe7f06..14d9d80716 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -67,7 +67,11 @@
一份 receipt(`ghostInstallReceipt.ts`),落在**安装根之外**的 owner-scoped 状态根里,
钉住这次批准过的 manifest、trust、启停态和一个随机 `revision`;`GhostManager.list()`
只从 receipt 取这些字段,安装目录里的 `ghost.json` / `.cindy-trust.json` / `.disabled`
- 退化为旧版本兼容镜像。理由是可变安装目录曾经就是授权事实本身:就地改写
+ 退化为旧版本兼容镜像。**唯一的非对称例外是启停态**:`.disabled` 镜像在读取时只往
+ 停用方向合并(`enabled = receipt.enabled && !镜像存在`)——停用必须永远能成功,状态根
+ 不可写时镜像是 `setEnabled(false)` 唯一还能落笔的地方,只读 receipt 会让那次停用在
+ 重启后静默复活;镜像**不能**把插件往启用方向翻,重新启用只有 `setEnabled(true)` 成功
+ 写 receipt 一条路。理由是可变安装目录曾经就是授权事实本身:就地改写
`ghost.json` 能让权限 diff 显示"无新增",未确认的 slot 因此拿到运行授权。
- 没有 receipt(旧安装)或 receipt 损坏 = **不构成运行授权**:一律按停用列出、
不许启用、不参与技能落链。但"不构成运行授权"只是**当下状态**,不等于"该由用户
@@ -283,8 +287,20 @@
(那就是把授权事实重新交给可变安装目录,等于回到 #636)。迁移之后批准再丢失的恢复
路径:市场包走市场重装确认;本地包走「从已装目录重新确认」(`ghosts:reapprove-inspect`
→ 确认卡全量权限清单 → `ghosts:reapprove-installed`,清单字节以 manifestSha256 绑定
- 确认间隙,trust 走与迁移同一个封顶读取器)—— 不要求用户重新提供原始 `.cindy`,不存在
- 不可恢复状态;随包插件不走人工确认,由启动对账自动补(UI 提示「重启应用即恢复」)。
+ 确认间隙,trust 走与迁移同一个封顶读取器,装入侧的指令查重/tokenBroker/保留前缀
+ 门禁照走)—— 不要求用户重新提供原始 `.cindy`,不存在不可恢复状态;随包插件不走人工
+ 确认,由启动对账自动补(UI 提示「重启应用即恢复」)。一次性门的完整判据(三道,缺一
+ 即漏):ledger 存在不迁;状态根有任何**有效** receipt 不迁并补写 ledger(损坏/旧
+ schema 的 receipt 不算「活动过」——它们正是本条要治愈的对象,能改坏 receipt 的进程与
+ §「状态根无写保护」登记的伪造者同类);**首次写任何 receipt 时自动落 ledger**(不落
+ 的话,「新装 receipt 后、下一轮对账前」删 receipt 可骗一次按已扩权 manifest 的重铸)。
+ 安装根为空/未诞生时**不落 ledger**——门要留给 owner 命名空间 legacy 恢复流程随后搬入
+ 的旧目录;恢复流程对刚搬入的 id 走 `backfillRecoveredLegacyGhosts` 旁路(信任级与首轮
+ 迁移等同,只作用于恢复流程自己搬动的 id)。安装根读失败(非 ENOENT)整轮放弃且不落
+ ledger,下次启动重试。迁移失败的 id 记进 ledger 的 `failedIds` 供排查,逐个走上面的
+ 恢复入口。整轮对账(迁移+播种+批准写入)与「从已装目录重新确认」都必须持
+ GhostMutationCoordinator 的 owner 租约——状态根路径是每次调用现解析的,不持租约时
+ 异步 hash/copy 中途账号切换落定,写入会漏进新 owner 的状态根。
- `networkSlot.ts` 的 `as: 'media'` 不能只信任 Content-Type(GLB 常见
`application/octet-stream`),需要安全的 magic-byte/扩展名嗅探。
- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机