Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 支持企业默认插件自动接管本地安装 (#3553)

fmfsaisaif0354ec187e1
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index fa8e0cb904..38d9a3b338 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -1036,6 +1036,19 @@ export class GhostManager {
}
}
+ /**
+ * 自动接管只能把一份成功读取且仍为 approved 的 receipt 当作来源证据。
+ * 与授权链的宽松投影不同,这里任何缺失、损坏或 I/O 异常都必须上抛。
+ */
+ readApprovedInstallOriginStrict(id: string): 'manual' | 'agent-forge' {
+ this.ensureCurrentOwnerContextSync();
+ const approval = this.readApproval(id);
+ if (approval.state !== 'approved') {
+ throw new Error(`approved Plugin receipt is unavailable: ${approval.state}`);
+ }
+ return effectiveInstallOrigin(approval.receipt);
+ }
+
/**
* Host-owned evidence for reconnecting an installation to retained source metadata.
* A pending package mutation or an invalid approval fails closed. Legacy provenance
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 8b626881e9..bf6e0d63fe 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -2269,7 +2269,7 @@ describe('GhostManager · update pre-rename recovery', () => {
});
describe('GhostManager · install', () => {
- it('个人 Forge 新装不写来源,企业确认后的 Forge 新装才写 agent-forge', async () => {
+ it('个人和企业 Forge 新装都写 agent-forge', async () => {
const personalOrigin = forgeInstallOriginForMembership('personal');
const personal = await manager.install(
await makeCindy('personal.cindy', goodManifest('personal')),
@@ -2279,8 +2279,8 @@ describe('GhostManager · install', () => {
const personalReceipt = JSON.parse(
await fs.promises.readFile(path.join(manager.approvalStateRoot(), 'personal.json'), 'utf8'),
) as Record<string, unknown>;
- expect(personalReceipt).not.toHaveProperty('installOrigin');
- expect(manager.readEffectiveInstallOrigin('personal')).toBe('manual');
+ expect(personalReceipt).toHaveProperty('installOrigin', 'agent-forge');
+ expect(manager.readEffectiveInstallOrigin('personal')).toBe('agent-forge');
const organizationOrigin = forgeInstallOriginForMembership('org');
const forged = await manager.install(
@@ -2295,6 +2295,40 @@ describe('GhostManager · install', () => {
expect(manager.readEffectiveInstallOrigin('acme-tool')).toBe('agent-forge');
});
+ it('strict origin reading rejects unreadable, invalid, and non-approved receipts', async () => {
+ await manager.install(await makeCindy('strict-origin.cindy', goodManifest()));
+ const receiptPath = path.join(manager.approvalStateRoot(), 'hello.json');
+ const mockUnreadableOnce = (): void => {
+ const realOpenSync = fs.openSync;
+ const openSpy = vi.spyOn(fs, 'openSync');
+ openSpy.mockImplementation((target, ...args) => {
+ if (path.resolve(String(target)) === path.resolve(receiptPath)) {
+ openSpy.mockRestore();
+ throw Object.assign(new Error('EIO: receipt temporarily unreadable'), { code: 'EIO' });
+ }
+ return (realOpenSync as (...openArgs: unknown[]) => number)(target, ...args);
+ });
+ };
+
+ mockUnreadableOnce();
+ expect(() => manager.readApprovedInstallOriginStrict('hello')).toThrow(
+ 'approved Plugin receipt is unavailable',
+ );
+ mockUnreadableOnce();
+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('manual');
+
+ await fs.promises.writeFile(receiptPath, '{invalid');
+ expect(() => manager.readApprovedInstallOriginStrict('hello')).toThrow(
+ 'approved Plugin receipt is unavailable',
+ );
+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('manual');
+
+ expect(() => manager.readApprovedInstallOriginStrict('missing')).toThrow(
+ 'approved Plugin receipt is unavailable',
+ );
+ expect(manager.readEffectiveInstallOrigin('missing')).toBe('manual');
+ });
+
it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
const manifest = {
...goodManifest(),
@@ -2503,7 +2537,7 @@ describe('GhostManager · install', () => {
it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {
const cindy = await makeCindy('at-resource.cindy', atResourceManifest());
- const installed = await manager.install(cindy);
+ await manager.install(cindy);
const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');
const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<
@@ -4601,7 +4635,7 @@ describe('GhostManager · update(原位换版)', () => {
expect(manager.readEffectiveInstallOrigin('hello')).toBe('agent-forge');
});
- it('个人 Forge 更新清掉旧企业 Forge 来源而不是继承资格', async () => {
+ it('个人 Forge 更新继续写作者自测来源', async () => {
await manager.install(await makeCindy('forge-v1.cindy', goodManifest()), {
installOrigin: 'agent-forge',
});
@@ -4620,7 +4654,22 @@ describe('GhostManager · update(原位换版)', () => {
const receipt = JSON.parse(
await fs.promises.readFile(path.join(manager.approvalStateRoot(), 'hello.json'), 'utf8'),
) as Record<string, unknown>;
- expect(receipt).not.toHaveProperty('installOrigin');
+ expect(receipt).toHaveProperty('installOrigin', 'agent-forge');
+ expect(manager.readEffectiveInstallOrigin('hello')).toBe('agent-forge');
+ });
+
+ it('普通本地导入覆盖 Forge 安装后回到 manual', async () => {
+ await manager.install(await makeCindy('forge-v1.cindy', goodManifest()), {
+ installOrigin: 'agent-forge',
+ });
+ const installed = manager.list().find((ghost) => ghost.manifest.id === 'hello');
+
+ const result = await manager.update(
+ await makeCindy('manual-v2.cindy', { ...goodManifest(), version: '2.0.0' }),
+ { expectedInstalledApproval: ghostInstallApprovalToken(installed?.approval) },
+ );
+
+ expect(result).toHaveProperty('ghost');
expect(manager.readEffectiveInstallOrigin('hello')).toBe('manual');
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 5f6630d136..2a348f786d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1507,7 +1507,10 @@ describe('FORGE_GUIDE', () => {
expect(FORGE_GUIDE).toContain("ghost_forge_install({ dir: '<绝对路径>' })");
expect(FORGE_GUIDE).toContain('不要因为 scaffold 或 pack 成功就自动调用本工具');
expect(FORGE_GUIDE).toContain('同版本也可覆盖');
- expect(FORGE_GUIDE).toContain('个人身份下的 Forge 安装和手动导入都不会取得这项资格');
+ expect(FORGE_GUIDE).toContain(
+ '个人身份下的 Forge 安装绝不会仅凭自测标记取得 Broker 或 Connection 权限',
+ );
+ expect(FORGE_GUIDE).toContain('受组织默认插件自动接管保护');
expect(FORGE_GUIDE).toContain(
'仅 `ghostId` 精确等于 `mivo-canvas` 且精确 oidc-token host 仅为 `mivo-canvas.dsworks.cn` 的组织成员本地安装可解析 audience',
);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallConfirmBridge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallConfirmBridge.test.ts
index 362f16d07b..9c06875354 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallConfirmBridge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallConfirmBridge.test.ts
@@ -55,12 +55,12 @@ describe('createForgeOidcInstallMainWindowSender', () => {
});
it('只有受信辅助窗口、没有主 App 窗口时失败关闭', () => {
- const trustedAuxiliaryWindow = { kind: 'resource-usage' };
- const isTrustedMainWindow = vi.fn((window: typeof trustedAuxiliaryWindow) =>
+ type TrustedAuxiliaryWindow = { kind: string };
+ const isTrustedMainWindow = vi.fn((window: TrustedAuxiliaryWindow) =>
Boolean(window),
);
const send = vi.fn();
- const sender = createForgeOidcInstallMainWindowSender<typeof trustedAuxiliaryWindow>({
+ const sender = createForgeOidcInstallMainWindowSender<TrustedAuxiliaryWindow>({
getMainWindow: () => null,
isTrustedMainWindow,
send,
@@ -73,9 +73,9 @@ describe('createForgeOidcInstallMainWindowSender', () => {
});
describe('forgeInstallOriginForMembership', () => {
- it('只给本次企业身份的 Forge 安装写作者自测来源', () => {
+ it('给个人和企业身份的明确 Forge 安装都写作者自测来源', () => {
expect(forgeInstallOriginForMembership('org')).toBe('agent-forge');
- expect(forgeInstallOriginForMembership('personal')).toBeUndefined();
+ expect(forgeInstallOriginForMembership('personal')).toBe('agent-forge');
});
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
index 329bc5a3f5..d70e66b248 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgeOidcInstallEntry.test.ts
@@ -29,12 +29,14 @@ describe('Forge OIDC install entry wiring', () => {
expect(beforeMutation).not.toContain('updateLocalGhostPackageLocked(');
});
- it('新装与原位更新都只在本次企业身份下传 agent-forge', () => {
+ it('个人与企业身份的新装和原位更新都传 agent-forge', () => {
const body = forgeInstallBody();
expect(body).toContain("const membershipKind = user?.membershipKind ?? 'personal';");
expect(body).toContain('const installOrigin = forgeInstallOriginForMembership(membershipKind);');
expect(body).toContain('...(installOrigin ? { installOrigin } : {})');
- expect(body).toContain('getActiveAppSession(),\n installOrigin,');
+ expect(body).toContain(
+ 'ghostInstallApprovalToken(installed.approval),\n installOrigin,',
+ );
expect(body).not.toContain("installOrigin: 'agent-forge'");
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index f52148c8bd..b891c3f896 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -173,7 +173,7 @@ describe('market Ghost session boundary', () => {
);
const managerUpdateIndex = helperBody.indexOf('manager.update(cindyFilePath,');
const detachIndex = helperBody.indexOf(
- 'marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject)',
+ 'marketLedger.markRemoved(inspected.manifest.id, null)',
);
expect(captureIndex).toBeGreaterThan(-1);
@@ -190,9 +190,10 @@ describe('market Ghost session boundary', () => {
expect(detachIndex).toBeGreaterThan(stopAndWaitIndex);
expect(oauthLockIndex).toBeGreaterThan(detachIndex);
expect(managerUpdateIndex).toBeGreaterThan(oauthLockIndex);
- expect(helperBody).toContain('marketLedger.isDefaultInstallSuppressed(');
expect(helperBody).toContain('marketLedger.restoreInstallation(');
- expect(helperBody).toContain('suppressed: marketRecordWasSuppressed');
+ expect(helperBody).not.toContain('marketLedger.isDefaultInstallSuppressed(');
+ expect(helperBody).not.toContain('marketInstallSubject');
+ expect(helperBody).toContain('用户显式卸载,不得产生 default-install opt-out');
expect(helperBody).toContain('onPackagePlaced: () => {');
expect(helperBody).toContain('packagePlaced = true;');
expect(helperBody).toContain('if (!packagePlaced) {\n restoreMarketRecord();');
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index e4a7253b8b..f199bbfd37 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1464,7 +1464,9 @@ ghost_forge_pack 校验并生成 .cindy 产物;需要发布时改用 publish i
Cindy 校验真实包后直接安装并启用,不再追加整张能力确认弹窗。唯一的窄确认是:企业作者
用 \`ghost_forge_install\` 安装声明了 \`oidc-token\` 的包时,需核对 id 与注入域名。市场安装会绑定所选来源,
此后的新版本由 Cindy 静默更新并保留当前启用状态;本地 \`.cindy\` 不自动猜测更新来源,
-需要用户再次导入新版包。插件自主 Host 能力仍必须完整声明,插件详情会如实展示,Host 运行时按声明
+需要用户再次导入新版包。当前组织的默认插件可能在严格核对组织、前缀、批准、退订与来源后,
+接管同 id 的普通本地导入;明确通过 \`ghost_forge_install\` 安装或更新的作者自测包会被保护,
+不会被这条自动接管路径覆盖。插件自主 Host 能力仍必须完整声明,插件详情会如实展示,Host 运行时按声明
强制守门;市场下载包若超出该版本市场清单声明的能力,会作为包内容不一致被拒绝。
**先判断谁执行,再声明能力**:
@@ -4383,8 +4385,10 @@ const opened = await cindy.iosSimulator.request({
产生的确切包直接安装;首次安装会启用,同 id 已安装时原位更新并保留启用状态、配置、
数据与面板位置,同版本也可覆盖。不要因为 scaffold 或 pack 成功就自动调用本工具。
企业身份下若清单声明 \`source:"oidc-token"\`,提交安装前会展示插件名、id 与精确请求
- 域名,并要求用户手输相同 id;取消不会安装。只有确认后的企业作者自测才会取得 Forge
- 作者资格并可签发 Connection JWT;个人身份下的 Forge 安装和手动导入都不会取得这项资格。
+ 域名,并要求用户手输相同 id;取消不会安装。个人与企业身份下的明确 Forge 安装都会标记为
+ 作者本地自测并受组织默认插件自动接管保护;但 Connection JWT 资格仍只来自当前企业身份、
+ 组织前缀与 OIDC 窄确认,个人身份下的 Forge 安装绝不会仅凭自测标记取得 Broker 或 Connection 权限,
+ 普通手动导入也不取得这项资格。
本地安装另有一条点名例外,见 §4.7:仅 \`ghostId\` 精确等于 \`mivo-canvas\` 且精确 oidc-token host 仅为 \`mivo-canvas.dsworks.cn\` 的组织成员本地安装可解析 audience;
4. 安装后再让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。
diff --git a/apps/desktop/src/main/cindy-brain/forgeOidcInstallConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/forgeOidcInstallConfirmBridge.ts
index 759bcb9e8e..9c6b9470eb 100644
--- a/apps/desktop/src/main/cindy-brain/forgeOidcInstallConfirmBridge.ts
+++ b/apps/desktop/src/main/cindy-brain/forgeOidcInstallConfirmBridge.ts
@@ -17,11 +17,10 @@ export interface ForgeOidcInstallConfirmFacts {
hosts: string[];
}
-/** 只有本次安装发生在企业身份下,receipt 才记录 Forge 作者自测来源。 */
-export function forgeInstallOriginForMembership(
- membershipKind: 'personal' | 'org',
-): 'agent-forge' | undefined {
- return membershipKind === 'org' ? 'agent-forge' : undefined;
+/** 所有明确由 ghost_forge_install 发起的安装都记录作者自测来源。 */
+export function forgeInstallOriginForMembership(membershipKind: 'personal' | 'org'): 'agent-forge' {
+ void membershipKind;
+ return 'agent-forge';
}
/** 只有企业身份安装声明了 oidc-token 的 Forge 包才需要这扇窄确认窗。 */
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 6c9c6434f7..c439ff0dfc 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -102,7 +102,6 @@ import {
import {
getAccessToken,
getAuthState,
- getCurrentUserId,
onAuthStateChange,
} from '../authManager.js';
import { serverApiFetch } from '../serverApiClient.js';
@@ -5504,7 +5503,6 @@ async function updateLocalGhostPackageLocked(
inspected: InspectedGhostPackage,
expectedPackageSha256: string,
expectedInstalledApproval: string,
- mutationOwner: ActiveAppSession,
installOrigin?: 'agent-forge',
): Promise<InstalledGhost> {
const runtime = getGhostRuntime();
@@ -5517,19 +5515,8 @@ async function updateLocalGhostPackageLocked(
// 两份后台进程。仅在确认退出后的更新阶段失败时恢复旧版本。
await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);
let marketRecord: PluginMarketInstallationRecord | null;
- let marketInstallSubject: string | null = null;
- let marketRecordWasSuppressed = false;
try {
marketRecord = marketLedger.installationForGhost(inspected.manifest.id);
- if (
- marketRecord?.installed &&
- (marketRecord.source === 'market' || marketRecord.source === 'legacy-adopted')
- ) {
- marketInstallSubject = getCurrentUserId() ?? mutationOwner.dataOwnerId;
- marketRecordWasSuppressed = marketInstallSubject
- ? marketLedger.isDefaultInstallSuppressed(marketInstallSubject, marketRecord.pluginId)
- : false;
- }
} catch (error) {
if (previousGhost) spawnIfResident(previousGhost);
log.warn('failed to verify Plugin provenance before local update', {
@@ -5544,15 +5531,9 @@ async function updateLocalGhostPackageLocked(
const restoreMarketRecord = (): void => {
if (!detachMarketRecord || !marketRecord) return;
try {
- marketLedger.restoreInstallation(
- marketRecord,
- marketInstallSubject
- ? {
- userId: marketInstallSubject,
- suppressed: marketRecordWasSuppressed,
- }
- : undefined,
- );
+ // 来源解绑不触碰 opt-out,失败恢复同样只恢复旧路由;用户过去的显式
+ // 卸载决定因此既不会被新增,也不会被清除。
+ marketLedger.restoreInstallation(marketRecord);
} catch (error) {
// 恢复失败时保持路由失效是安全降级:不能让旧市场自动覆盖用户明确选择的本地包。
log.error('failed to restore Plugin market provenance after local update failure', {
@@ -5563,8 +5544,9 @@ async function updateLocalGhostPackageLocked(
};
if (detachMarketRecord) {
try {
- // 先持久化切断自动更新路由,再改真实包。账本不可写时不触碰包。
- marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject);
+ // 先持久化切断自动更新路由,再改真实包。普通本地/Forge 换源不是
+ // 用户显式卸载,不得产生 default-install opt-out。
+ marketLedger.markRemoved(inspected.manifest.id, null);
} catch (error) {
restoreMarketRecord();
if (previousGhost) spawnIfResident(previousGhost);
@@ -5698,7 +5680,6 @@ export async function installOrUpdateLocalGhostPackageFromForge(
inspected,
expected.packageSha256,
ghostInstallApprovalToken(installed.approval),
- getActiveAppSession(),
installOrigin,
),
action: 'updated',
@@ -7302,7 +7283,6 @@ export function registerGhostIpc(): void {
inspected,
expectedPackageSha256,
expectedInstalledApproval,
- mutationOwner,
),
),
};
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index d35ecbc109..c15d3c24a2 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -133,7 +133,9 @@ describe('Plugin Market IPC error boundary', () => {
expect(serviceSource).toContain("onDefaultReconciliationOutcome?: (outcome: 'completed' | 'failed') => void;");
expect(serviceSource).toContain("const outcome = completed ? 'completed' : 'failed';");
expect(serviceSource).toContain('options.onDefaultReconciliationOutcome?.(outcome);');
- expect(serviceSource).toContain('if (!(await this.applyDefaultInstalls(plugins, owner, ledger))) completed = false;');
+ expect(serviceSource).toContain(
+ 'await this.applyDefaultInstalls(plugins, currentOrganization, owner, ledger)',
+ );
expect(serviceSource).toContain('await this.applyAutomaticUpgrades(plugins, customDiscovery.entries, owner, ledger)');
expect(serviceSource).toContain('if (error instanceof SilentUpgradeBusyError) {');
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
index 0acb2a71ef..bb489d1f11 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
@@ -122,6 +122,23 @@ describe('PluginMarketLedger', () => {
).toBe(false);
});
+ it('detaches a replacement source without creating or clearing explicit opt-out', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(record());
+ ledger.markRemoved('cindy-test', 'user-a');
+ ledger.restoreInstallation(record());
+ expect(ledger.isDefaultInstallSuppressed('user-a', `c${'a'.repeat(24)}`)).toBe(true);
+
+ ledger.markRemoved('cindy-test', null);
+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: false });
+ expect(ledger.isDefaultInstallSuppressed('user-a', `c${'a'.repeat(24)}`)).toBe(true);
+ expect(ledger.isDefaultInstallSuppressed('user-b', `c${'a'.repeat(24)}`)).toBe(false);
+
+ ledger.restoreInstallation(record());
+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: true });
+ expect(ledger.isDefaultInstallSuppressed('user-a', `c${'a'.repeat(24)}`)).toBe(true);
+ });
+
it('atomically reconnects an unchanged server record and clears its false opt-out', () => {
const { ledger } = harness();
ledger.upsertInstallation(record({ rawManifestSha256: 'd'.repeat(64) }));
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 9568b5d1bf..7adbb20ddd 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -12,6 +12,7 @@ import {
type GhostInstallApproval,
type GhostManifest,
type GhostTrustInfo,
+ type InstalledGhost,
} from '../../../shared/ghost.js';
const runtime = vi.hoisted(() => ({
ghosts: [] as Array<{
@@ -31,12 +32,21 @@ const runtime = vi.hoisted(() => ({
runningErrand: false,
cindyWork: false,
generatedInstallDirs: [] as string[],
+ installOrigins: new Map<string, 'manual' | 'agent-forge'>(),
+ installOriginError: false,
+ currentOrganization: null as {
+ organizationId: string;
+ pluginPrefix: string | null;
+ } | null,
boundaryPending: false,
- approvedInstallEvidence: vi.fn(() => null as {
+ approvedInstallEvidence: vi.fn(
+ () =>
+ null as {
packageSha256: string | null;
approvedManifest: GhostManifest;
legacyMigrated: boolean;
- } | null),
+ } | null,
+ ),
pluginApiBaseUrl: 'https://plugin.test.invalid' as string | null,
session: {
mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
@@ -104,6 +114,10 @@ vi.mock('../../cindy-brain/index.js', () => ({
}),
approvedInstallEvidence: runtime.approvedInstallEvidence,
inspect: runtime.inspect,
+ readApprovedInstallOriginStrict: (ghostId: string) => {
+ if (runtime.installOriginError) throw new Error('receipt unreadable');
+ return runtime.installOrigins.get(ghostId) ?? 'manual';
+ },
}),
isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),
installOrUpdateMarketGhostPackage: async (
@@ -171,7 +185,7 @@ import {
legacyNoSlotsGhostManifestDigest,
type PluginMarketInstallationRecord,
} from '../ledger';
-import { PluginMarketService } from '../service';
+import { organizationDefaultTakeoverEligibility, PluginMarketService } from '../service';
import type { PluginMarketApi } from '../api';
import { createOrganizationPrefixStore } from '../organizationPrefixStore';
@@ -203,6 +217,9 @@ afterEach(() => {
for (const dir of runtime.generatedInstallDirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
+ runtime.installOrigins.clear();
+ runtime.installOriginError = false;
+ runtime.currentOrganization = null;
runtime.boundaryPending = false;
runtime.approvedInstallEvidence.mockReset();
runtime.approvedInstallEvidence.mockReturnValue(null);
@@ -354,13 +371,11 @@ function harness(items: VisiblePluginSummary[], removals: PluginRemovalNotice[]
roots.push(root);
const ledger = new PluginMarketLedger(path.join(root, 'ledger.json'));
const api = {
- listAll: vi.fn(
- async (): Promise<Awaited<ReturnType<PluginMarketApi['listAll']>>> => ({
+ listAll: vi.fn(async (): Promise<Awaited<ReturnType<PluginMarketApi['listAll']>>> => ({
plugins: items,
removals,
- currentOrganization: null,
- }),
- ),
+ currentOrganization: runtime.currentOrganization,
+ })),
detail: vi.fn(async (pluginId: string): Promise<VisiblePluginDetail> => {
const item = items.find((candidate) => candidate.id === pluginId);
if (!item) throw new Error('not found');
@@ -1014,11 +1029,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-recovery-'));
roots.push(installDir);
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: canonicalManifest as unknown as Record<string, unknown>,
dir: installDir,
enabled: false,
- }];
+ },
+ ];
runtime.approvedInstallEvidence.mockReturnValue({
packageSha256: item.currentRelease.sha256,
approvedManifest: canonicalManifest,
@@ -1069,11 +1086,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-org-recovery-'));
roots.push(installDir);
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: canonicalManifest as unknown as Record<string, unknown>,
dir: installDir,
enabled: true,
- }];
+ },
+ ];
runtime.approvedInstallEvidence.mockReturnValue({
packageSha256: item.currentRelease.sha256,
approvedManifest: canonicalManifest,
@@ -1168,9 +1187,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
it.each([
{ receiptCase: 'missing', receiptSha: null },
{ receiptCase: 'different', receiptSha: 'f'.repeat(64) },
- ])('keeps a disconnected market route detached when its receipt hash is $receiptCase', async ({
- receiptSha,
- }) => {
+ ])(
+ 'keeps a disconnected market route detached when its receipt hash is $receiptCase',
+ async ({ receiptSha }) => {
const canonicalManifest = normalizedManifest(manifest());
const item = summary({
currentRelease: {
@@ -1181,11 +1200,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-mismatch-'));
roots.push(installDir);
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: canonicalManifest as unknown as Record<string, unknown>,
dir: installDir,
enabled: true,
- }];
+ },
+ ];
runtime.approvedInstallEvidence.mockReturnValue(
receiptSha === null
? null
@@ -1216,7 +1237,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(snapshot.items[0]?.installState).toBe('conflict');
expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);
expect(runtime.install).not.toHaveBeenCalled();
- });
+ },
+ );
it('reconnects an explicitly migrated legacy receipt whose approved manifest is unchanged', async () => {
const canonicalManifest = normalizedManifest(manifest());
@@ -1229,11 +1251,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-legacy-recovery-'));
roots.push(installDir);
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: canonicalManifest as unknown as Record<string, unknown>,
dir: installDir,
enabled: true,
- }];
+ },
+ ];
runtime.approvedInstallEvidence.mockReturnValue({
packageSha256: null,
approvedManifest: canonicalManifest,
@@ -1281,11 +1305,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
path.join(installDir, 'ghost.json'),
JSON.stringify({ ...canonicalManifest, description: 'changed after migration' }),
);
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: canonicalManifest as unknown as Record<string, unknown>,
dir: installDir,
enabled: true,
- }];
+ },
+ ];
runtime.approvedInstallEvidence.mockReturnValue({
packageSha256: null,
approvedManifest: canonicalManifest,
@@ -1318,11 +1344,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-legacy-unresolved-'));
roots.push(installDir);
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: canonicalManifest as unknown as Record<string, unknown>,
dir: installDir,
enabled: true,
- }];
+ },
+ ];
const h = harness([item]);
h.ledger.upsertInstallation({
pluginId: item.id,
@@ -1555,9 +1583,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
dir: '/userData/cindy-brain/cindy-test',
enabled: true,
});
- await expect(
- h.service.install(item.id, reviewedInstallOptions(item)),
- ).resolves.toMatchObject({ ghost: { manifest: { id: 'cindy-test' } } });
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({
+ ghost: { manifest: { id: 'cindy-test' } },
+ });
expect(runtime.install).toHaveBeenCalledTimes(1);
});
@@ -1867,7 +1895,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
publisherName: 'Cindy Plugin Market',
}),
);
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: rawManifest,
dir: installDir,
enabled: true,
@@ -1877,7 +1906,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
publisherVerified: false,
reviewed: false,
},
- }];
+ },
+ ];
const h = harness([item]);
const digest = ghostManifestDigest(rawManifest);
h.ledger.upsertInstallation({
@@ -1977,7 +2007,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
publisherName: 'Cindy Plugin Market',
}),
);
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: rawManifest,
dir: installDir,
enabled: true,
@@ -1988,7 +2019,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
reviewed: true,
publisherName: 'Cindy Plugin Market',
},
- }];
+ },
+ ];
const h = harness([item]);
h.ledger.upsertInstallation({
pluginId: item.id,
@@ -2013,10 +2045,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
it('Host receipt 已可信但目录镜像缺失时仍回填旧版兼容 trust', async () => {
const item = summary({ ghostId: 'cindy-github' });
const rawManifest = manifest('cindy-github');
- const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-github-mirror-missing-'));
+ const installDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'cindy-market-github-mirror-missing-'),
+ );
roots.push(installDir);
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));
- runtime.ghosts = [{
+ runtime.ghosts = [
+ {
manifest: rawManifest,
dir: installDir,
enabled: true,
@@ -2027,7 +2062,8 @@ describe('PluginMarketService migration and defaultInstall', () => {
reviewed: true,
publisherName: 'Cindy Plugin Market',
},
- }];
+ },
+ ];
const h = harness([item]);
h.ledger.upsertInstallation({
pluginId: item.id,
@@ -2711,6 +2747,49 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install).toHaveBeenCalledTimes(2);
});
+ it('keeps automatic-upgrade approval drift on the existing failure/backoff path', async () => {
+ const item = summary({
+ scope: 'organization',
+ organizationId: 'org-1',
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ const oldManifest = manifest(item.ghostId, '1.0.0');
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-receipt-race-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
+ runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
+ h.api.download.mockImplementationOnce(async () => {
+ runtime.ghosts[0]!.approval = {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ };
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: item.currentRelease.sha256,
+ sizeBytes: item.currentRelease.sizeBytes,
+ };
+ });
+
+ await h.service.snapshot();
+ await h.service.snapshot();
+
+ expect(h.api.detail).toHaveBeenCalledTimes(1);
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ releaseId: 'release-1',
+ installed: true,
+ });
+ });
+
it('abandons a silent upgrade before download when the installed route digest changes', async () => {
const item = summary({
scope: 'organization',
@@ -3582,6 +3661,48 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
});
+ it('keeps a manual market replacement receipt race as PRECONDITION_FAILED without retrying', async () => {
+ const item = summary();
+ const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-manual-replace-race-'));
+ roots.push(installedDir);
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(manifest()));
+ runtime.ghosts = [
+ {
+ manifest: manifest(),
+ dir: installedDir,
+ enabled: true,
+ approval: {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ },
+ ];
+ const h = harness([item]);
+ h.api.download.mockImplementationOnce(async () => {
+ runtime.ghosts[0]!.approval = {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ };
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: item.currentRelease.sha256,
+ sizeBytes: item.currentRelease.sizeBytes,
+ };
+ });
+
+ await expect(
+ h.service.install(item.id, {
+ ...reviewedInstallOptions(item, true),
+ expectedInstalledApproval: APPROVED_INSTALL_TOKEN,
+ }),
+ ).rejects.toThrow('[PRECONDITION_FAILED]');
+
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
+ });
+
it('does not overwrite a local plugin that appears while an official package downloads', async () => {
const item = summary();
const h = harness([item]);
@@ -3867,7 +3988,864 @@ function recordForTest(
};
}
-describe('market detail 响应身份绑定', () => {
+function organizationDefaultSummary(
+ overrides: Partial<VisiblePluginSummary> = {},
+): VisiblePluginSummary {
+ return summary({
+ ghostId: 'acme-tool',
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
+ ...overrides,
+ });
+}
+
+function setCurrentOrganization(pluginPrefix: string | null = 'acme'): void {
+ runtime.currentOrganization = { organizationId: 'org-1', pluginPrefix };
+}
+
+function installRuntimeGhost(
+ rawManifest: Record<string, unknown>,
+ options: {
+ enabled?: boolean;
+ approval?: GhostInstallApproval;
+ origin?: 'manual' | 'agent-forge';
+ } = {},
+): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-org-default-takeover-'));
+ roots.push(dir);
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(rawManifest));
+ runtime.ghosts = [
+ {
+ manifest: rawManifest,
+ dir,
+ enabled: options.enabled ?? true,
+ ...(options.approval ? { approval: options.approval } : {}),
+ },
+ ];
+ runtime.installOrigins.set(rawManifest.id as string, options.origin ?? 'manual');
+ return dir;
+}
+
+describe('organization default Plugin takeover', () => {
+ it('re-downloads and replaces a same-release bad target record without writing opt-out', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const localManifest = { ...manifest(item.ghostId), description: 'Local package' };
+ const dir = installRuntimeGhost(localManifest, { enabled: false });
+ fs.writeFileSync(path.join(dir, 'settings.json'), '{"kept":true}');
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ manifestDigest: ghostManifestDigest(manifest(item.ghostId)),
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: true });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: false };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ const snapshot = await h.service.snapshot();
+
+ expect(h.api.detail).toHaveBeenCalledWith(item.id);
+ expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: false });
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ source: 'market',
+ releaseId: item.currentRelease.id,
+ manifestDigest: ghostManifestDigest(manifest(item.ghostId)),
+ });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ expect(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')).toBe('{"kept":true}');
+ });
+
+ it('restarts one same-release takeover from fresh facts after a local update supersedes its receipt', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const firstLocalManifest = { ...manifest(item.ghostId), description: 'First local package' };
+ const dir = installRuntimeGhost(firstLocalManifest, {
+ enabled: false,
+ approval: {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ });
+ fs.writeFileSync(path.join(dir, 'settings.json'), '{"kept":true}');
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ manifestDigest: ghostManifestDigest(manifest(item.ghostId)),
+ });
+ let downloads = 0;
+ h.api.download.mockImplementation(async () => {
+ downloads += 1;
+ if (downloads === 1) {
+ const replacement = {
+ ...firstLocalManifest,
+ description: 'Concurrent ordinary local update',
+ };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(replacement));
+ runtime.ghosts = [
+ {
+ manifest: replacement,
+ dir,
+ enabled: false,
+ approval: {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ },
+ },
+ ];
+ runtime.installOrigins.set(item.ghostId, 'manual');
+ }
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed: (typeof runtime.ghosts)[number] = {
+ manifest: manifest(item.ghostId),
+ dir,
+ enabled: false,
+ approval: {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000003',
+ },
+ };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ const snapshot = await h.service.snapshot();
+
+ expect(h.api.detail).toHaveBeenCalledTimes(2);
+ expect(h.api.download).toHaveBeenCalledTimes(2);
+ expect(runtime.inspect).toHaveBeenCalledTimes(2);
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: false });
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ releaseId: item.currentRelease.id,
+ source: 'market',
+ manifestDigest: ghostManifestDigest(manifest(item.ghostId)),
+ });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ expect(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')).toBe('{"kept":true}');
+ });
+
+ it('limits one snapshot to two superseded downloads and lets the next snapshot retry immediately', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const dir = installRuntimeGhost(
+ { ...manifest(item.ghostId), description: 'Initial local package' },
+ {
+ approval: {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ },
+ );
+ const h = harness([item]);
+ let downloads = 0;
+ h.api.download.mockImplementation(async () => {
+ downloads += 1;
+ if (downloads <= 2) {
+ const replacement = {
+ ...manifest(item.ghostId),
+ description: `Concurrent local update ${downloads}`,
+ };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(replacement));
+ runtime.ghosts = [
+ {
+ manifest: replacement,
+ dir,
+ enabled: true,
+ approval: {
+ state: 'approved',
+ revision:
+ downloads === 1
+ ? '00000000-0000-4000-8000-000000000002'
+ : '00000000-0000-4000-8000-000000000003',
+ },
+ },
+ ];
+ runtime.installOrigins.set(item.ghostId, 'manual');
+ }
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ const outcomes: Array<'completed' | 'failed'> = [];
+ await h.service.snapshot({
+ onDefaultReconciliationOutcome: (outcome) => outcomes.push(outcome),
+ });
+
+ expect(h.api.detail).toHaveBeenCalledTimes(2);
+ expect(h.api.download).toHaveBeenCalledTimes(2);
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
+ expect(outcomes).toEqual(['failed']);
+
+ await h.service.snapshot();
+
+ expect(h.api.detail).toHaveBeenCalledTimes(3);
+ expect(h.api.download).toHaveBeenCalledTimes(3);
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ installed: true,
+ });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ });
+
+ it('restarts from a fresh not-installed state when the takeover target disappears', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const dir = installRuntimeGhost({ ...manifest(item.ghostId), description: 'Local package' });
+ const h = harness([item]);
+ let downloads = 0;
+ h.api.download.mockImplementation(async () => {
+ downloads += 1;
+ if (downloads === 1) runtime.ghosts = [];
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ await h.service.snapshot();
+
+ expect(h.api.detail).toHaveBeenCalledTimes(2);
+ expect(h.api.download).toHaveBeenCalledTimes(2);
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ installed: true,
+ });
+ });
+
+ it('takes over an approved ordinary local/manual install with no market record', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const dir = installRuntimeGhost({ ...manifest(item.ghostId), description: 'Local package' });
+ const h = harness([item]);
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ await h.service.snapshot();
+
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ installed: true,
+ });
+ });
+
+ it('takes over an ordinary local replacement after its old market route was detached', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const dir = installRuntimeGhost({
+ ...manifest(item.ghostId),
+ description: 'Local replacement',
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item));
+ h.ledger.markRemoved(item.ghostId, null);
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ await h.service.snapshot();
+
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ source: 'market',
+ installed: true,
+ });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ });
+
+ it('keeps a Forge replacement protected after detaching its old market route', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ installRuntimeGhost(
+ { ...manifest(item.ghostId), description: 'Forge replacement' },
+ { origin: 'agent-forge' },
+ );
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item));
+ h.ledger.markRemoved(item.ghostId, null);
+
+ await h.service.snapshot();
+
+ expect(h.api.detail).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ });
+
+ it.each(['git-market', 'local-market'] as const)(
+ 'treats an installed=false %s record as no effective source',
+ async (source) => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const dir = installRuntimeGhost({
+ ...manifest(item.ghostId),
+ description: 'Local replacement',
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({ ...recordForTest(item), source, installed: false });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ await h.service.snapshot();
+
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ source: 'market',
+ installed: true,
+ });
+ },
+ );
+
+ it('keeps an explicit uninstall opt-out ahead of a later same-id local install', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const h = harness([item]);
+ h.ledger.upsertInstallation(recordForTest(item));
+ h.ledger.markRemoved(item.ghostId, 'user-1');
+ installRuntimeGhost({ ...manifest(item.ghostId), description: 'Later local install' });
+
+ await h.service.snapshot();
+
+ expect(h.api.detail).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);
+ });
+
+ it('repairs a same-target market record whose scope route no longer matches', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const installedManifest = manifest(item.ghostId);
+ const dir = installRuntimeGhost(installedManifest);
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ scope: 'public',
+ organizationId: null,
+ manifestDigest: ghostManifestDigest(installedManifest),
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: installedManifest, dir, enabled: true };
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ await h.service.snapshot();
+
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ scope: 'organization',
+ organizationId: 'org-1',
+ });
+ });
+
+ it.each([
+ ['public scope', { summary: { scope: 'public', organizationId: null } }],
+ ['non-default', { summary: { defaultInstall: false } }],
+ ['other organization', { summary: { organizationId: 'org-2' } }],
+ ['missing current organization', { currentOrganizationMissing: true }],
+ ['missing prefix', { prefix: null }],
+ ['invalid prefix', { prefix: 'A' }],
+ ['mismatched prefix', { prefix: 'other' }],
+ ['duplicate ghost id', { uniqueGhostId: false }],
+ ['Forge install', { origin: 'agent-forge' }],
+ ['unapproved install', { approval: { state: 'legacy-unapproved' } }],
+ ['explicit opt-out', { optedOut: true }],
+ ['builtin tombstone', { builtinRemoved: true }],
+ ['busy Plugin', { busy: true }],
+ ] satisfies Array<
+ [
+ string,
+ {
+ summary?: Partial<VisiblePluginSummary>;
+ currentOrganizationMissing?: boolean;
+ prefix?: string | null;
+ uniqueGhostId?: boolean;
+ origin?: 'manual' | 'agent-forge';
+ approval?: GhostInstallApproval;
+ optedOut?: boolean;
+ builtinRemoved?: boolean;
+ busy?: boolean;
+ },
+ ]
+ >)('rejects %s', (_name, overrides) => {
+ const factsOverrides = overrides as {
+ summary?: Partial<VisiblePluginSummary>;
+ currentOrganizationMissing?: boolean;
+ prefix?: string | null;
+ uniqueGhostId?: boolean;
+ origin?: 'manual' | 'agent-forge';
+ approval?: GhostInstallApproval;
+ optedOut?: boolean;
+ builtinRemoved?: boolean;
+ busy?: boolean;
+ };
+ const item = organizationDefaultSummary(factsOverrides.summary ?? {});
+ const installed = {
+ manifest: manifest(item.ghostId),
+ dir: '/not-read-for-local-conflict',
+ enabled: true,
+ approval: factsOverrides.approval ?? {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000001',
+ },
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ } satisfies InstalledGhost;
+ expect(
+ organizationDefaultTakeoverEligibility({
+ summary: item,
+ currentOrganization: factsOverrides.currentOrganizationMissing
+ ? null
+ : {
+ organizationId: 'org-1',
+ pluginPrefix: 'prefix' in factsOverrides ? (factsOverrides.prefix ?? null) : 'acme',
+ },
+ uniqueGhostId: factsOverrides.uniqueGhostId ?? true,
+ installed,
+ record: null,
+ installOrigin: factsOverrides.origin ?? 'manual',
+ runtimeAvailable: true,
+ optedOut: factsOverrides.optedOut ?? false,
+ builtinRemoved: factsOverrides.builtinRemoved ?? false,
+ busy: factsOverrides.busy ?? false,
+ }).eligible,
+ ).toBe(false);
+ });
+
+ it.each([
+ ['custom git market', 'git-market', PLUGIN_ID, 'organization', 'org-1'],
+ ['custom local market', 'local-market', PLUGIN_ID, 'organization', 'org-1'],
+ ['public market', 'market', `c${'d'.repeat(24)}`, 'public', null],
+ ['other organization market', 'market', `c${'e'.repeat(24)}`, 'organization', 'org-2'],
+ ] as const)('protects an existing %s route', (_name, source, pluginId, scope, organizationId) => {
+ const item = organizationDefaultSummary();
+ const installed = {
+ manifest: manifest(item.ghostId),
+ dir: '/not-read-for-protected-route',
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ } satisfies InstalledGhost;
+ expect(
+ organizationDefaultTakeoverEligibility({
+ summary: item,
+ currentOrganization: { organizationId: 'org-1', pluginPrefix: 'acme' },
+ uniqueGhostId: true,
+ installed,
+ record: { ...recordForTest(item), pluginId, source, scope, organizationId },
+ installOrigin: 'manual',
+ runtimeAvailable: true,
+ optedOut: false,
+ builtinRemoved: false,
+ busy: false,
+ }).eligible,
+ ).toBe(false);
+ });
+
+ it('skips busy work without backoff and retries after it becomes idle', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const dir = installRuntimeGhost({ ...manifest(item.ghostId), description: 'Local package' });
+ const h = harness([item]);
+ runtime.pendingCalls = true;
+ await h.service.snapshot();
+ expect(h.api.detail).not.toHaveBeenCalled();
+
+ runtime.pendingCalls = false;
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['detail', 'download', 'inspect'] as const)(
+ 'keeps service backoff for a real %s failure',
+ async (failurePoint) => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ installRuntimeGhost({ ...manifest(item.ghostId), description: 'Local package' });
+ const h = harness([item]);
+ if (failurePoint === 'detail') {
+ h.api.detail.mockRejectedValue(new Error('detail unavailable'));
+ } else if (failurePoint === 'download') {
+ h.api.download.mockRejectedValue(new Error('download unavailable'));
+ } else {
+ runtime.inspect.mockRejectedValue(new Error('package validation failed'));
+ }
+
+ await h.service.snapshot();
+ await h.service.snapshot();
+
+ expect(h.api.detail).toHaveBeenCalledTimes(1);
+ expect(h.api.download).toHaveBeenCalledTimes(failurePoint === 'detail' ? 0 : 1);
+ expect(runtime.inspect).toHaveBeenCalledTimes(failurePoint === 'inspect' ? 1 : 0);
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
+ },
+ );
+
+ it('backs off the same failed release, retries a new release, and clears after success', async () => {
+ setCurrentOrganization();
+ const items = [organizationDefaultSummary()];
+ const dir = installRuntimeGhost({
+ ...manifest(items[0].ghostId),
+ description: 'Local package',
+ });
+ const h = harness(items);
+ runtime.install.mockRejectedValueOnce(new Error('placement failed'));
+
+ await h.service.snapshot();
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+
+ items[0] = organizationDefaultSummary({
+ currentRelease: { ...items[0].currentRelease, id: 'release-2', version: '2.0.0' },
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(items[0].ghostId, '2.0.0'), dir, enabled: true };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+ await h.service.snapshot();
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledTimes(2);
+ });
+
+ it('continues taking over other defaults when one Plugin fails', async () => {
+ setCurrentOrganization();
+ const first = organizationDefaultSummary();
+ const second = organizationDefaultSummary({
+ id: `c${'f'.repeat(24)}`,
+ ghostId: 'acme-other',
+ });
+ installRuntimeGhost({ ...manifest(first.ghostId), description: 'First local package' });
+ const secondDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-org-default-takeover-'));
+ roots.push(secondDir);
+ const secondLocalManifest = {
+ ...manifest(second.ghostId),
+ description: 'Second local package',
+ };
+ fs.writeFileSync(path.join(secondDir, 'ghost.json'), JSON.stringify(secondLocalManifest));
+ runtime.ghosts.push({
+ manifest: secondLocalManifest,
+ dir: secondDir,
+ enabled: true,
+ });
+ runtime.installOrigins.set(second.ghostId, 'manual');
+ const h = harness([first, second]);
+ runtime.install
+ .mockRejectedValueOnce(new Error('first placement failed'))
+ .mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(second.ghostId), dir: secondDir, enabled: true };
+ fs.writeFileSync(path.join(secondDir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = runtime.ghosts.map((ghost) =>
+ ghost.manifest.id === second.ghostId ? installed : ghost,
+ );
+ return installed;
+ });
+
+ await h.service.snapshot();
+
+ expect(runtime.install).toHaveBeenCalledTimes(2);
+ expect(h.ledger.installationForGhost(first.ghostId)).toBeNull();
+ expect(h.ledger.installationForGhost(second.ghostId)).toMatchObject({
+ pluginId: second.id,
+ installed: true,
+ });
+ });
+
+ it('refuses a Forge switch during download without changing package, ledger, or opt-out', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const localManifest = { ...manifest(item.ghostId), description: 'Local package' };
+ const dir = installRuntimeGhost(localManifest);
+ const h = harness([item]);
+ const downloadStarted = deferred();
+ const downloadGate = deferred();
+ h.api.download.mockImplementationOnce(async () => {
+ downloadStarted.resolve();
+ await downloadGate.promise;
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ throw new Error('must stop before placement');
+ });
+
+ const snapshot = h.service.snapshot();
+ await downloadStarted.promise;
+ runtime.ghosts = runtime.ghosts.map((ghost) => ({
+ ...ghost,
+ approval: {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ },
+ }));
+ runtime.installOrigins.set(item.ghostId, 'agent-forge');
+ downloadGate.resolve();
+ await snapshot;
+
+ expect(h.api.detail).toHaveBeenCalledTimes(1);
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(fs.readFileSync(path.join(dir, 'ghost.json'), 'utf8')).toBe(
+ JSON.stringify(localManifest),
+ );
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ });
+
+ it('keeps a download-time explicit opt-out and stops before package placement', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const localManifest = { ...manifest(item.ghostId), description: 'Local package' };
+ const dir = installRuntimeGhost(localManifest);
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ manifestDigest: ghostManifestDigest(manifest(item.ghostId)),
+ });
+ const downloadStarted = deferred();
+ const downloadGate = deferred();
+ h.api.download.mockImplementationOnce(async () => {
+ downloadStarted.resolve();
+ await downloadGate.promise;
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ throw new Error('must stop before placement');
+ });
+
+ const snapshot = h.service.snapshot();
+ await downloadStarted.promise;
+ h.ledger.markRemoved(item.ghostId, 'user-1');
+ downloadGate.resolve();
+ await snapshot;
+
+ expect(h.api.detail).toHaveBeenCalledTimes(1);
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+ expect(fs.readFileSync(path.join(dir, 'ghost.json'), 'utf8')).toBe(
+ JSON.stringify(localManifest),
+ );
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);
+ });
+
+ it('does not retry when a protected custom-market route appears during download', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const localManifest = { ...manifest(item.ghostId), description: 'Local package' };
+ const dir = installRuntimeGhost(localManifest);
+ const h = harness([item]);
+ h.api.download.mockImplementationOnce(async () => {
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ source: 'git-market',
+ manifestDigest: ghostManifestDigest(localManifest),
+ });
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+ let packagePlaced = false;
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ packagePlaced = true;
+ throw new Error('must stop before placement');
+ });
+
+ await h.service.snapshot();
+
+ expect(h.api.detail).toHaveBeenCalledTimes(1);
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(packagePlaced).toBe(false);
+ expect(fs.readFileSync(path.join(dir, 'ghost.json'), 'utf8')).toBe(
+ JSON.stringify(localManifest),
+ );
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ source: 'git-market',
+ installed: true,
+ });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ });
+
+ it('does not classify an owner generation change as a superseded takeover retry', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ installRuntimeGhost({ ...manifest(item.ghostId), description: 'Local package' });
+ const h = harness([item]);
+ h.api.download.mockImplementationOnce(async () => {
+ runtime.session = {
+ mode: 'cloud',
+ dataOwnerId: 'user-1',
+ generation: 2,
+ };
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+
+ await expect(h.service.snapshot()).rejects.toThrow(/session|owner|changed/i);
+
+ expect(h.api.detail).toHaveBeenCalledTimes(1);
+ expect(h.api.download).toHaveBeenCalledTimes(1);
+ expect(runtime.install).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
+ });
+
+ it('does not downgrade an install-origin read failure to replaceable manual', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ installRuntimeGhost({ ...manifest(item.ghostId), description: 'Local package' });
+ runtime.installOriginError = true;
+ const h = harness([item]);
+
+ await h.service.snapshot();
+
+ expect(h.api.detail).not.toHaveBeenCalled();
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('does not write opt-out when ledger persistence fails after package placement and converges later', async () => {
+ setCurrentOrganization();
+ const item = organizationDefaultSummary();
+ const dir = installRuntimeGhost({ ...manifest(item.ghostId), description: 'Local package' });
+ const h = harness([item]);
+ const upsert = vi.spyOn(h.ledger, 'upsertInstallation').mockImplementationOnce(() => {
+ throw new Error('ledger unavailable');
+ });
+ runtime.install.mockImplementation(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ const installed = { manifest: manifest(item.ghostId), dir, enabled: true };
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(installed.manifest));
+ runtime.ghosts = [installed];
+ return installed;
+ });
+
+ await h.service.snapshot();
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
+ await h.service.snapshot();
+ expect(runtime.install).toHaveBeenCalledTimes(1);
+
+ upsert.mockRestore();
+ // 新的 service 模拟进程重启,进程内退避自然清空;同 release 必须重新下载收敛。
+ const restarted = new PluginMarketService(h.api as unknown as PluginMarketApi, h.ledger);
+ await restarted.snapshot();
+ expect(runtime.install).toHaveBeenCalledTimes(2);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: true });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ });
+});
+
+describe('market detail 响应身份绑定', () => {
+ it('rejects a detail response that changes the default-install policy', async () => {
+ const item = organizationDefaultSummary();
+ const h = harness([item]);
+ h.api.detail.mockImplementationOnce(async () => detail({ ...item, defaultInstall: false }));
+
+ await h.service.snapshot();
+
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
it('detail 自报的 id/ghostId 与请求不一致 → 拒,不把 A 的确认导向 B 的内容', async () => {
const item = summary();
const h = harness([item]);
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 771d0e7c87..4aff900ce2 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -4,6 +4,7 @@ import crypto from 'node:crypto';
import {
isValidPluginResourceId,
+ PLUGIN_PREFIX_PATTERN,
type PluginCurrentOrganization,
type PluginRemovalNotice,
type VisiblePluginDetail,
@@ -101,6 +102,7 @@ const log = createLogger('plugin-market');
class SilentUpgradeBusyError extends Error {}
class SilentDefaultInstallCancelledError extends Error {}
+class SilentOrganizationDefaultTakeoverSupersededError extends Error {}
/**
* 来源增删改的互斥键。自定义市场安装的提交段也要拿这把锁,保证所选来源从
@@ -216,6 +218,7 @@ function assertDetailMatchesSummary(
detail.ghostId !== summary.ghostId ||
detail.scope !== summary.scope ||
detail.organizationId !== summary.organizationId ||
+ detail.defaultInstall !== summary.defaultInstall ||
detail.currentRelease.id !== summary.currentRelease.id ||
detail.currentRelease.version !== summary.currentRelease.version ||
detail.currentRelease.sha256 !== summary.currentRelease.sha256 ||
@@ -225,6 +228,63 @@ function assertDetailMatchesSummary(
}
}
+type ServerSourceReplacementMode =
+ 'preserve-existing-source' | 'user-requested-source-change' | 'organization-default-takeover';
+
+interface OrganizationDefaultTakeoverFacts {
+ summary: VisiblePluginSummary;
+ currentOrganization: PluginCurrentOrganization | null | undefined;
+ uniqueGhostId: boolean;
+ installed: InstalledGhost;
+ record: PluginMarketInstallationRecord | null;
+ installOrigin: 'manual' | 'agent-forge';
+ runtimeAvailable: boolean;
+ optedOut: boolean;
+ builtinRemoved: boolean;
+ busy: boolean;
+}
+
+/** 当前组织默认插件能否接管既有同 id 安装;只消费调用方已经重读的本地事实。 */
+export function organizationDefaultTakeoverEligibility(
+ facts: OrganizationDefaultTakeoverFacts,
+): { eligible: true } | { eligible: false; reason: string } {
+ const { summary, currentOrganization, installed, record } = facts;
+ const prefix = currentOrganization?.pluginPrefix;
+ if (
+ !summary.defaultInstall ||
+ summary.scope !== 'organization' ||
+ !currentOrganization ||
+ summary.organizationId !== currentOrganization.organizationId ||
+ typeof prefix !== 'string' ||
+ !PLUGIN_PREFIX_PATTERN.test(prefix) ||
+ !summary.ghostId.startsWith(`${prefix}-`)
+ ) {
+ return { eligible: false, reason: 'not-current-organization-default' };
+ }
+ if (!facts.uniqueGhostId) return { eligible: false, reason: 'duplicate-ghost-id' };
+ if (!facts.runtimeAvailable) return { eligible: false, reason: 'runtime-unavailable' };
+ if (facts.optedOut) return { eligible: false, reason: 'explicit-opt-out' };
+ if (facts.builtinRemoved) return { eligible: false, reason: 'builtin-tombstone' };
+ if (facts.busy) return { eligible: false, reason: 'busy' };
+ if (installed.approval.state !== 'approved') {
+ return { eligible: false, reason: 'unapproved-install' };
+ }
+ if (facts.installOrigin === 'agent-forge') {
+ return { eligible: false, reason: 'forge-install' };
+ }
+ if (!record || !record.installed) return { eligible: true };
+ if (
+ record.installed &&
+ record.pluginId === summary.id &&
+ (record.source === 'market' || record.source === 'legacy-adopted') &&
+ (!serverRecordMatchesInstalledGhost(summary.id, installed, record) ||
+ !serverRecordMatchesSummaryRoute(summary, record))
+ ) {
+ return { eligible: true };
+ }
+ return { eligible: false, reason: 'protected-source' };
+}
+
/**
* Claims a trusted legacy install without pretending its bytes came from the
* current market release. A synthetic release id keeps the local version
@@ -444,6 +504,20 @@ function serverRecordMatchesInstalledGhost(
);
}
+/** 账本是否仍指向当前服务端目录项;release 变化是升级,不属于路由漂移。 */
+function serverRecordMatchesSummaryRoute(
+ plugin: VisiblePluginSummary,
+ record: PluginMarketInstallationRecord | null,
+): boolean {
+ return Boolean(
+ record &&
+ record.pluginId === plugin.id &&
+ record.ghostId === plugin.ghostId &&
+ record.scope === plugin.scope &&
+ record.organizationId === plugin.organizationId,
+ );
+}
+
function canBackfillOfficialCindyGithubTrust(
record: PluginMarketInstallationRecord,
installed: InstalledGhost,
@@ -453,10 +527,7 @@ function canBackfillOfficialCindyGithubTrust(
record.source === 'market' &&
record.manifestDigest !== undefined &&
installed.approval.state === 'approved' &&
- (
- !isCindyOfficialTrustInfo(installed.trust) ||
- !hasCindyOfficialTrustMetadata(installed.dir)
- ) &&
+ (!isCindyOfficialTrustInfo(installed.trust) || !hasCindyOfficialTrustMetadata(installed.dir)) &&
serverRecordMatchesInstalledGhost(record.pluginId, installed, record)
);
}
@@ -558,7 +629,7 @@ export class PluginMarketService {
private automaticUpgradeRetryKey(
owner: ActiveAppSession,
- source: 'server' | 'custom',
+ source: 'server' | 'custom' | 'organization-default',
pluginId: string,
): string {
return [owner.mode, owner.dataOwnerId, source, pluginId].join('\u0000');
@@ -720,7 +791,9 @@ export class PluginMarketService {
// 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。
let completed = true;
try {
- if (!(await this.applyDefaultInstalls(plugins, owner, ledger))) completed = false;
+ if (!(await this.applyDefaultInstalls(plugins, currentOrganization, owner, ledger))) {
+ completed = false;
+ }
} catch (error) {
completed = false;
log.warn('default plugin install reconciliation failed', {
@@ -1076,7 +1149,10 @@ export class PluginMarketService {
...(options.expectedInstalledApproval !== undefined
? { expectedInstalledApproval: options.expectedInstalledApproval }
: {}),
- allowSourceReplacement: options.allowSourceReplacement === true,
+ sourceReplacementMode:
+ options.allowSourceReplacement === true
+ ? 'user-requested-source-change'
+ : 'preserve-existing-source',
},
owner,
ledger,
@@ -1324,10 +1400,7 @@ export class PluginMarketService {
if (
ghostInstallApprovalToken(installedNow.approval) !== options.expectedInstalledApproval
) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin approval state changed during the update',
- );
+ throwIpcError('PRECONDITION_FAILED', 'Plugin approval state changed during the update');
}
};
assertCustomApprovalStateUnchanged(existing ?? null);
@@ -1696,8 +1769,8 @@ export class PluginMarketService {
options: {
/** receipt 模型的并发护栏:比对 receipt 派生 token,状态变更即拒(与 main 硬化叠加)。 */
expectedInstalledApproval?: string;
- /** 用户明确点击安装时,允许所选市场包原地替换其它来源的同 id 插件。 */
- allowSourceReplacement?: boolean;
+ /** 是否保留现有来源,或按明确意图切换来源。 */
+ sourceReplacementMode?: ServerSourceReplacementMode;
beforeCommitInLock?: () => void;
/** 发起操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
@@ -1721,9 +1794,18 @@ export class PluginMarketService {
.list()
.find((ghost) => ghost.manifest.id === plugin.ghostId);
const currentRecord = ledger.installationForGhost(plugin.ghostId);
+ const sourceReplacementMode = options.sourceReplacementMode ?? 'preserve-existing-source';
+ if (
+ sourceReplacementMode === 'organization-default-takeover' &&
+ Boolean(existing) !== options.expectedInstalled
+ ) {
+ throw new SilentOrganizationDefaultTakeoverSupersededError(
+ 'Organization default Plugin takeover target presence changed',
+ );
+ }
if (
existing &&
- !options.allowSourceReplacement &&
+ sourceReplacementMode === 'preserve-existing-source' &&
!serverRecordMatchesInstalledGhost(plugin.id, existing, currentRecord)
) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
@@ -1737,6 +1819,11 @@ export class PluginMarketService {
);
}
if (ghostInstallApprovalToken(existing.approval) !== options.expectedInstalledApproval) {
+ if (sourceReplacementMode === 'organization-default-takeover') {
+ throw new SilentOrganizationDefaultTakeoverSupersededError(
+ 'Organization default Plugin takeover target approval changed',
+ );
+ }
throwIpcError('PRECONDITION_FAILED', 'Plugin approval state changed during the update');
}
}
@@ -1778,7 +1865,7 @@ export class PluginMarketService {
...(options.expectedInstalledApproval !== undefined
? { expectedInstalledApproval: options.expectedInstalledApproval }
: {}),
- allowSourceReplacement: options.allowSourceReplacement,
+ sourceReplacementMode,
beforeCommitInLock: options.beforeCommitInLock,
},
owner,
@@ -1796,7 +1883,7 @@ export class PluginMarketService {
plugin: VisiblePluginSummary | VisiblePluginDetail,
options: {
expectedInstalledApproval?: string;
- allowSourceReplacement?: boolean;
+ sourceReplacementMode: ServerSourceReplacementMode;
beforeCommitInLock?: () => void;
expectedInstalled: boolean;
},
@@ -1809,6 +1896,11 @@ export class PluginMarketService {
.find((ghost) => ghost.manifest.id === plugin.ghostId);
const currentRecordNow = ledger.installationForGhost(plugin.ghostId);
if (Boolean(installedNow) !== options.expectedInstalled) {
+ if (options.sourceReplacementMode === 'organization-default-takeover') {
+ throw new SilentOrganizationDefaultTakeoverSupersededError(
+ 'Organization default Plugin takeover target presence changed',
+ );
+ }
throwIpcError(
'PRECONDITION_FAILED',
installedNow
@@ -1818,7 +1910,7 @@ export class PluginMarketService {
}
if (
installedNow &&
- !options.allowSourceReplacement &&
+ options.sourceReplacementMode === 'preserve-existing-source' &&
!serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow)
) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
@@ -1833,6 +1925,11 @@ export class PluginMarketService {
if (
ghostInstallApprovalToken(installedNow.approval) !== options.expectedInstalledApproval
) {
+ if (options.sourceReplacementMode === 'organization-default-takeover') {
+ throw new SilentOrganizationDefaultTakeoverSupersededError(
+ 'Organization default Plugin takeover target approval changed',
+ );
+ }
throwIpcError(
'PRECONDITION_FAILED',
'Plugin approval state changed while the update was downloading',
@@ -1842,7 +1939,7 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
const replacingSource = Boolean(
installedNow &&
- options.allowSourceReplacement &&
+ options.sourceReplacementMode === 'user-requested-source-change' &&
currentRecordNow?.installed &&
!serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow),
);
@@ -1929,7 +2026,9 @@ export class PluginMarketService {
const record = local.installations[plugin.ghostId];
const identity = local.manifestIdentityByGhostId.get(plugin.ghostId) ?? null;
const matchesUpdateRoute = Boolean(
- ghost && serverRecordMatchesInstalledGhost(plugin.id, ghost, record ?? null, identity),
+ ghost
+ && serverRecordMatchesInstalledGhost(plugin.id, ghost, record ?? null, identity)
+ && serverRecordMatchesSummaryRoute(plugin, record ?? null),
);
// 其它同 id 条目不进入自动更新,但仍可由用户显式选择替换。
const conflict = Boolean(ghost && !matchesUpdateRoute);
@@ -2119,18 +2218,18 @@ export class PluginMarketService {
for (const record of records) {
const summary = summariesById.get(record.pluginId);
if (
- record.installed
- || (record.source !== 'market' && record.source !== 'legacy-adopted')
- || !isValidPluginResourceId(record.pluginId)
- || !isValidPluginResourceId(record.releaseId)
- || !isValidGhostId(record.ghostId)
- || !/^[a-f0-9]{64}$/.test(record.sha256)
- || pluginIdCounts.get(record.pluginId) !== 1
- || ghostCounts.get(record.ghostId) !== 1
- || !summary
- || summary.ghostId !== record.ghostId
- || summary.scope !== record.scope
- || summary.organizationId !== record.organizationId
+ record.installed ||
+ (record.source !== 'market' && record.source !== 'legacy-adopted') ||
+ !isValidPluginResourceId(record.pluginId) ||
+ !isValidPluginResourceId(record.releaseId) ||
+ !isValidGhostId(record.ghostId) ||
+ !/^[a-f0-9]{64}$/.test(record.sha256) ||
+ pluginIdCounts.get(record.pluginId) !== 1 ||
+ ghostCounts.get(record.ghostId) !== 1 ||
+ !summary ||
+ summary.ghostId !== record.ghostId ||
+ summary.scope !== record.scope ||
+ summary.organizationId !== record.organizationId
) {
continue;
}
@@ -2151,17 +2250,17 @@ export class PluginMarketService {
.list()
.find((ghost) => ghost.manifest.id === record.ghostId);
if (
- !currentInstalled
- || currentInstalled.approval.state !== 'approved'
- || currentInstalled.manifest.version !== record.version
+ !currentInstalled ||
+ currentInstalled.approval.state !== 'approved' ||
+ currentInstalled.manifest.version !== record.version
) {
return;
}
const approvalEvidence = getGhostManager().approvedInstallEvidence(record.ghostId);
if (!approvalEvidence) return;
if (
- approvalEvidence.packageSha256 !== null
- && approvalEvidence.packageSha256 !== record.sha256
+ approvalEvidence.packageSha256 !== null &&
+ approvalEvidence.packageSha256 !== record.sha256
) {
log.info('disconnected market recovery skipped', {
pluginId: record.pluginId,
@@ -2438,6 +2537,7 @@ export class PluginMarketService {
private async applyDefaultInstalls(
plugins: readonly VisiblePluginSummary[],
+ currentOrganization: PluginCurrentOrganization | null | undefined,
owner: ActiveAppSession,
ledger: PluginMarketLedger,
): Promise<boolean> {
@@ -2455,56 +2555,176 @@ export class PluginMarketService {
if (ledgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)) continue;
if (isBuiltinGhostRemovedByUser(summary.ghostId)) continue;
const state = this.toItem(summary, local).installState;
- if (state !== 'not-installed') continue;
+ if (state !== 'not-installed' && state !== 'conflict') continue;
+ const takeoverRetryKey = this.automaticUpgradeRetryKey(
+ owner,
+ 'organization-default',
+ summary.id,
+ );
+ const releaseKey = summary.currentRelease.id;
+ if (
+ state === 'conflict' &&
+ (isGhostBusy(summary.ghostId) ||
+ this.shouldDeferAutomaticUpgrade(takeoverRetryKey, releaseKey))
+ ) {
+ continue;
+ }
try {
await this.withMutation(summary.id, async () => {
- requireSameMarketOwner(owner);
- const freshLedgerData = ledger.read();
- if (freshLedgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)) {
- return;
- }
- const freshLocal = this.localInstallSnapshot(ledger, freshLedgerData.installations);
- if (this.toItem(summary, freshLocal).installState !== 'not-installed') {
- return;
- }
- const detail = await this.api.detail(summary.id);
- requireSameMarketOwner(owner);
- assertDetailMatchesSummary(summary, detail);
- // 装完即开语义已收敛进市场安装入口本身,这里无需再显式声明。
- await this.installDetail(
- detail,
- {
- expectedInstalled: false,
- // 下载期间用户可能从本地插件页完成显式卸载。最终落位前在
- // ghostId 锁内重读卸载意图,不能让旧 snapshot 把插件装回来。
- beforeCommitInLock: () => {
- const commitLedgerData = ledger.read();
- if (commitLedgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)) {
- throw new SilentDefaultInstallCancelledError(
- 'Default Plugin was explicitly uninstalled',
- );
+ const runFreshTakeoverPass = async (): Promise<void> => {
+ requireSameMarketOwner(owner);
+ const freshLedgerData = ledger.read();
+ if (freshLedgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)) {
+ return;
+ }
+ const freshLocal = this.localInstallSnapshot(ledger, freshLedgerData.installations);
+ const freshState = this.toItem(summary, freshLocal).installState;
+ if (freshState !== 'not-installed' && freshState !== 'conflict') {
+ return;
+ }
+ const freshInstalled = freshLocal.ghostsById.get(summary.ghostId);
+ let expectedInstalledApproval: string | undefined;
+ if (freshState === 'conflict') {
+ if (!freshInstalled) return;
+ // approval 是读取 installOrigin 的前置条件。严格 receipt 读取
+ // 失败必须上抛,不能把异常降级成可接管的 manual。
+ const installOrigin =
+ freshInstalled.approval.state === 'approved'
+ ? getGhostManager().readApprovedInstallOriginStrict(summary.ghostId)
+ : 'manual';
+ const eligibility = organizationDefaultTakeoverEligibility({
+ summary,
+ currentOrganization,
+ uniqueGhostId: uniqueGhostIds.has(summary.ghostId),
+ installed: freshInstalled,
+ record: freshLedgerData.installations[summary.ghostId] ?? null,
+ installOrigin,
+ runtimeAvailable: isGhostAvailableForActiveSession(summary.ghostId),
+ optedOut: Boolean(
+ freshLedgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id),
+ ),
+ builtinRemoved: isBuiltinGhostRemovedByUser(summary.ghostId),
+ busy: isGhostBusy(summary.ghostId),
+ });
+ if (!eligibility.eligible) {
+ if (eligibility.reason === 'busy') {
+ throw new SilentUpgradeBusyError('Plugin is busy');
}
- const commitLocal = this.localInstallSnapshot(
- ledger,
- commitLedgerData.installations,
- );
- if (this.toItem(summary, commitLocal).installState !== 'not-installed') {
- throw new SilentDefaultInstallCancelledError(
- 'Default Plugin install state changed',
+ return;
+ }
+ expectedInstalledApproval = ghostInstallApprovalToken(freshInstalled.approval);
+ }
+ const detail = await this.api.detail(summary.id);
+ requireSameMarketOwner(owner);
+ assertDetailMatchesSummary(summary, detail);
+ // 装完即开语义已收敛进市场安装入口本身,这里无需再显式声明。
+ await this.installDetail(
+ detail,
+ {
+ expectedInstalled: freshState === 'conflict',
+ ...(expectedInstalledApproval ? { expectedInstalledApproval } : {}),
+ sourceReplacementMode:
+ freshState === 'conflict'
+ ? 'organization-default-takeover'
+ : 'preserve-existing-source',
+ // 下载期间用户可能从本地插件页完成显式卸载。最终落位前在
+ // ghostId 锁内重读卸载意图,不能让旧 snapshot 把插件装回来。
+ beforeCommitInLock: () => {
+ requireSameMarketOwner(owner);
+ const commitLedgerData = ledger.read();
+ if (
+ commitLedgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)
+ ) {
+ throw new SilentDefaultInstallCancelledError(
+ 'Default Plugin was explicitly uninstalled',
+ );
+ }
+ const commitLocal = this.localInstallSnapshot(
+ ledger,
+ commitLedgerData.installations,
);
- }
+ if (freshState === 'not-installed') {
+ if (
+ !isGhostAvailableForActiveSession(summary.ghostId) ||
+ isBuiltinGhostRemovedByUser(summary.ghostId) ||
+ this.toItem(summary, commitLocal).installState !== 'not-installed'
+ ) {
+ throw new SilentDefaultInstallCancelledError(
+ 'Default Plugin install state changed',
+ );
+ }
+ return;
+ }
+ const commitInstalled = commitLocal.ghostsById.get(summary.ghostId);
+ if (!commitInstalled || commitInstalled.approval.state !== 'approved') {
+ throw new SilentDefaultInstallCancelledError(
+ 'Default Plugin install state changed',
+ );
+ }
+ const commitOrigin = getGhostManager().readApprovedInstallOriginStrict(
+ summary.ghostId,
+ );
+ const eligibility = organizationDefaultTakeoverEligibility({
+ summary,
+ currentOrganization,
+ uniqueGhostId: uniqueGhostIds.has(summary.ghostId),
+ installed: commitInstalled,
+ record: commitLedgerData.installations[summary.ghostId] ?? null,
+ installOrigin: commitOrigin,
+ runtimeAvailable: isGhostAvailableForActiveSession(summary.ghostId),
+ optedOut: false,
+ builtinRemoved: isBuiltinGhostRemovedByUser(summary.ghostId),
+ busy: isGhostBusy(summary.ghostId),
+ });
+ if (!eligibility.eligible) {
+ if (eligibility.reason === 'busy') {
+ throw new SilentUpgradeBusyError('Plugin is busy');
+ }
+ throw new SilentDefaultInstallCancelledError(
+ `Default Plugin takeover became ineligible: ${eligibility.reason}`,
+ );
+ }
+ },
},
- },
- owner,
- ledger,
- );
+ owner,
+ ledger,
+ );
+ };
+ try {
+ await runFreshTakeoverPass();
+ } catch (error) {
+ if (!(error instanceof SilentOrganizationDefaultTakeoverSupersededError)) {
+ throw error;
+ }
+ // 抢先完成的本地 mutation 已经释放 ghostId 锁;只按最新 receipt、
+ // 来源与账本事实完整重跑一次,不能复用上一轮下载或 eligibility。
+ await runFreshTakeoverPass();
+ }
});
+ if (state === 'conflict') {
+ this.clearAutomaticUpgradeFailure(takeoverRetryKey, releaseKey);
+ }
} catch (error) {
// 单个默认插件失败不拖垮整个市场;下次同步可重试。
- if (!(error instanceof SilentDefaultInstallCancelledError)) {
+ if (error instanceof SilentOrganizationDefaultTakeoverSupersededError) {
+ completed = false;
+ } else if (error instanceof SilentUpgradeBusyError) {
+ completed = false;
+ } else if (!(error instanceof SilentDefaultInstallCancelledError)) {
completed = false;
+ const retry =
+ state === 'conflict'
+ ? this.recordAutomaticUpgradeFailure(takeoverRetryKey, releaseKey)
+ : null;
log.warn('default plugin install failed', {
pluginId: summary.id,
+ ...(retry
+ ? {
+ releaseId: releaseKey,
+ failures: retry.failures,
+ retryAfter: new Date(retry.retryAfter).toISOString(),
+ }
+ : {}),
error: error instanceof Error ? error.message : String(error),
});
}
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 5e669d17bc..1de805db97 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -122,7 +122,15 @@
一致。旧记录缺少 raw 字段时,Host 只能按已发布的 legacy digest 编码核对同一份受限读取
的字节,命中后原地补字段且不改 `updatedAt`;raw 字段已经存在但不匹配时必须 fail closed,
不得用当前目录覆盖基线。`manifestDigest` 保留旧语义供降级客户端读取,不能改写成 raw SHA。
- 任何同 id 来源冲突或目录漂移都不得被自动覆盖,只能由用户显式选择替换来源。
+ 同 id 来源冲突或目录漂移通常不得被自动覆盖,只能由用户显式选择替换来源。唯一受控例外是:
+ 当前组织下发 `defaultInstall`、组织与合法非空前缀都精确匹配、同 ghost id 在目录中唯一时,
+ 可以接管无有效市场来源的普通本地安装,或修复同一目标 `pluginId` 的坏 market / legacy-adopted
+ 记录。接管仍要求现有 receipt 已批准、未显式卸载退订、插件不忙,并在落位前于 ghost id 锁内
+ 重读 owner、来源、批准与退订事实;不得覆盖有效的公开/其它组织市场路由或 Git/本地自定义
+ 市场路由。`ghost_forge_install` 的首装与更新一律记录 `agent-forge`,作为作者本地自测保护,
+ 不进入自动接管;普通 `.cindy` 导入仍是 `manual`,不享受这项保护。自动接管不得复用用户手动
+ 换源的退订语义,不写 `markRemoved` 或 default-install opt-out。普通本地/Forge 换源只把
+ 旧来源记录置为 `installed=false`,不得新增或清除 opt-out;只有用户显式卸载才写 opt-out。
- 所有仍匹配稳定来源的已装插件都静默自动更新,不限 public/organization、也不限
`defaultInstall`。更新保持现有启用状态,不弹成功 toast;插件正有调用、派活或 Cindy
工作时跳过,下一轮重试。服务端市场按客户端版本投影最近发布、曾上架且仍有效的兼容