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(plugin): 自动迁移设备模拟器安装身份并保留原数据键

Dash51cf9a368662
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 40841027dc..695e3c2818 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -116,6 +116,7 @@ import {
type GhostInstallReceiptReadResult,
} from './ghostInstallReceipt.js';
import { parseInstalledGhostManifest } from '../installedGhostManifest.js';
+import { validSimulatorMigration } from '../../shared/simulatorIdentityMigration.js';
import {
decodeGhostManualMarkdown,
ghostManualLogicalPathForEntry,
@@ -237,6 +238,7 @@ export interface GhostManagerLogger {
}
export interface ApprovedGhostInstallEvidence {
+ simulatorMarketRelease?: GhostInstallReceipt['simulatorMarketRelease'];
/** Immutable package hash when the approval came from a modern install/update. */
packageSha256: string | null;
/** Unlocalized manifest frozen in the Host approval receipt. */
@@ -897,6 +899,7 @@ export class GhostManager {
const receipt = recovery.receipt;
return {
ghostId: receipt.id,
+ ...(receipt.simulatorPreviousRelId ? { simulatorPreviousRelId: receipt.simulatorPreviousRelId } : {}),
hasNamespace: hasDeliveryNamespace(receipt),
namespace: hasDeliveryNamespace(receipt) ? receipt.namespace ?? null : null,
revision: receipt.revision,
@@ -1441,6 +1444,9 @@ export class GhostManager {
continue;
}
const marker = markerResult.mutation;
+ if (marker.kind === 'update' && marker.simulatorPreviousRelId) {
+ this.untrustedApprovals.add(this.isolationKey(marker.simulatorPreviousRelId));
+ }
try {
if (marker.kind === 'uninstall') {
// 卸载崩在半途:把批准与内容目录都删净(幂等,顺序无关)。撤批准已在卸载时
@@ -1505,6 +1511,40 @@ export class GhostManager {
(marker.oldPackageSha256 !== undefined
? marker.oldPackageSha256 !== marker.packageSha256
: marker.phase === 'published'));
+ if (marker.simulatorPreviousRelId) {
+ const previousId = marker.simulatorPreviousRelId;
+ const previousDir = this.contentPath(previousId);
+ const previousKind = this.recoveryEntryKind(previousDir);
+ if (committed) {
+ if (approval.state !== 'approved' || approval.receipt.simulatorPreviousRelId !== previousId ||
+ previousKind !== 'missing' || (backupKind !== 'missing' && backupKind !== 'directory')) {
+ throw new Error('Simulator migration commit evidence changed');
+ }
+ this.receiptStore.removeSync(previousId);
+ if (backupKind === 'directory') fs.rmSync(backupPath, { recursive: true, force: true });
+ } else {
+ // A new receipt without its directory, or an unrelated receipt, must not be overwritten.
+ if (approval.state === 'approved') throw new Error('Simulator migration receipt changed');
+ const previousApproval = this.receiptStore.readForRecovery(previousId);
+ if (previousApproval.state !== 'approved' ||
+ (marker.oldPackageSha256 && previousApproval.receipt.packageSha256 !== marker.oldPackageSha256)) {
+ throw new Error('Simulator migration original approval changed');
+ }
+ if (backupKind === 'directory' && previousKind === 'missing') {
+ if (finalKind === 'directory') fs.rmSync(finalDir, { recursive: true, force: true });
+ else if (finalKind !== 'missing') throw new Error('Simulator migration target is not a directory');
+ fs.renameSync(backupPath, previousDir);
+ this.receiptStore.removeSync(id);
+ } else if (!(backupKind === 'missing' && previousKind === 'directory' &&
+ finalKind === 'missing' && marker.phase === 'prepared')) {
+ throw new Error('Simulator migration rollback has no unique original directory');
+ }
+ }
+ this.receiptStore.clearPendingMutationSync(id);
+ this.untrustedApprovals.delete(this.isolationKey(id));
+ this.untrustedApprovals.delete(this.isolationKey(previousId));
+ continue;
+ }
if (marker.sourceStateArchiveId !== undefined) {
if (!this.options.onArchiveSourceState) throw new Error('source archive recovery callback unavailable');
if (backupKind !== 'directory' && backupKind !== 'missing') {
@@ -1959,6 +1999,7 @@ export class GhostManager {
packageSha256:
packageSha256 && /^[a-f0-9]{64}$/.test(packageSha256) ? packageSha256 : null,
approvedManifest: approval.receipt.manifest,
+ ...(approval.receipt.simulatorMarketRelease ? { simulatorMarketRelease: approval.receipt.simulatorMarketRelease } : {}),
legacyMigrated: Boolean(
migration
&& migration.state !== 'in-progress'
@@ -4120,6 +4161,9 @@ export class GhostManager {
installOrigin?: 'manual' | 'agent-forge';
namespace?: string | null;
sourceStateArchiveId?: string;
+ /** Host-only official market transition; package authors cannot request this. */
+ simulatorPreviousRelId?: string;
+ simulatorMarketRelease?: GhostInstallReceipt['simulatorMarketRelease'];
beforePackageCommit?: () => GhostPackageCommitPreparation | void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
onPackagePlaced?: () => void;
@@ -4139,6 +4183,8 @@ export class GhostManager {
installOrigin?: 'manual' | 'agent-forge';
namespace?: string | null;
sourceStateArchiveId?: string;
+ simulatorPreviousRelId?: string;
+ simulatorMarketRelease?: GhostInstallReceipt['simulatorMarketRelease'];
/** 新目录已换位、旧目录仍可回滚时执行;抛错会恢复旧版本。 */
beforePackageCommit?: () => GhostPackageCommitPreparation | void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
@@ -4175,6 +4221,15 @@ export class GhostManager {
const identity = createPluginLogicalIdentity(opts.namespace ?? null, manifest.id);
const relId =
this.resolvePhysicalRelId(pluginNewInstallRelId(identity), true) ?? pluginNewInstallRelId(identity);
+ const previousRelId = opts.simulatorPreviousRelId;
+ const sourceRelId = previousRelId ?? relId;
+ if (previousRelId !== undefined &&
+ (!validSimulatorMigration(previousRelId, manifest.id, opts.namespace) ||
+ opts.sourceStateArchiveId !== undefined || this.recoveryEntryKind(this.contentPath(relId)) !== 'missing' ||
+ findInstanceByContentRelId(this.syncInstanceRegistry(), relId) !== undefined ||
+ this.receiptStore.readForRecovery(relId).state !== 'missing')) {
+ return { rejection: { code: 'state-changed', reason: 'Simulator migration target changed' } };
+ }
if (this.hasPendingMutationJournal(relId)) {
this.untrustedApprovals.add(this.isolationKey(relId));
return { rejection: { code: 'io', reason: '意识正在恢复,请稍后重试' } };
@@ -4187,12 +4242,21 @@ export class GhostManager {
return { rejection: { code: 'io', reason: 'source state archive identity or callback unavailable' } };
}
const finalDir = this.contentPath(relId);
- if (!this.isRealDirChildRel(relId)) {
+ const sourceDir = this.contentPath(sourceRelId);
+ if (!this.isRealDirChildRel(sourceRelId) || this.hasPendingMutationJournal(sourceRelId)) {
return {
rejection: { code: 'not-installed', reason: `意识 ${manifest.id} 未装入,无从更新` },
};
}
- const approvalResult = this.readApproval(relId);
+ const approvalResult = this.readApproval(sourceRelId);
+ if (previousRelId && (approvalResult.state !== 'approved' || approvalResult.receipt.namespace != null)) {
+ return { rejection: { code: 'state-changed', reason: 'Simulator migration needs an approved root installation' } };
+ }
+ if (previousRelId && opts.simulatorMarketRelease && approvalResult.state === 'approved' &&
+ approvalResult.receipt.packageSha256 &&
+ approvalResult.receipt.packageSha256 !== opts.simulatorMarketRelease.previousPackageSha256) {
+ return { rejection: { code: 'state-changed', reason: 'Simulator migration package provenance changed' } };
+ }
const actualApproval = approvalTokenFor(approvalResult);
if (actualApproval !== opts.expectedInstalledApproval) {
return {
@@ -4205,22 +4269,24 @@ export class GhostManager {
// 来源描述的是本次明确选择的装入通道,而不是 id 的永久资格。手动更新
// 不继承旧 Forge 来源,否则新增 OIDC host 可绕过 Forge 的窄确认。
const installOrigin = opts.installOrigin;
+ const retainedSimulatorRelId = previousRelId ??
+ (approvalResult.state === 'approved' ? approvalResult.receipt.simulatorPreviousRelId : undefined);
// 延续当前唤醒/沉睡状态。旧安装尚无 receipt 时,重新安装仍采用原
// `.disabled` 镜像;损坏 receipt 一律保持停用。
const enabled =
approvalResult.state === 'approved'
? // 读时合并后的有效值:receipt 可能因状态根短暂不可写而停在陈旧的 enabled=true,
// 用户的停用镜像不能被一次更新静默冲掉。
- this.effectiveEnabled(finalDir, approvalResult.receipt.enabled)
+ this.effectiveEnabled(sourceDir, approvalResult.receipt.enabled)
: approvalResult.state === 'legacy-unapproved'
- ? !this.isDisabledMarkerPresentSync(finalDir)
+ ? !this.isDisabledMarkerPresentSync(sourceDir)
: false;
// 指令查重同 install,但豁免自己(新版本沿用/改名自己的指令都合法)。
if (manifest.command !== undefined) {
const holder = findConflictingGhostCommand(this.list(), manifest.command, {
incomingNamespace: identity.namespace,
- exemptPhysicalRelId: relId,
+ exemptPhysicalRelId: sourceRelId,
});
if (holder) {
return {
@@ -4266,6 +4332,7 @@ export class GhostManager {
backupDirName: path.basename(backupDir),
receiptRevision,
phase: 'prepared',
+ ...(previousRelId ? { simulatorPreviousRelId: previousRelId } : {}),
...(archiveId !== undefined ? { sourceStateArchiveId: archiveId } : {}),
...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256
? { oldPackageSha256: approvalResult.receipt.packageSha256 }
@@ -4283,10 +4350,13 @@ export class GhostManager {
// receipt onto the new finalDir while the new receipt and skill snapshot
// are still being committed.
this.untrustedApprovals.add(this.isolationKey(relId));
+ this.untrustedApprovals.add(this.isolationKey(sourceRelId));
const clearUpdateQuarantineAfterRollback = async (): Promise<void> => {
try {
+ if (previousRelId) await this.receiptStore.remove(relId);
await this.receiptStore.clearPendingMutation(relId);
this.untrustedApprovals.delete(this.isolationKey(relId));
+ this.untrustedApprovals.delete(this.isolationKey(sourceRelId));
} catch {
// Keep the in-process quarantine if the journal cannot be cleared;
// restart recovery must see the marker before authorization resumes.
@@ -4294,7 +4364,7 @@ export class GhostManager {
};
// 换目录:旧版先挪去备份位,新版 rename 失败即滚回,保证任何时刻都有一份完整版本在位。
try {
- await this.renameManagedDir(finalDir, backupDir, 'update backup', manifest.id);
+ await this.renameManagedDir(sourceDir, backupDir, 'update backup', manifest.id);
} catch (err) {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
await clearUpdateQuarantineAfterRollback();
@@ -4312,6 +4382,7 @@ export class GhostManager {
backupDirName: path.basename(backupDir),
receiptRevision,
phase: 'backed-up',
+ ...(previousRelId ? { simulatorPreviousRelId: previousRelId } : {}),
...(archiveId !== undefined ? { sourceStateArchiveId: archiveId } : {}),
...(approvalResult.state === 'approved' && approvalResult.receipt.packageSha256
? { oldPackageSha256: approvalResult.receipt.packageSha256 }
@@ -4331,7 +4402,7 @@ export class GhostManager {
await this.renameManagedDir(stagingDir, finalDir, 'update placement', manifest.id);
} catch (err) {
let rolledBack = true;
- await this.renameManagedDir(backupDir, finalDir, 'update rollback', manifest.id).catch((rollbackErr) => {
+ await this.renameManagedDir(backupDir, sourceDir, 'update rollback', manifest.id).catch((rollbackErr) => {
rolledBack = false;
(this.options.log?.error ?? this.options.log?.warn)?.call(
this.options.log,
@@ -4373,6 +4444,8 @@ export class GhostManager {
}
packageCommitPreparation = opts.beforePackageCommit?.() ?? undefined;
receipt = createGhostInstallReceipt({
+ ...(retainedSimulatorRelId ? { simulatorPreviousRelId: retainedSimulatorRelId } : {}),
+ ...(previousRelId && opts.simulatorMarketRelease ? { simulatorMarketRelease: opts.simulatorMarketRelease } : {}),
manifest: approvedManifest,
localeResources,
enabled,
@@ -4438,7 +4511,7 @@ export class GhostManager {
if (sideEffectRolledBack) {
directoryRolledBack = true;
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
- await this.renameManagedDir(backupDir, finalDir, 'update receipt rollback', manifest.id).catch((rollbackErr) => {
+ await this.renameManagedDir(backupDir, sourceDir, 'update receipt rollback', manifest.id).catch((rollbackErr) => {
directoryRolledBack = false;
(this.options.log?.error ?? this.options.log?.warn)?.call(
this.options.log,
@@ -4475,8 +4548,10 @@ export class GhostManager {
}
// receipt 已就位 = 事务提交,清标记后再回收 backup;顺序保证"标记在 ⟺ 可能未提交"。
try {
+ if (previousRelId) await this.receiptStore.remove(previousRelId);
await this.receiptStore.clearPendingMutation(relId);
this.untrustedApprovals.delete(this.isolationKey(relId));
+ this.untrustedApprovals.delete(this.isolationKey(sourceRelId));
} catch {
// Keep quarantine while the durable journal remains; recovery retries it.
}
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 2b3771e46a..dc623d7bee 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -103,6 +103,137 @@ function goodManifest(id = 'hello'): Record<string, unknown> {
};
}
+describe('official simulator identity migration', () => {
+ it.each(['prepared', 'backed-up', 'placed', 'committed'] as const)(
+ 'recovers an interrupted rename at %s without duplicating the installed instance', async phase => {
+ await manager.install(await makeCindy('old.cindy', goodManifest('baguette-simulator')), { namespace: null });
+ const old = manager.list()[0]!;
+ const oldRelId = installedGhostPhysicalRelId(old);
+ const other = new GhostManager({ getRootDir: () => path.join(workDir, 'package-fixture') });
+ await other.install(await makeCindy('new.cindy', goodManifest('cindy-simulator')), { namespace: null });
+ const next = other.list()[0]!;
+ const relId = installedGhostPhysicalRelId(next);
+ const nextStore = new GhostInstallReceiptStore(() => other.approvalStateRoot());
+ const nextApproval = nextStore.read(relId);
+ if (nextApproval.state !== 'approved') throw new Error('missing fixture approval');
+ const store = new GhostInstallReceiptStore(() => manager.approvalStateRoot());
+ const backupDirName = `.cindy-updating-${pluginInstallStoragePart(relId)}-1234abcd`;
+ await store.writePendingMutation(relId, {
+ kind: 'update', packageSha256: nextApproval.receipt.packageSha256!,
+ receiptRevision: nextApproval.receipt.revision, backupDirName,
+ phase: phase === 'prepared' ? 'prepared' : 'backed-up', simulatorPreviousRelId: oldRelId,
+ });
+ const finalDir = path.join(rootDir, relId);
+ if (phase !== 'prepared') fs.renameSync(old.dir, path.join(rootDir, backupDirName));
+ if (phase === 'placed' || phase === 'committed') fs.cpSync(next.dir, finalDir, { recursive: true });
+ if (phase === 'committed') await store.write({ ...nextApproval.receipt, simulatorPreviousRelId: oldRelId },
+ { relId, skillSourceDir: finalDir });
+ manager = new GhostManager({ getRootDir: () => rootDir });
+ const recovered = manager.list();
+ expect(recovered).toHaveLength(1);
+ expect(recovered[0]!.manifest.id).toBe(phase === 'committed' ? 'cindy-simulator' : 'baguette-simulator');
+ expect(installedGhostStoragePart(recovered[0]!)).toBe(installedGhostStoragePart(old));
+ expect(recovered[0]!.approval.state).toBe('approved');
+ expect(store.readPendingMutationSync(relId).state).toBe('missing');
+ expect(fs.existsSync(path.join(rootDir, backupDirName))).toBe(false);
+ },
+ );
+
+ it('does not take over an organization installation', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest('baguette-simulator')), { namespace: 'acme' });
+ const old = manager.list()[0]!;
+ const file = await makeCindy('new.cindy', goodManifest('cindy-simulator'));
+ await expectRejection(await manager.update(file, { namespace: null,
+ simulatorPreviousRelId: installedGhostPhysicalRelId(old), expectedInstalledApproval: ghostInstallApprovalToken(old.approval),
+ }), 'state-changed');
+ expect(manager.list()[0]!.dir).toBe(old.dir);
+ });
+
+ it('does not replace a separately installed target or accept a stale source approval', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest('baguette-simulator')), { namespace: null });
+ const old = manager.list()[0]!;
+ const file = await makeCindy('new.cindy', goodManifest('cindy-simulator'));
+ await expectRejection(await manager.update(file, { namespace: null,
+ simulatorPreviousRelId: installedGhostPhysicalRelId(old),
+ expectedInstalledApproval: 'approved:00000000-0000-4000-8000-000000000001',
+ }), 'state-changed');
+ await manager.install(file, { namespace: null });
+ await expectRejection(await manager.update(file, { namespace: null,
+ simulatorPreviousRelId: installedGhostPhysicalRelId(old), expectedInstalledApproval: ghostInstallApprovalToken(old.approval),
+ }), 'state-changed');
+ expect(manager.list()).toHaveLength(2);
+ });
+
+ it('keeps the original bare storage key and existing task grants for a legacy root install', async () => {
+ const manifest = { ...goodManifest('baguette-simulator'), slots: ['tool', 'agent'], agent: { tasks: true, targets: true } };
+ await installLegacyApproved(await makeCindy('legacy.cindy', manifest));
+ const old = manager.list()[0]!;
+ const store = new GhostInstallReceiptStore(() => manager.approvalStateRoot());
+ const approval = store.read(installedGhostPhysicalRelId(old));
+ if (approval.state !== 'approved') throw new Error('missing fixture receipt');
+ await store.write({ ...approval.receipt, taskCapabilityApproved: true, targetCapabilityApproved: true },
+ { relId: installedGhostPhysicalRelId(old), skillSourceDir: old.dir });
+ const result = await manager.update(await makeCindy('new.cindy', { ...manifest, id: 'cindy-simulator' }), {
+ namespace: null, simulatorPreviousRelId: installedGhostPhysicalRelId(old),
+ expectedInstalledApproval: ghostInstallApprovalToken(old.approval),
+ });
+ expect(result).toHaveProperty('ghost');
+ const next = manager.list()[0]!;
+ expect(installedGhostStoragePart(next)).toBe('baguette-simulator');
+ const receipt = manager.readApprovedInstallReceipt(installedGhostStoragePart(next));
+ expect(receipt).toMatchObject({ id: 'cindy-simulator', taskCapabilityApproved: true, targetCapabilityApproved: true });
+ await manager.setEnabled(installedGhostPhysicalRelId(next), false, ghostInstallApprovalToken(next.approval));
+ expect(manager.list()[0]!.enabled).toBe(false);
+ await manager.uninstall(installedGhostPhysicalRelId(manager.list()[0]!));
+ expect(manager.list()).toHaveLength(0);
+ });
+
+ it.each([true, false])('preserves storage and enabled=%s across rename, restart and subsequent updates', async (enabled) => {
+ await manager.install(await makeCindy('old.cindy', goodManifest('baguette-simulator')),
+ { initiallyEnabled: enabled, namespace: null });
+ const old = manager.list()[0]!;
+ const previousRelId = installedGhostPhysicalRelId(old);
+ const nextPackage = await makeCindy('new.cindy', { ...goodManifest('cindy-simulator'), version: '2.0.0' });
+ const result = await manager.update(nextPackage, {
+ expectedInstalledApproval: ghostInstallApprovalToken(old.approval),
+ namespace: null, simulatorPreviousRelId: previousRelId,
+ });
+ expect(result).toHaveProperty('ghost');
+ expect(manager.list()).toHaveLength(1);
+ const next = manager.list()[0]!;
+ expect(next.manifest.id).toBe('cindy-simulator');
+ expect(next.enabled).toBe(enabled);
+ expect(installedGhostStoragePart(next)).toBe(installedGhostStoragePart(old));
+ expect(fs.existsSync(old.dir)).toBe(false);
+ manager = new GhostManager({ getRootDir: () => rootDir });
+ expect(installedGhostStoragePart(manager.list()[0]!)).toBe(installedGhostStoragePart(old));
+ // Registry recovery must derive the same key from the host receipt, never from the new name.
+ fs.unlinkSync(path.join(manager.approvalStateRoot(), 'plugin-instances.v2.json'));
+ manager = new GhostManager({ getRootDir: () => rootDir });
+ const recovered = manager.list()[0]!;
+ expect(installedGhostStoragePart(recovered)).toBe(installedGhostStoragePart(old));
+ const update = await manager.update(await makeCindy('next.cindy', {
+ ...goodManifest('cindy-simulator'), version: '3.0.0',
+ }), { expectedInstalledApproval: ghostInstallApprovalToken(recovered.approval), namespace: null });
+ expect(update).toHaveProperty('ghost');
+ expect(installedGhostStoragePart(manager.list()[0]!)).toBe(installedGhostStoragePart(old));
+ });
+
+ it('restores the old package and approval when the new receipt cannot commit', async () => {
+ await manager.install(await makeCindy('old.cindy', goodManifest('baguette-simulator')), { namespace: null });
+ const old = manager.list()[0]!;
+ const result = await manager.update(await makeCindy('new.cindy', goodManifest('cindy-simulator')), {
+ namespace: null, simulatorPreviousRelId: installedGhostPhysicalRelId(old),
+ expectedInstalledApproval: ghostInstallApprovalToken(old.approval),
+ beforePackageCommit: () => { throw new Error('injected commit failure'); },
+ });
+ expect(result).toHaveProperty('rejection.code', 'io');
+ expect(manager.list()).toHaveLength(1);
+ expect(manager.list()[0]!.manifest.id).toBe('baguette-simulator');
+ expect(manager.list()[0]!.approval).toEqual(old.approval);
+ });
+});
+
describe('GhostManager enable revision boundary', () => {
// Unit regression: an unreadable installation subtree used to become an empty
// scan and persist active:false. Exercise list(), retain the approved install
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 9e9ac8f52c..caf945d596 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -2,7 +2,8 @@ import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { readBoundedFileNoFollow, readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
-import { isValidPluginNamespace } from '@cindy/plugin-protocol';
+import { isValidPluginNamespace, isValidPluginResourceId } from '@cindy/plugin-protocol';
+import { validSimulatorMigration } from '../../shared/simulatorIdentityMigration.js';
import {
createPluginLogicalIdentity,
@@ -120,6 +121,10 @@ function isValidIconDataUrl(value: unknown): value is string {
* 目录加载,只有技能目录因为越出沙箱而被拷成快照。
*/
export interface GhostInstallReceipt {
+ /** Host-written origin preserves the existing storage key across the official simulator rename. */
+ simulatorPreviousRelId?: string;
+ /** Verified market delivery committed with the rename; repairs a crash before ledger completion. */
+ simulatorMarketRelease?: { pluginId: string; releaseId: string; previousPackageSha256: string };
/** Explicit Host confirmation; absent on older receipts, never inferred from manifest. */
taskCapabilityApproved?: true;
targetCapabilityApproved?: true;
@@ -242,6 +247,7 @@ export type GhostPendingMutation =
/** Hash of the previously approved bytes, when an approval existed. */
oldPackageSha256?: string;
sourceStateArchiveId?: string;
+ simulatorPreviousRelId?: string;
}
// uninstall 不带 packageSha256:它的提交信号不是"receipt 写到某版本",而是"receipt +
// 内容目录都已移除"。恢复见到它就把两者删干净(顺序无关,幂等)。
@@ -975,6 +981,12 @@ export class GhostInstallReceiptStore {
const oldPackageSha256 = raw.oldPackageSha256;
const receiptRevision = raw.receiptRevision;
const sourceStateArchiveId = raw.sourceStateArchiveId;
+ const simulatorPreviousRelId = raw.simulatorPreviousRelId;
+ if (simulatorPreviousRelId !== undefined &&
+ (!validSimulatorMigration(simulatorPreviousRelId, parsePluginInstallRelId(id)?.ghostId ?? '',
+ parsePluginInstallRelId(id)?.namespace) || sourceStateArchiveId !== undefined || receiptRevision === undefined)) {
+ return { state: 'invalid', reason: 'journal simulator migration identity is invalid' };
+ }
if (sourceStateArchiveId !== undefined &&
(!isValidGhostSourceStateArchiveId(sourceStateArchiveId) || receiptRevision === undefined)) {
return { state: 'invalid', reason: 'journal source state archive identity is invalid' };
@@ -1001,6 +1013,7 @@ export class GhostInstallReceiptStore {
...(phase !== undefined ? { phase } : {}),
...(oldPackageSha256 !== undefined ? { oldPackageSha256 } : {}),
...(sourceStateArchiveId !== undefined ? { sourceStateArchiveId } : {}),
+ ...(typeof simulatorPreviousRelId === 'string' ? { simulatorPreviousRelId } : {}),
},
};
}
@@ -1251,6 +1264,8 @@ export function readLegacyInstallTrust(dir: string): GhostTrustInfo | null {
}
export function createGhostInstallReceipt(input: {
+ simulatorPreviousRelId?: string;
+ simulatorMarketRelease?: GhostInstallReceipt['simulatorMarketRelease'];
taskCapabilityApproved?: true;
targetCapabilityApproved?: true;
manifest: GhostManifest;
@@ -1272,6 +1287,8 @@ export function createGhostInstallReceipt(input: {
return {
schemaVersion: RECEIPT_SCHEMA_VERSION,
id: input.manifest.id,
+ ...(input.simulatorPreviousRelId ? { simulatorPreviousRelId: input.simulatorPreviousRelId } : {}),
+ ...(input.simulatorMarketRelease ? { simulatorMarketRelease: input.simulatorMarketRelease } : {}),
...(hasDeliveryNamespace(input)
? { namespace: input.namespace ?? null }
: {}),
@@ -1455,6 +1472,22 @@ function validateReceipt(
typeof value.legacyFirstPartyEligible !== 'boolean') {
return { ok: false, reason: 'receipt legacyFirstPartyEligible 不合法' };
}
+ if (value.simulatorPreviousRelId !== undefined &&
+ !validSimulatorMigration(value.simulatorPreviousRelId, expectedId, namespace)) {
+ return { ok: false, reason: 'receipt simulator migration identity is invalid' };
+ }
+ let simulatorMarketRelease: GhostInstallReceipt['simulatorMarketRelease'];
+ if (value.simulatorMarketRelease !== undefined) {
+ const release = value.simulatorMarketRelease as Record<string, unknown> | null;
+ if (!value.simulatorPreviousRelId || !release || typeof release !== 'object' ||
+ !isValidPluginResourceId(release.pluginId) || !isValidPluginResourceId(release.releaseId) ||
+ typeof release.previousPackageSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(release.previousPackageSha256) ||
+ typeof value.packageSha256 !== 'string') {
+ return { ok: false, reason: 'receipt simulator market release is invalid' };
+ }
+ simulatorMarketRelease = { pluginId: release.pluginId, releaseId: release.releaseId,
+ previousPackageSha256: release.previousPackageSha256 };
+ }
let installOrigin: string | undefined;
if (value.installOrigin !== undefined) {
if (
@@ -1470,6 +1503,8 @@ function validateReceipt(
receipt: {
schemaVersion: RECEIPT_SCHEMA_VERSION,
id: expectedId,
+ ...(typeof value.simulatorPreviousRelId === 'string' ? { simulatorPreviousRelId: value.simulatorPreviousRelId } : {}),
+ ...(simulatorMarketRelease ? { simulatorMarketRelease } : {}),
revision: value.revision,
manifest: manifestResult.manifest,
localeResources,
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 355d547f54..5c5bc94804 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -245,6 +245,8 @@ import {
hasDeliveryNamespace,
deliveryNamespaceFields,
} from '../../shared/pluginIdentity.js';
+import { LEGACY_SIMULATOR_ID, validSimulatorMigration } from '../../shared/simulatorIdentityMigration.js';
+import type { GhostInstallReceipt } from './ghostInstallReceipt.js';
import { allocateArchiveInstanceKey, selectMarketPluginIdForInstance } from './pluginInstanceRegistry.js';
import {
createNamespaceMigrationHost,
@@ -7391,6 +7393,8 @@ export async function installOrUpdateMarketGhostPackage(
cindyFilePath: string,
expected: {
ghostId: string;
+ simulatorPreviousRelId?: string;
+ simulatorMarketRelease?: GhostInstallReceipt['simulatorMarketRelease'];
version: string;
namespace?: string | null;
sourceChanged?: boolean;
@@ -7432,7 +7436,9 @@ export async function installOrUpdateMarketGhostPackage(
// 都经此出口,调用方漏取锁也被兜住;调用方已持有时按可重入 no-op(它们会把
// 复核与账本写入一起纳入同一把锁,范围比这里更大)。
return withGhostInstallLock(expected.ghostId, () =>
- installOrUpdateMarketGhostPackageLocked(cindyFilePath, expected),
+ expected.simulatorPreviousRelId
+ ? withGhostInstallLock(LEGACY_SIMULATOR_ID, () => installOrUpdateMarketGhostPackageLocked(cindyFilePath, expected))
+ : installOrUpdateMarketGhostPackageLocked(cindyFilePath, expected),
);
}
@@ -7440,6 +7446,8 @@ async function installOrUpdateMarketGhostPackageLocked(
cindyFilePath: string,
expected: {
ghostId: string;
+ simulatorPreviousRelId?: string;
+ simulatorMarketRelease?: GhostInstallReceipt['simulatorMarketRelease'];
version: string;
namespace?: string | null;
sourceChanged?: boolean;
@@ -7498,7 +7506,18 @@ async function installOrUpdateMarketGhostPackageLocked(
// Manifest 只用于展示,不参与这里的安装准入。
const marketNamespace: string | null = hasDeliveryNamespace(expected) ? expected.namespace : null;
const installIdentity = createPluginLogicalIdentity(marketNamespace, expected.ghostId);
- const installed = findInstalledGhostByIdentity(manager.list(), installIdentity);
+ const allInstalled = manager.list();
+ const directInstalled = findInstalledGhostByIdentity(allInstalled, installIdentity);
+ const previousRelId = expected.simulatorPreviousRelId;
+ if (previousRelId !== undefined && (!validSimulatorMigration(previousRelId, expected.ghostId, marketNamespace) ||
+ expected.pendingMarketRecord?.scope !== 'public' || !expected.pluginId || expected.sourceChanged || directInstalled ||
+ expected.simulatorMarketRelease?.pluginId !== expected.pluginId)) {
+ throwIpcError('PRECONDITION_FAILED', 'Simulator migration target changed');
+ }
+ const installed = previousRelId
+ ? allInstalled.find(ghost => installedGhostPhysicalRelId(ghost) === previousRelId && ghost.namespace == null)
+ : directInstalled;
+ if (previousRelId && !installed) throwIpcError('PRECONDITION_FAILED', 'Simulator migration source disappeared');
const placementError = organizationMarketPlacementError({
scope: expected.pendingMarketRecord?.scope ?? null,
requestedNamespace: marketNamespace,
@@ -7619,6 +7638,8 @@ async function installOrUpdateMarketGhostPackageLocked(
targetCapabilityApproved: confirmedTaskCapability(expected.consent, installed, inspected.manifest, 'targets'),
expectedPackageSha256: inspected.packageSha256,
expectedInstalledApproval: expected.expectedInstalledApproval!,
+ ...(previousRelId ? { simulatorPreviousRelId: previousRelId } : {}),
+ ...(previousRelId ? { simulatorMarketRelease: expected.simulatorMarketRelease } : {}),
...(expected.sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(installed) } : {}),
...(trustOverride ? { trustOverride } : {}),
namespace: marketNamespace,
diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
index c2b504dc15..750aed0217 100644
--- a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
@@ -3,7 +3,8 @@
*
* instanceKey is the directory storage key (helper, _root__helper,
* _ns__xd__helper). It is not allocated. Logical namespace still lives
- * here, because an old client can rewrite a receipt.
+ * here, because an old client can rewrite a receipt. The official simulator
+ * rename retains its original directory key, proven by the Host receipt.
*
* Storage (KV, secrets, OAuth, library, partitions, skills) must use
* instanceKey. Do not derive a new key from a path or namespace.
@@ -18,6 +19,7 @@ import {
hasDeliveryNamespace,
} from '../../shared/pluginIdentity.js';
import { isValidGhostId } from '../../shared/ghost.js';
+import { simulatorPreviousStoragePart, validSimulatorMigration } from '../../shared/simulatorIdentityMigration.js';
const PLUGIN_INSTANCE_REGISTRY_V1_VERSION = 1 as const;
const PLUGIN_INSTANCE_REGISTRY_VERSION = 2 as const;
@@ -90,6 +92,7 @@ export interface InstanceConfirmationEvidence {
}
export interface PluginInstanceReceiptFact {
+ simulatorPreviousRelId?: string;
ghostId: string;
hasNamespace: boolean;
namespace: string | null;
@@ -125,7 +128,9 @@ export function adoptContentInstall(input: {
/** Set when the market ledger has exactly one installed record for this ghost. */
marketPluginId?: string | null;
}): PluginInstanceRecord | null {
- const instanceKey = instanceKeyForExistingContent(input.relId);
+ const previous = input.receipt?.simulatorPreviousRelId;
+ const instanceKey = previous && validSimulatorMigration(previous, input.ghostId, input.receipt?.namespace)
+ ? simulatorPreviousStoragePart(previous) : instanceKeyForExistingContent(input.relId);
if (!instanceKey || !isValidGhostId(input.ghostId)) return null;
const origin = input.receipt?.installOrigin;
const identity = parsePluginInstallRelId(input.relId);
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 519ce97696..0acfd5ae38 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -66,6 +66,7 @@ const runtime = vi.hoisted(() => ({
packageSha256: string | null;
approvedManifest: GhostManifest;
legacyMigrated: boolean;
+ simulatorMarketRelease?: { pluginId: string; releaseId: string; previousPackageSha256: string };
} | null,
),
pluginApiBaseUrl: 'https://plugin.test.invalid' as string | null,
@@ -708,6 +709,79 @@ describe('same-release legacy organization source recovery', () => {
});
describe('PluginMarketService migration and defaultInstall', () => {
+ it('upgrades the official simulator through the old route and atomically replaces its ledger key', async () => {
+ const item = summary({ ghostId: 'cindy-simulator', namespace: null,
+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID, version: '2.0.0' } });
+ const oldManifest = manifest('baguette-simulator');
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-simulator-migration-'));
+ roots.push(root);
+ const oldDir = path.join(root, 'baguette-simulator');
+ fs.mkdirSync(oldDir);
+ fs.writeFileSync(path.join(oldDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: oldDir, namespace: null, enabled: false }];
+ runtime.approvedInstallEvidence.mockReturnValue({ packageSha256: 'a'.repeat(64),
+ approvedManifest: normalizedManifest(oldManifest), legacyMigrated: false });
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(summary({ ghostId: 'baguette-simulator', namespace: null }), {
+ manifestDigest: ghostManifestDigest(oldManifest),
+ }));
+ runtime.install.mockImplementation(async () => {
+ const next = manifest('cindy-simulator', '2.0.0');
+ const dir = path.join(root, 'cindy-simulator');
+ fs.mkdirSync(dir);
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(next));
+ runtime.ghosts = [{ manifest: next, dir, namespace: null, enabled: false }];
+ return runtime.ghosts[0];
+ });
+ const snapshot = await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledOnce();
+ expect(runtime.install.mock.calls[0]![1]).toMatchObject({
+ ghostId: 'cindy-simulator', simulatorPreviousRelId: 'baguette-simulator',
+ simulatorMarketRelease: { pluginId: item.id, releaseId: RELEASE_ID },
+ });
+ expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: false });
+ expect(h.ledger.installationForPlugin({ ghostId: 'baguette-simulator', namespace: null })).toBeNull();
+ expect(h.ledger.installationForPlugin(item)).toMatchObject({ ghostId: 'cindy-simulator', releaseId: RELEASE_ID });
+ });
+
+ it('repairs a committed simulator rename after interruption before the market ledger write', async () => {
+ const item = summary({ ghostId: 'cindy-simulator', namespace: null,
+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID, version: '2.0.0' } });
+ const next = manifest('cindy-simulator', '2.0.0');
+ runtime.ghosts = [{ ...ghostEntry('cindy-simulator'), manifest: next, namespace: null }];
+ runtime.approvedInstallEvidence.mockReturnValue({ packageSha256: item.currentRelease.sha256,
+ approvedManifest: normalizedManifest(next), legacyMigrated: false,
+ simulatorMarketRelease: { pluginId: item.id, releaseId: RELEASE_ID, previousPackageSha256: 'a'.repeat(64) },
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(summary({ ghostId: 'baguette-simulator', namespace: null })));
+ const snapshot = await h.service.snapshot();
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(snapshot.items[0]).toMatchObject({ installState: 'installed' });
+ expect(h.ledger.installationForPlugin(item)).toMatchObject({ releaseId: RELEASE_ID, version: '2.0.0' });
+ expect(h.ledger.installationForPlugin({ ghostId: 'baguette-simulator', namespace: null })).toBeNull();
+ });
+
+ it.each(['another-market-record', 'different-approved-package', 'server-rollback'] as const)(
+ 'preserves the installed simulator on %s instead of creating or taking over another instance', async scenario => {
+ const rolledBack = scenario === 'server-rollback';
+ const item = summary({ ghostId: rolledBack ? 'baguette-simulator' : 'cindy-simulator', namespace: null });
+ const installedId = rolledBack ? 'cindy-simulator' : 'baguette-simulator';
+ runtime.ghosts = [{ ...ghostEntry(installedId), namespace: null }];
+ runtime.approvedInstallEvidence.mockReturnValue({ packageSha256: 'b'.repeat(64),
+ approvedManifest: normalizedManifest(manifest(installedId)), legacyMigrated: false });
+ const h = harness([item]);
+ const previous = recordForTest(summary({ ghostId: installedId, namespace: null }), {
+ pluginId: scenario === 'another-market-record' ? `c${'f'.repeat(24)}` : item.id,
+ });
+ h.ledger.upsertInstallation(previous);
+ const snapshot = await h.service.snapshot();
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(snapshot.items[0]!.installState).toBe('conflict');
+ expect(runtime.ghosts[0]!.manifest.id).toBe(installedId);
+ },
+ );
+
// Unit: market install used four full synchronous scans before download.
// Existing download-race cases protect the later fresh approval checks;
// this first-install case protects the uninterrupted preflight work budget.
diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.ts
index 68c2c287d9..cfb10c156e 100644
--- a/apps/desktop/src/main/plugin-market/api.ts
+++ b/apps/desktop/src/main/plugin-market/api.ts
@@ -73,7 +73,8 @@ export class PluginMarketApi {
private requestOptions(): Omit<ApiFetchOptions, 'baseUrl'> {
return {
cache: 'no-store',
- headers: { [CINDY_CLIENT_VERSION_HEADER]: this.getClientVersion() },
+ headers: { [CINDY_CLIENT_VERSION_HEADER]: this.getClientVersion(),
+ 'x-cindy-plugin-migrations': 'simulator-id-v1' },
timeoutMs: PLUGIN_MARKET_API_TIMEOUT_MS,
};
}
diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.ts
index 7d7b46efb5..8c9fa66065 100644
--- a/apps/desktop/src/main/plugin-market/ledger.ts
+++ b/apps/desktop/src/main/plugin-market/ledger.ts
@@ -571,6 +571,21 @@ export class PluginMarketLedger {
this.write(data);
}
+ /** The simulator keeps its server resource; replace both local route keys in one ledger write. */
+ migrateSimulatorInstallation(expected: PluginMarketInstallationRecord, next: PluginMarketInstallationRecord): boolean {
+ const data = this.read();
+ const current = data.installations[pluginLedgerRecordKey(expected)];
+ const target = data.installations[pluginLedgerRecordKey(next)];
+ if (!current || canonicalJson(current) !== canonicalJson(expected) || !current.installed ||
+ current.ghostId !== 'baguette-simulator' || next.ghostId !== 'cindy-simulator' ||
+ current.scope !== 'public' || next.scope !== 'public' || current.namespace != null || next.namespace !== null ||
+ current.pluginId !== next.pluginId || (current.source !== 'market' && current.source !== 'legacy-adopted') ||
+ (target && target.installed)) return false;
+ this.replaceRecord(data, current, next);
+ this.write(data);
+ return true;
+ }
+
backfillServerRoot(expected: PluginMarketInstallationRecord, serverRoot: string): boolean {
const data = this.read();
const current = data.installations[pluginLedgerRecordKey(expected)];
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 381ae9a5ad..45adc90b8a 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -26,6 +26,7 @@ import {
type InstalledGhost,
} from '../../shared/ghost.js';
import { isIpcError } from '../../shared/ipc-errors.js';
+import { LEGACY_SIMULATOR_ID, SIMULATOR_ID, isSimulatorMigrationTarget, isLegacySimulatorListing } from '../../shared/simulatorIdentityMigration.js';
import type {
MarketSourceConfig,
MarketSourceSummary,
@@ -251,27 +252,39 @@ async function yieldMarketReconciliation(owner: ActiveAppSession): Promise<void>
}
function installedGhostMatchingMarketPlugin(
- plugin: { ghostId: string; namespace?: string | null },
+ plugin: { ghostId: string; namespace?: string | null; scope?: string },
ghosts: readonly InstalledGhost[] = listMarketInstallations(),
): InstalledGhost | undefined {
if (!isValidGhostId(plugin.ghostId)) {
return ghosts.find((ghost) => ghost.manifest.id === plugin.ghostId);
}
- return findInstalledGhostByIdentity(
+ const installed = findInstalledGhostByIdentity(
ghosts,
createPluginLogicalIdentity(
hasDeliveryNamespace(plugin) ? plugin.namespace : null,
plugin.ghostId,
),
);
+ return installed ?? (isSimulatorMigrationTarget(plugin)
+ ? findInstalledGhostByIdentity(ghosts, createPluginLogicalIdentity(null, LEGACY_SIMULATOR_ID))
+ : isLegacySimulatorListing(plugin) ? findInstalledGhostByIdentity(ghosts, createPluginLogicalIdentity(null, SIMULATOR_ID)) : undefined);
}
function snapshotInstallation(
local: { installations: Readonly<Record<string, PluginMarketInstallationRecord>> },
- plugin: { ghostId: string; namespace?: string | null },
+ plugin: { ghostId: string; namespace?: string | null; scope?: string; id?: string },
): PluginMarketInstallationRecord | undefined {
- return local.installations[pluginLedgerRecordKey(plugin)];
+ const current = local.installations[pluginLedgerRecordKey(plugin)];
+ if (current?.installed || !isSimulatorMigrationTarget(plugin)) return current;
+ const previous = Object.values(local.installations).filter(record => record.installed &&
+ record.ghostId === LEGACY_SIMULATOR_ID && record.namespace == null && record.scope === 'public' &&
+ record.pluginId === plugin.id && (record.source === 'market' || record.source === 'legacy-adopted'));
+ return previous.length === 1 ? previous[0] : current;
+}
+
+function serverInstallation(ledger: PluginMarketLedger, plugin: VisiblePluginSummary): PluginMarketInstallationRecord | null {
+ return snapshotInstallation({ installations: ledger.read().installations }, plugin) ?? null;
}
function removalIdentity(
@@ -292,19 +305,17 @@ function removalIdentity(
function snapshotGhost(
local: LocalInstallSnapshot,
- plugin: { ghostId: string; namespace?: string | null },
+ plugin: { ghostId: string; namespace?: string | null; scope?: string },
): InstalledGhost | undefined {
- const ghosts = local.ghostsById.get(plugin.ghostId) ?? [];
+ const ghosts = isSimulatorMigrationTarget(plugin)
+ ? [...(local.ghostsById.get(plugin.ghostId) ?? []), ...(local.ghostsById.get(LEGACY_SIMULATOR_ID) ?? [])]
+ : isLegacySimulatorListing(plugin)
+ ? [...(local.ghostsById.get(plugin.ghostId) ?? []), ...(local.ghostsById.get(SIMULATOR_ID) ?? [])]
+ : local.ghostsById.get(plugin.ghostId) ?? [];
if (!isValidGhostId(plugin.ghostId)) {
return ghosts[0];
}
- return findInstalledGhostByIdentity(
- ghosts,
- createPluginLogicalIdentity(
- hasDeliveryNamespace(plugin) ? plugin.namespace : null,
- plugin.ghostId,
- ),
- );
+ return installedGhostMatchingMarketPlugin(plugin, ghosts);
}
function snapshotManifestIdentity(
@@ -731,6 +742,18 @@ function serverRecordMatchesInstalledGhost(
);
}
+function serverRecordMatchesDelivery(
+ plugin: VisiblePluginSummary, ghost: InstalledGhost, record: PluginMarketInstallationRecord | null,
+ identity = readInstalledMarketManifestIdentity(ghost.dir),
+): boolean {
+ if (!serverRecordMatchesInstalledGhost(plugin.id, ghost, record, identity)) return false;
+ if (!isSimulatorMigrationTarget(plugin) || ghost.manifest.id !== LEGACY_SIMULATOR_ID) return true;
+ if (ghost.approval.state !== 'approved' || !record || !serverRecordMatchesSummaryRoute(plugin, record)) return false;
+ const evidence = getGhostManager().approvedInstallEvidence(installedGhostPhysicalRelId(ghost));
+ return Boolean(evidence && (evidence.packageSha256 === record.sha256 ||
+ (evidence.packageSha256 === null && evidence.legacyMigrated)));
+}
+
/** 账本是否仍指向当前服务端目录项;release 变化是升级,不属于路由漂移。 */
function serverRecordMatchesSummaryRoute(
plugin: VisiblePluginSummary,
@@ -739,7 +762,7 @@ function serverRecordMatchesSummaryRoute(
return Boolean(
record &&
record.pluginId === plugin.id &&
- record.ghostId === plugin.ghostId &&
+ (record.ghostId === plugin.ghostId || (isSimulatorMigrationTarget(plugin) && record.ghostId === LEGACY_SIMULATOR_ID)) &&
record.scope === plugin.scope &&
record.organizationId === plugin.organizationId &&
!knownDeliveryNamespacesDiffer(record, plugin),
@@ -1191,7 +1214,9 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
const ledger = this.ledgerForOwner(owner);
await this.ledgerMutation;
- if (!options.discoveryOnly) await this.backfillInstalledManifestIdentities(ledger, owner, refresh);
+ if (!options.discoveryOnly) {
+ await this.backfillInstalledManifestIdentities(ledger, owner, refresh);
+ }
const reconcileCustomUpdates = async (): Promise<'completed' | 'failed'> => {
const completed = await this.applyAutomaticUpgrades(
[],
@@ -2483,7 +2508,10 @@ export class PluginMarketService {
throwIpcError(brokerPortError.code, brokerPortError.reason);
}
const existing = snapshotGhost(local, plugin);
- const currentRecord = ledger.installationForPlugin(plugin);
+ const currentRecord = serverInstallation(ledger, plugin);
+ if (isLegacySimulatorListing(plugin) && existing?.manifest.id === SIMULATOR_ID) {
+ throwIpcError('PRECONDITION_FAILED', 'The migrated simulator cannot be replaced by a legacy-ID package');
+ }
const sourceReplacementMode = options.sourceReplacementMode ?? 'preserve-existing-source';
if (
sourceReplacementMode === 'organization-default-takeover' &&
@@ -2496,7 +2524,7 @@ export class PluginMarketService {
if (
existing &&
sourceReplacementMode === 'preserve-existing-source' &&
- !serverRecordMatchesInstalledGhost(plugin.id, existing, currentRecord, snapshotManifestIdentity(local, existing))
+ !serverRecordMatchesDelivery(plugin, existing, currentRecord, snapshotManifestIdentity(local, existing))
) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
@@ -2634,7 +2662,10 @@ export class PluginMarketService {
): Promise<InstalledGhost> {
return withPluginDeliveryInstallLock(plugin, async () => {
const installedNow = installedGhostMatchingMarketPlugin(plugin);
- const currentRecordNow = ledger.installationForPlugin(plugin);
+ const currentRecordNow = serverInstallation(ledger, plugin);
+ if (isLegacySimulatorListing(plugin) && installedNow?.manifest.id === SIMULATOR_ID) {
+ throwIpcError('PRECONDITION_FAILED', 'The migrated simulator cannot be replaced by a legacy-ID package');
+ }
if (Boolean(installedNow) !== options.expectedInstalled) {
if (options.sourceReplacementMode === 'organization-default-takeover') {
throw new SilentOrganizationDefaultTakeoverSupersededError(
@@ -2651,7 +2682,7 @@ export class PluginMarketService {
if (
installedNow &&
options.sourceReplacementMode === 'preserve-existing-source' &&
- !serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow)
+ !serverRecordMatchesDelivery(plugin, installedNow, currentRecordNow)
) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
@@ -2681,8 +2712,12 @@ export class PluginMarketService {
installedNow &&
(options.sourceReplacementMode === 'user-requested-source-change' ||
options.sourceReplacementMode === 'organization-default-takeover') &&
- !serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow),
+ !serverRecordMatchesDelivery(plugin, installedNow, currentRecordNow),
);
+ const simulatorMigration = installedNow?.manifest.id === LEGACY_SIMULATOR_ID && isSimulatorMigrationTarget(plugin);
+ if (simulatorMigration && (!currentRecordNow || sourceChanged)) {
+ throwIpcError('PRECONDITION_FAILED', 'Simulator migration requires its original market source');
+ }
const replacingSource = sourceChanged &&
options.sourceReplacementMode === 'user-requested-source-change' &&
currentRecordNow?.installed === true;
@@ -2702,6 +2737,10 @@ export class PluginMarketService {
};
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: plugin.ghostId,
+ ...(simulatorMigration && currentRecordNow
+ ? { simulatorPreviousRelId: installedGhostPhysicalRelId(installedNow),
+ simulatorMarketRelease: { pluginId: plugin.id, releaseId: plugin.currentRelease.id,
+ previousPackageSha256: currentRecordNow.sha256 } } : {}),
pluginId: plugin.id,
version: plugin.currentRelease.version,
consent: options.consent,
@@ -2735,12 +2774,17 @@ export class PluginMarketService {
// 包已落位且仍持原 owner mutation lease;即使切号终止等待超时推进了
// 当前 generation,也必须把来源写进操作开始时捕获的旧 owner 账本。
await this.withCapturedLedgerMutation(ledger, () => {
- ledger.upsertInstallation({ ...recordFrom(plugin, 'market', {
+ const next = { ...recordFrom(plugin, 'market', {
manifest: evidence.canonicalManifest,
rawManifestSha256: evidence.rawManifestSha256,
legacyManifestDigest: evidence.legacyManifestDigest,
legacyManifestDigests: [],
- }), ...(options.verifiedServerRoot ? { serverRoot: options.verifiedServerRoot } : {}) });
+ }), ...(options.verifiedServerRoot ? { serverRoot: options.verifiedServerRoot } : {}) };
+ if (simulatorMigration) {
+ if (!currentRecordNow || !ledger.migrateSimulatorInstallation(currentRecordNow, next)) {
+ throwIpcError('PRECONDITION_FAILED', 'Simulator market route changed during migration');
+ }
+ } else ledger.upsertInstallation(next);
});
},
}).catch((error) => {
@@ -2774,7 +2818,7 @@ export class PluginMarketService {
const identity = snapshotManifestIdentity(local, ghost);
const matchesUpdateRoute = Boolean(
ghost
- && serverRecordMatchesInstalledGhost(plugin.id, ghost, record ?? null, identity)
+ && serverRecordMatchesDelivery(plugin, ghost, record ?? null, identity)
&& serverRecordMatchesSummaryRoute(plugin, record ?? null),
);
const conflict = Boolean((ghost && !matchesUpdateRoute) ||
@@ -2854,7 +2898,9 @@ export class PluginMarketService {
owner: ActiveAppSession,
refresh: PluginMarketRefreshContext,
): Promise<void> {
- const candidates = Object.values(ledger.read().installations).filter(
+ const installations = ledger.read().installations;
+ await this.recoverSimulatorInstallation(ledger, owner, installations);
+ const candidates = Object.values(installations).filter(
(record) => record.installed && record.rawManifestSha256 === undefined,
);
if (candidates.length === 0) return;
@@ -2889,6 +2935,36 @@ export class PluginMarketService {
}
}
+ /** Finish only a Host-committed rename. No catalog claim can manufacture this receipt evidence. */
+ private async recoverSimulatorInstallation(ledger: PluginMarketLedger, owner: ActiveAppSession,
+ installations: Readonly<Record<string, PluginMarketInstallationRecord>>): Promise<void> {
+ const previous = Object.values(installations).filter(record => record.installed &&
+ record.ghostId === LEGACY_SIMULATOR_ID && record.namespace == null && record.scope === 'public' &&
+ (record.source === 'market' || record.source === 'legacy-adopted'));
+ if (previous.length !== 1) return;
+ const record = previous[0]!;
+ await this.withMutation(record.pluginId, () => withGhostInstallLock('cindy-simulator', () =>
+ withGhostInstallLock(LEGACY_SIMULATOR_ID, async () => {
+ requireSameMarketOwner(owner);
+ const manager = getGhostManager();
+ const installed = findInstalledGhostByIdentity(manager.list(), createPluginLogicalIdentity(null, 'cindy-simulator'));
+ if (!installed || installed.approval.state !== 'approved') return;
+ const evidence = manager.approvedInstallEvidence(installedGhostPhysicalRelId(installed));
+ const migration = evidence?.simulatorMarketRelease;
+ if (!migration || !evidence?.packageSha256 || migration.pluginId !== record.pluginId ||
+ migration.previousPackageSha256 !== record.sha256) return;
+ const identity = readInstalledMarketManifestIdentity(installed.dir);
+ if (!identity || !installedIdentityMatchesManifest(identity, evidence.approvedManifest)) return;
+ await this.withLedgerMutation(owner, () => ledger.migrateSimulatorInstallation(record, {
+ ...record, ghostId: 'cindy-simulator', namespace: null,
+ releaseId: migration.releaseId, version: evidence.approvedManifest.version,
+ sha256: evidence.packageSha256!, source: 'market',
+ manifestDigest: identity.legacyManifestDigest, rawManifestSha256: identity.rawManifestSha256,
+ updatedAt: new Date().toISOString(),
+ }));
+ })));
+ }
+
private manifestIdentityForBackfill(
record: PluginMarketInstallationRecord,
installed: InstalledGhost | undefined,
@@ -3748,7 +3824,8 @@ export class PluginMarketService {
): LocalInstallSnapshot {
const ghosts = listMarketInstallations();
return this.projectLocalInstallSnapshot(ghosts, installations, new Map(
- ghosts.filter((ghost) => ghostId === undefined || ghost.manifest.id === ghostId).map((ghost) => [
+ ghosts.filter((ghost) => ghostId === undefined || ghost.manifest.id === ghostId ||
+ (ghostId === 'cindy-simulator' && ghost.manifest.id === LEGACY_SIMULATOR_ID)).map((ghost) => [
installedGhostStoragePart(ghost),
readInstalledMarketManifestIdentity(ghost.dir),
]),
diff --git a/apps/desktop/src/shared/simulatorIdentityMigration.ts b/apps/desktop/src/shared/simulatorIdentityMigration.ts
new file mode 100644
index 0000000000..980d6c5911
--- /dev/null
+++ b/apps/desktop/src/shared/simulatorIdentityMigration.ts
@@ -0,0 +1,26 @@
+import { parsePluginInstallRelId, pluginInstallStoragePart } from './pluginIdentity.js';
+
+export const LEGACY_SIMULATOR_ID = 'baguette-simulator';
+export const SIMULATOR_ID = 'cindy-simulator';
+
+/** One host-owned migration; never an author-controlled alias or organization takeover. */
+export function isSimulatorMigrationTarget(value: {
+ ghostId: string; namespace?: string | null; scope?: string;
+}): boolean {
+ return value.ghostId === SIMULATOR_ID && value.namespace == null && value.scope === 'public';
+}
+
+export function isLegacySimulatorListing(value: { ghostId: string; namespace?: string | null; scope?: string }): boolean {
+ return value.ghostId === LEGACY_SIMULATOR_ID && value.namespace == null && value.scope === 'public';
+}
+
+export function simulatorPreviousStoragePart(previousRelId: unknown): string | null {
+ if (typeof previousRelId !== 'string') return null;
+ const identity = parsePluginInstallRelId(previousRelId);
+ return identity?.ghostId === LEGACY_SIMULATOR_ID && identity.namespace === null
+ ? pluginInstallStoragePart(previousRelId) : null;
+}
+
+export function validSimulatorMigration(previousRelId: unknown, ghostId: string, namespace: unknown): boolean {
+ return ghostId === SIMULATOR_ID && namespace === null && simulatorPreviousStoragePart(previousRelId) !== null;
+}
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 0987815e87..8c6c930098 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -655,6 +655,17 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
`instanceKey` 由安装目录推出,不另分配:旧 root 是 `helper`,新 root 是 `_root__helper`,企业是 `_ns__<namespace>__<ghostId>`。注册表丢失或损坏时按目录重建,KV、密钥和 OAuth 仍挂在这个键上。
+设备模拟器的官方 ID 迁移是单项例外:`baguette-simulator` → `cindy-simulator` 只接受
+同一 public 市场资源、root 实例、当前批准和已验证包。更新事务更换包目录、清单与 receipt,
+保留原 `instanceKey`;KV、凭据、Library、历史任务等继续使用原键,不复制数据。
+Host receipt 的 `simulatorPreviousRelId` 只允许这对 ID 和 root 路径,注册表重建仍取原键;
+作者清单不能声明该字段。后续同 ID 更新继续保留此存储身份。
+事务在移走旧包前记录旧路径,receipt 提交前中断则恢复旧包,提交后清理旧包与旧 receipt。
+提交期间两端保持隔离。新 receipt 同时记录已验证的市场资源、版本资源和旧包 SHA;
+若进程在市场账本写入前中断,现有市场维护流程核对批准、现存清单和原账本后补写。
+此恢复证据不跨下一次包更新继承。组织同名插件、自定义来源、目标已占用及来源证据不符不自动迁移。
+权限确认仍使用正常更新判据,不能借改名扩大权限;`BaguetteCindy` 底层数据目录不变。
+
`namespaceState`:
- `confirmed`:身份已确认,可以按该 namespace 使用 Broker、OIDC 等新权限。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index dfe001a60a..3dbc5cbe96 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1,5 +1,18 @@
# 跨端协议兼容
+## 设备模拟器官方 ID 更新
+
+市场请求携带 `x-cindy-plugin-migrations: simulator-id-v1` 表示客户端支持这一次官方
+`baguette-simulator` → `cindy-simulator` 安装身份迁移,不是权限或发布者凭证。
+Server 保留原市场资源 ID 和不可变旧 Release;无能力声明的客户端继续获取旧 ID 包。
+有声明的客户端获取新 ID 包,列表、详情、下载的 ghostId 必须与选中包的 manifest.id 一致。
+新客户端访问旧 Server 时仍按旧 ID 运行。只有 Server 全量升级且客户端支持已发布后,
+才可审核上架新包;不能只靠引用改名宣称旧安装已迁移。
+回滚 Server 前须通过既有版本选择恢复旧 Release;不可在新包仍为 current 时回滚到不识别迁移的 Server。
+迁移过的客户端保留新安装和原数据键,不会自动降级成旧 ID 或再装一个旧副本。
+事务失败回滚是恢复尚未提交的旧安装,不是支持任意降级客户端二进制。迁移后不得退回不认识
+该 receipt 字段的客户端并重建注册表;回退应保留这段兼容读取能力,避免重新派生数据键。
+
## 手动对齐 worktree 源分支
`worktree:list-branches` 的 IPC 响应可选追加 `remoteDefaultBranch`