Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): 修复市场插件 Manifest 身份兼容与无感自愈 (#3509)
GaoWei Liu2d63613c6f02
diff --git a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts b/apps/desktop/src/main/__tests__/installedGhostManifest.test.tsindex 5e3409bd5e..44f127ec8e 100644--- a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts+++ b/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts@@ -1,3 +1,4 @@+import crypto from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -8,6 +9,7 @@ import {parseInstalledGhostManifest,readInstalledGhostManifest,readInstalledGhostManifestDigestFormats,+ readInstalledGhostManifestSnapshot,} from '../installedGhostManifest.js';import { ghostManifestDigest } from '../plugin-market/ledger.js';@@ -133,6 +135,42 @@ describe('installed ghost manifest compatibility', () => {expect(parsed.manifest).not.toHaveProperty('manual');});+ it('hashes the exact bytes read instead of a normalized serialization', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-manifest-sha-'));+ roots.push(root);+ const bytes = Buffer.from(`${JSON.stringify(manifest(), null, 2)}\n`);+ fs.writeFileSync(path.join(root, 'ghost.json'), bytes);++ const result = readInstalledGhostManifestSnapshot(root, 64 * 1024);++ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.snapshot.rawManifestSha256).toBe(+ crypto.createHash('sha256').update(bytes).digest('hex'),+ );+ expect(result.snapshot.rawManifestSha256).not.toBe(+ crypto.createHash('sha256').update(JSON.stringify(result.snapshot.manifest)).digest('hex'),+ );+ });++ it('keeps semantic equality separate from raw-byte identity', () => {+ const rootsForFormats = [+ fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-format-a-')),+ fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-format-b-')),+ ];+ roots.push(...rootsForFormats);+ fs.writeFileSync(path.join(rootsForFormats[0], 'ghost.json'), JSON.stringify(manifest()));+ fs.writeFileSync(path.join(rootsForFormats[1], 'ghost.json'), JSON.stringify(manifest(), null, 2));++ const first = readInstalledGhostManifestSnapshot(rootsForFormats[0], 64 * 1024);+ const second = readInstalledGhostManifestSnapshot(rootsForFormats[1], 64 * 1024);++ expect(first.ok && second.ok).toBe(true);+ if (!first.ok || !second.ok) return;+ expect(first.snapshot.manifest).toEqual(second.snapshot.manifest);+ expect(first.snapshot.rawManifestSha256).not.toBe(second.snapshot.rawManifestSha256);+ });+it('keeps the upgrade-time v2 digest candidate in the original slot order', () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-v2-digest-'));roots.push(root);@@ -154,4 +192,59 @@ describe('installed ghost manifest compatibility', () => {expect(digestCandidates).toContain(ghostManifestDigest(legacy));expect(parsed.manifest).toMatchObject({ notify: true });});++ it.each([+ ['omitted', undefined],+ ['empty', {}],+ ['explicit false', { externalLinks: false }],+ ])('reproduces the v0.1.61 card projection when card is %s', (_label, card) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-v2-card-shape-'));+ roots.push(root);+ const raw = {+ schemaVersion: 2 as const,+ id: 'cindy-card-shape',+ name: 'Card Shape',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['card'],+ ...(card === undefined ? {} : { card }),+ };+ fs.writeFileSync(path.join(root, 'ghost.json'), JSON.stringify(raw));++ const result = readInstalledGhostManifestSnapshot(root, 64 * 1024);++ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.snapshot.releasedLegacyDigestFormat).not.toHaveProperty('card');+ });++ it('keeps only released true-valued card and agent detail fields', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-v2-detail-shape-'));+ roots.push(root);+ const raw = {+ schemaVersion: 2 as const,+ id: 'cindy-detail-shape',+ name: 'Detail Shape',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['card', 'agent'],+ card: { externalLinks: true },+ agent: { background: true, errand: false },+ };+ fs.writeFileSync(path.join(root, 'ghost.json'), JSON.stringify(raw));++ const result = readInstalledGhostManifestSnapshot(root, 64 * 1024);++ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.snapshot.releasedLegacyDigestFormat).toMatchObject({+ card: { externalLinks: true },+ agent: { background: true },+ });+ expect(+ (result.snapshot.releasedLegacyDigestFormat as { agent: Record<string, unknown> }).agent,+ ).not.toHaveProperty('errand');+ });});diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex c049e13389..fa8e0cb904 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -18,6 +18,7 @@ import {ghostInstallApprovalToken,ghostIconMimeType,isValidGhostId,+ ghostManifestToLegacyV2DigestFormat,resolveGhostManifestLocale,validateGhostManifest,validateGhostManifestLocaleResource,@@ -2142,6 +2143,10 @@ export class GhostManager {unsupportedLegacySlots: string[];trust: GhostTrustInfo;packageSha256: string;+ /** SHA-256 of the exact ghost.json entry bytes in this package. */+ rawManifestSha256: string;+ /** Exact normalized shape emitted by the released v0.1.61 v2 validator. */+ releasedLegacyDigestFormat: unknown;iconDataUrl?: string;}| { rejection: InstallRejection }@@ -2154,6 +2159,8 @@ export class GhostManager {unsupportedLegacySlots: parsed.unsupportedLegacySlots,trust: parsed.trust,packageSha256: parsed.packageSha256,+ rawManifestSha256: parsed.rawManifestSha256,+ releasedLegacyDigestFormat: parsed.releasedLegacyDigestFormat,...(parsed.iconDataUrl !== undefined ? { iconDataUrl: parsed.iconDataUrl } : {}),};}@@ -2170,6 +2177,8 @@ export class GhostManager {unsupportedLegacySlots: string[];trust: GhostTrustInfo;packageSha256: string;+ rawManifestSha256: string;+ releasedLegacyDigestFormat: unknown;iconDataUrl?: string;allEntries: JSZip.JSZipObject[];prefix: string;@@ -2274,16 +2283,14 @@ export class GhostManager {// 3) 校验清单let manifestRaw: unknown;+ let manifestBytes: Buffer;try {- manifestRaw = JSON.parse(- (- await readZipEntryBufferWithLimit(- manifestEntry,- MAX_GHOST_MANIFEST_BYTES,- GHOST_MANIFEST_FILE,- )- ).toString('utf8'),+ manifestBytes = await readZipEntryBufferWithLimit(+ manifestEntry,+ MAX_GHOST_MANIFEST_BYTES,+ GHOST_MANIFEST_FILE,);+ manifestRaw = JSON.parse(manifestBytes.toString('utf8'));} catch {return {rejection: { code: 'file-invalid', reason: `${GHOST_MANIFEST_FILE} 不是合法 JSON` },@@ -2555,6 +2562,11 @@ export class GhostManager {unsupportedLegacySlots: v.unsupportedLegacySlots,trust: signature.trust,packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),+ rawManifestSha256: crypto.createHash('sha256').update(manifestBytes).digest('hex'),+ releasedLegacyDigestFormat: ghostManifestToLegacyV2DigestFormat(+ v.manifest,+ manifestRaw,+ ),...(iconDataUrl !== undefined ? { iconDataUrl } : {}),allEntries,prefix,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex a202d8d0c9..8b626881e9 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -4282,6 +4282,45 @@ describe('GhostManager · inspect(只验不装)', () => {expect(onChanged).not.toHaveBeenCalled();});+ it('returns the SHA of the exact ghost.json package entry bytes', async () => {+ const manifestBytes = Buffer.from(`${JSON.stringify(goodManifest(), null, 2)}\n`);+ const zip = new JSZip();+ zip.file('ghost.json', manifestBytes);+ const cindy = path.join(workDir, 'raw-manifest-sha.cindy');+ await fs.promises.writeFile(cindy, await zip.generateAsync({ type: 'nodebuffer' }));++ const inspected = await manager.inspect(cindy);++ expect(inspected).toMatchObject({+ rawManifestSha256: crypto.createHash('sha256').update(manifestBytes).digest('hex'),+ });+ });++ it('returns the released legacy digest shape from the same package entry', async () => {+ const rawManifest = {+ schemaVersion: 2,+ id: 'legacy-card',+ name: 'Legacy Card',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['card'],+ };+ const zip = new JSZip();+ zip.file('ghost.json', JSON.stringify(rawManifest));+ zip.file('main.js', 'export default {};');+ const cindy = path.join(workDir, 'legacy-card.cindy');+ await fs.promises.writeFile(cindy, await zip.generateAsync({ type: 'nodebuffer' }));++ const inspected = await manager.inspect(cindy);++ expect(inspected).toMatchObject({+ releasedLegacyDigestFormat: rawManifest,+ });+ expect((inspected as { releasedLegacyDigestFormat: unknown }).releasedLegacyDigestFormat)+ .not.toHaveProperty('card');+ });+it('本地化展示清单与包内 canonical 清单分离', async () => {hostLocale = 'zh-CN';const base = {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.tsindex 85422a1996..43775ffffd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import type { GhostManifest } from '../../../shared/ghost.js';import {ghostManifestDigest,@@ -53,6 +53,7 @@ const marketInstallation: PluginMarketInstallationRecord = {installed: true,updatedAt: '2026-08-04T00:00:00.000Z',manifestDigest: ghostManifestDigest(manifest),+ rawManifestSha256: ghostManifestDigest(manifest),};function resolverOptions(@@ -60,9 +61,15 @@ function resolverOptions(installation: PluginMarketInstallationRecord | null = marketInstallation,) {return {- readInstalledManifest: () => installedManifest,- readInstalledManifestDigest: () =>- installedManifest ? ghostManifestDigest(installedManifest) : null,+ readInstalledManifestIdentity: () =>+ installedManifest+ ? {+ manifest: installedManifest,+ rawManifestSha256: ghostManifestDigest(installedManifest),+ legacyManifestDigest: ghostManifestDigest(installedManifest),+ legacyManifestDigests: [ghostManifestDigest(installedManifest)],+ }+ : null,readMarketInstallation: () => installation,};}@@ -86,6 +93,19 @@ describe('installed Plugin Connection audience resolver', () => {});});+ it('reads the installed manifest and byte identity only once', () => {+ const readInstalledManifestIdentity = vi.fn(+ resolverOptions().readInstalledManifestIdentity,+ );+ const resolver = loadConnectionAudienceResolver({+ ...resolverOptions(),+ readInstalledManifestIdentity,+ });++ expect(resolver.resolve('plugin-a', identity)).not.toBeNull();+ expect(readInstalledManifestIdentity).toHaveBeenCalledTimes(1);+ });+it('requires a current organization market installation record', () => {const resolver = loadConnectionAudienceResolver(resolverOptions(manifest, { ...marketInstallation, source: 'local-market' }),@@ -109,17 +129,40 @@ describe('installed Plugin Connection audience resolver', () => {).toBeNull();expect(loadConnectionAudienceResolver(- resolverOptions(manifest, { ...marketInstallation, manifestDigest: undefined }),+ resolverOptions(manifest, {+ ...marketInstallation,+ manifestDigest: undefined,+ rawManifestSha256: undefined,+ }),).resolve('plugin-a', identity),).toBeNull();});+ it('uses raw manifest bytes when the legacy digest is absent', () => {+ const resolver = loadConnectionAudienceResolver(+ resolverOptions(manifest, { ...marketInstallation, manifestDigest: undefined }),+ );++ expect(resolver.resolve('plugin-a', identity)).not.toBeNull();+ });+it('rejects a changed installed manifest digest', () => {const changedManifest = { ...manifest, version: '2.0.0' };const resolver = loadConnectionAudienceResolver(resolverOptions(changedManifest));expect(resolver.resolve('plugin-a', identity)).toBeNull();});+ it('does not fall back to a matching legacy digest after raw identity mismatches', () => {+ const resolver = loadConnectionAudienceResolver(+ resolverOptions(manifest, {+ ...marketInstallation,+ rawManifestSha256: 'f'.repeat(64),+ }),+ );++ expect(resolver.resolve('plugin-a', identity)).toBeNull();+ });+it('rejects reserved publisher identity slugs even with a matching market install', () => {for (const ghostId of ['cindy-publisher', 'xd-publisher'] as const) {const reservedManifest = { ...manifest, id: ghostId };diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsindex 40df8838f8..f52148c8bd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@ -41,10 +41,10 @@ describe('market Ghost session boundary', () => {'beforePackagePlacement: () => {\n requireSameMarketOwner(owner);',);expect(installBody).toContain(- 'afterCommit: async (_installed, packagedManifest) => {',+ 'afterCommit: async (_installed, _packagedManifest, evidence) => {',);const afterCommitStart = installBody.indexOf(- 'afterCommit: async (_installed, packagedManifest) => {',+ 'afterCommit: async (_installed, _packagedManifest, evidence) => {',);const afterCommitEnd = installBody.indexOf('\n },\n }).catch', afterCommitStart);const afterCommitBody = installBody.slice(afterCommitStart, afterCommitEnd);@@ -60,10 +60,10 @@ describe('market Ghost session boundary', () => {const installEnd = source.indexOf('\n}\n\ntype GhostUninstallLedgerCompletion', installStart);const installBody = source.slice(installStart, installEnd);const firstAfterCommit = installBody.indexOf(- 'await expected.afterCommitInLock?.(installedGhost);',+ 'await expected.afterCommitInLock?.(installedGhost, commitEvidence);',);const updateAfterCommit = installBody.indexOf(- 'await expected.afterCommitInLock?.(result.ghost);',+ 'await expected.afterCommitInLock?.(result.ghost, commitEvidence);',);const release = installBody.indexOf('releaseMutation?.();');@@ -71,7 +71,7 @@ describe('market Ghost session boundary', () => {expect(updateAfterCommit).toBeGreaterThan(firstAfterCommit);expect(release).toBeGreaterThan(updateAfterCommit);const serverCommitStart = marketServiceSource.indexOf(- 'afterCommitInLock: async (committed) => {',+ 'afterCommitInLock: async (_committed, evidence) => {',);const serverCommitEnd = marketServiceSource.indexOf('\n },\n }).catch', serverCommitStart);const serverCommitBody = marketServiceSource.slice(serverCommitStart, serverCommitEnd);diff --git a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.tsindex 7f5f860d00..106a10023f 100644--- a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts+++ b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts@@ -12,6 +12,10 @@import { isValidGhostId, isValidGhostNetworkHostPattern } from '../../shared/ghost.js';import type { GhostManifest } from '../../shared/ghost.js';import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';+import {+ verifyInstalledMarketManifest,+ type InstalledMarketManifestIdentity,+} from '../plugin-market/installedManifestIdentity.js';import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID } from '../plugin-publisher/types.js';import { PLUGIN_PREFIX_PATTERN } from '@cindy/plugin-protocol';@@ -83,8 +87,8 @@ export type MarketInstallationLookup =| { kind: 'invalid' };export interface LoadConnectionAudienceResolverOptions {- readInstalledManifest(ghostId: string): GhostManifest | null;- readInstalledManifestDigest(ghostId: string): string | null;+ /** Manifest and byte identity from one bounded read of the installed ghost.json. */+ readInstalledManifestIdentity(ghostId: string): InstalledMarketManifestIdentity | null;readMarketInstallation(ghostId: string,): PluginMarketInstallationRecord | MarketInstallationLookup | null;@@ -141,9 +145,9 @@ export function loadConnectionAudienceResolver(};};- const readManifest = (): GhostManifest | null => {+ const readManifestIdentity = (): InstalledMarketManifestIdentity | null => {try {- return options.readInstalledManifest(ghostId);+ return options.readInstalledManifestIdentity(ghostId);} catch {return null;}@@ -161,10 +165,10 @@ export function loadConnectionAudienceResolver(if (!approvedSha || !/^[a-f0-9]{64}$/.test(approvedSha)) {return reject('forge-package-sha-missing');}- const manifest = readManifest();- if (!manifest) return reject('plugin-not-installed');- if (manifest.id !== ghostId) return reject('plugin-id-mismatch');- return finish(manifest);+ const identitySnapshot = readManifestIdentity();+ if (!identitySnapshot) return reject('plugin-not-installed');+ if (identitySnapshot.manifest.id !== ghostId) return reject('plugin-id-mismatch');+ return finish(identitySnapshot.manifest);}}@@ -189,17 +193,17 @@ export function loadConnectionAudienceResolver(// Named exception after the org gate and before market-missing reject.// Any persisted market row, including installed:false, still takes digest.if (ghostId === LOCAL_OIDC_ALLOWLIST_GHOST_ID) {- const allowlisted = readManifest();+ const allowlisted = readManifestIdentity();if (!allowlisted) return reject('plugin-not-installed');- if (allowlisted.id !== ghostId) return reject('plugin-id-mismatch');- const allowlistedHosts = declaredOidcTokenHosts(allowlisted);+ if (allowlisted.manifest.id !== ghostId) return reject('plugin-id-mismatch');+ const allowlistedHosts = declaredOidcTokenHosts(allowlisted.manifest);if (allowlistedHosts.length !== 1 ||allowlistedHosts[0] !== LOCAL_OIDC_ALLOWLIST_HOST) {return reject('oidc-host-not-allowlisted');}- return finish(allowlisted);+ return finish(allowlisted.manifest);}return reject('market-installation-missing');}@@ -211,28 +215,22 @@ export function loadConnectionAudienceResolver(if (installation.organizationId !== identity.orgId) {return reject('market-installation-org-mismatch');}- if (!installation.manifestDigest) {- return reject('market-manifest-digest-missing');+ if (!installation.rawManifestSha256 && !installation.manifestDigest) {+ return reject('market-manifest-identity-missing');}- let manifest: GhostManifest | null = null;+ let identitySnapshot: InstalledMarketManifestIdentity | null = null;try {- manifest = options.readInstalledManifest(ghostId);+ identitySnapshot = options.readInstalledManifestIdentity(ghostId);} catch {return reject('installed-manifest-read-failed');}- if (!manifest) return reject('plugin-not-installed');- if (manifest.id !== ghostId) return reject('plugin-id-mismatch');- let installedManifestDigest: string | null = null;- try {- installedManifestDigest = options.readInstalledManifestDigest(ghostId);- } catch {- return reject('installed-manifest-digest-read-failed');- }- if (installedManifestDigest !== installation.manifestDigest) {- return reject('installed-manifest-digest-mismatch');+ if (!identitySnapshot) return reject('plugin-not-installed');+ if (identitySnapshot.manifest.id !== ghostId) return reject('plugin-id-mismatch');+ if (!verifyInstalledMarketManifest(installation, identitySnapshot)) {+ return reject('installed-manifest-identity-mismatch');}- return finish(manifest);+ return finish(identitySnapshot.manifest);},};}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 96de840e2f..6c9c6434f7 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -311,12 +311,16 @@ import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';import { getSessionFsSnapshot, getSessionRowSnapshot } from '../localDb/ipc/sessions.js';import { getTeamByWorkerSession } from '../localDb/orcaTeamStore.js';import { getDirDepositVault, getSaveDepositVault, isPathInsideDir } from './dirDeposit.js';-import { readInstalledGhostManifestDigestFormats } from '../installedGhostManifest.js';+import { readInstalledGhostManifestSnapshot } from '../installedGhostManifest.js';import {ghostManifestDigest,PluginMarketLedger,type PluginMarketInstallationRecord,} from '../plugin-market/ledger.js';+import {+ installedMarketManifestIdentity,+ type InstalledMarketManifestIdentity,+} from '../plugin-market/installedManifestIdentity.js';import { createOrganizationPrefixStore } from '../plugin-market/organizationPrefixStore.js';import {GhostSubscriptionGateway,@@ -2554,30 +2558,26 @@ function getPluginMarketLedger(): PluginMarketLedger {return pluginMarketLedgerSingleton;}-/** Read the locale-independent manifest digest from the installed package. */-function readInstalledGhostManifestDigest(ghostId: string): string | null {+/** Read Manifest and byte identity together from one installed ghost.json snapshot. */+function readInstalledGhostManifestIdentity(+ ghostId: string,+): InstalledMarketManifestIdentity | null {const ghost = getGhostManager().list().find((candidate) => candidate.manifest.id === ghostId);if (!ghost) return null;- const digests = readInstalledGhostManifestDigestFormats(+ const result = readInstalledGhostManifestSnapshot(ghost.dir,GHOST_INSTALL_MANIFEST_MAX_BYTES,- ).map(ghostManifestDigest);- const expected = getPluginMarketLedger().installationForGhost(ghostId)?.manifestDigest;- if (expected !== undefined && digests.includes(expected)) return expected;- return digests[0] ?? null;+ );+ return result.ok ? installedMarketManifestIdentity(result.snapshot) : null;}/** Resolve Connection metadata from trusted organization installs or explicit Forge receipts. */function getConnectionAudienceResolver(): ConnectionAudienceResolver {if (!connectionAudienceResolverSingleton) {connectionAudienceResolverSingleton = loadConnectionAudienceResolver({- readInstalledManifest: (ghostId) =>- getGhostManager()- .list()- .find((candidate) => candidate.manifest.id === ghostId)?.manifest ?? null,- readInstalledManifestDigest: readInstalledGhostManifestDigest,+ readInstalledManifestIdentity: readInstalledGhostManifestIdentity,readMarketInstallation: (ghostId) =>getPluginMarketLedger().lookupInstallationForOidc(ghostId),readApprovedPackageSha256: (ghostId) =>@@ -5711,6 +5711,15 @@ export async function installOrUpdateLocalGhostPackageFromForge(* 因而允许官方保留前缀;本地文件入口仍继续走 rejectReservedGhostId。* tokenBroker 门控、原子换目录、布局停靠与运行时重启保持和本地安装一致。*/+export interface MarketGhostPackageCommitEvidence {+ /** SHA-256 of the exact ghost.json entry bytes bound to the accepted package. */+ rawManifestSha256: string;+ /** Digest format read by released clients; derived from the same package entry. */+ legacyManifestDigest: string;+ /** Locale-independent Manifest parsed from those same package entry bytes. */+ canonicalManifest: GhostManifest;+}+export async function installOrUpdateMarketGhostPackage(cindyFilePath: string,expected: {@@ -5732,7 +5741,10 @@ export async function installOrUpdateMarketGhostPackage(/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */onPackagePlacedInLock?: () => void;/** 包与 receipt 已提交,仍持 owner mutation lease;用于原子写入来源账本。 */- afterCommitInLock?: (installed: InstalledGhost) => void | Promise<void>;+ afterCommitInLock?: (+ installed: InstalledGhost,+ evidence: MarketGhostPackageCommitEvidence,+ ) => void | Promise<void>;/** 仅 server-market 主机路径可传;custom/local 不传。 */officialCindyGithub?: boolean;},@@ -5758,7 +5770,10 @@ async function installOrUpdateMarketGhostPackageLocked(/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */onPackagePlacedInLock?: () => void;/** 包与 receipt 已提交,仍持 owner mutation lease;用于原子写入来源账本。 */- afterCommitInLock?: (installed: InstalledGhost) => void | Promise<void>;+ afterCommitInLock?: (+ installed: InstalledGhost,+ evidence: MarketGhostPackageCommitEvidence,+ ) => void | Promise<void>;officialCindyGithub?: boolean;},): Promise<InstalledGhost> {@@ -5768,6 +5783,11 @@ async function installOrUpdateMarketGhostPackageLocked(const manager = getGhostManager();const inspected = await manager.inspect(cindyFilePath);if ('rejection' in inspected) throwInstallError(inspected.rejection);+ const commitEvidence: MarketGhostPackageCommitEvidence = {+ rawManifestSha256: inspected.rawManifestSha256,+ legacyManifestDigest: ghostManifestDigest(inspected.releasedLegacyDigestFormat),+ canonicalManifest: inspected.canonicalManifest,+ };// Publisher identity slugs stay reserved even on the market path.// Official reserved prefixes from shared/ghost.ts remain exempt here; publisher slugs do not.rejectReservedPublisherSlug(inspected.canonicalManifest.id);@@ -5848,7 +5868,7 @@ async function installOrUpdateMarketGhostPackageLocked(expectedPackageSha256: inspected.packageSha256,...(trustOverride ? { trustOverride } : {}),});- await expected.afterCommitInLock?.(installedGhost);+ await expected.afterCommitInLock?.(installedGhost, commitEvidence);return installedGhost;}@@ -5925,7 +5945,7 @@ async function installOrUpdateMarketGhostPackageLocked(}}spawnIfResident(result.ghost);- await expected.afterCommitInLock?.(result.ghost);+ await expected.afterCommitInLock?.(result.ghost, commitEvidence);return result.ghost;} finally {releaseMutation?.();diff --git a/apps/desktop/src/main/installedGhostManifest.ts b/apps/desktop/src/main/installedGhostManifest.tsindex 607f4f04f9..c633f4028a 100644--- a/apps/desktop/src/main/installedGhostManifest.ts+++ b/apps/desktop/src/main/installedGhostManifest.ts@@ -1,3 +1,4 @@+import crypto from 'node:crypto';import path from 'node:path';import {@@ -11,6 +12,21 @@ export type InstalledGhostManifestParse =| { ok: true; manifest: GhostManifest; legacyManualIgnored: boolean }| { ok: false; reason: string };+export interface InstalledGhostManifestSnapshot {+ manifest: GhostManifest;+ legacyManualIgnored: boolean;+ /** SHA-256 of the exact ghost.json bytes read from disk. */+ rawManifestSha256: string;+ /** Exact normalized shape emitted by the released v0.1.61 v2 validator. */+ releasedLegacyDigestFormat: unknown;+ /** Historical normalized projections; migration is their only consumer. */+ legacyDigestFormats: readonly unknown[];+}++export type InstalledGhostManifestSnapshotRead =+ | { ok: true; snapshot: InstalledGhostManifestSnapshot }+ | { ok: false; reason: string };+function isPlainObject(value: unknown): value is Record<string, unknown> {if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;const prototype = Object.getPrototypeOf(value);@@ -40,10 +56,44 @@ export function readInstalledGhostManifest(dir: string,maxBytes: number,): InstalledGhostManifestParse {+ const result = readInstalledGhostManifestSnapshot(dir, maxBytes);+ return result.ok+ ? {+ ok: true,+ manifest: result.snapshot.manifest,+ legacyManualIgnored: result.snapshot.legacyManualIgnored,+ }+ : result;+}++/**+ * Read the installed ghost.json once and derive every identity projection from+ * that same Buffer. Consumers must not pair this result with a second manifest+ * read: doing so would reopen a validate-one-file/use-another TOCTOU window.+ */+export function readInstalledGhostManifestSnapshot(+ dir: string,+ maxBytes: number,+): InstalledGhostManifestSnapshotRead {try {const bytes = readBoundedFileNoFollowSync(path.join(dir, 'ghost.json'), maxBytes);if (bytes === null) return { ok: false, reason: 'manifest is not a bounded regular file' };- return parseInstalledGhostManifest(JSON.parse(bytes.toString('utf8')) as unknown);+ const raw = JSON.parse(bytes.toString('utf8')) as unknown;+ const parsed = parseInstalledGhostManifest(raw);+ if (!parsed.ok) return parsed;+ const current = parsed.manifest;+ const legacy = ghostManifestToLegacyV2DigestFormat(current, raw);+ return {+ ok: true,+ snapshot: {+ manifest: current,+ legacyManualIgnored: parsed.legacyManualIgnored,+ rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ releasedLegacyDigestFormat: legacy,+ legacyDigestFormats:+ JSON.stringify(current) === JSON.stringify(legacy) ? [current] : [current, legacy],+ },+ };} catch {return { ok: false, reason: 'manifest could not be read' };}@@ -54,16 +104,6 @@ export function readInstalledGhostManifestDigestFormats(dir: string,maxBytes: number,): unknown[] {- try {- const bytes = readBoundedFileNoFollowSync(path.join(dir, 'ghost.json'), maxBytes);- if (bytes === null) return [];- const raw = JSON.parse(bytes.toString('utf8')) as unknown;- const parsed = parseInstalledGhostManifest(raw);- if (!parsed.ok) return [];- const current = parsed.manifest;- const legacy = ghostManifestToLegacyV2DigestFormat(current, raw);- return JSON.stringify(current) === JSON.stringify(legacy) ? [current] : [current, legacy];- } catch {- return [];- }+ const result = readInstalledGhostManifestSnapshot(dir, maxBytes);+ return result.ok ? [...result.snapshot.legacyDigestFormats] : [];}diff --git a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.tsindex c042bd9865..36b38f4699 100644--- a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts@@ -40,11 +40,22 @@ vi.mock('../../cindy-brain/index.js', () => ({installOrUpdateMarketGhostPackage: async (filePath: string,options: {- afterCommitInLock?: (installed: unknown) => void | Promise<void>;+ afterCommitInLock?: (+ installed: unknown,+ evidence: {+ rawManifestSha256: string;+ legacyManifestDigest: string;+ canonicalManifest: GhostManifest;+ },+ ) => void | Promise<void>;},) => {const installed = await brain.installOrUpdateMarketGhostPackage(filePath, options);- await options.afterCommitInLock?.(installed);+ await options.afterCommitInLock?.(installed, {+ rawManifestSha256: 'b'.repeat(64),+ legacyManifestDigest: 'c'.repeat(64),+ canonicalManifest: (installed as { manifest: GhostManifest }).manifest,+ });return installed;},rejectReservedGhostIdForCustomMarket: brain.rejectReservedGhostIdForCustomMarket,@@ -240,6 +251,11 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {expect(afterCommit).toHaveBeenCalledWith(expect.objectContaining({ manifest: GOOD_MANIFEST }),GOOD_MANIFEST,+ {+ rawManifestSha256: 'b'.repeat(64),+ legacyManifestDigest: 'c'.repeat(64),+ canonicalManifest: GOOD_MANIFEST,+ },);expect(fs.existsSync(String(commitPath))).toBe(false);});diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.tsindex 2e2604bc37..0acb2a71ef 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts@@ -43,12 +43,17 @@ function record(describe('PluginMarketLedger', () => {it('writes provenance atomically and reads it back', () => {const { filePath, ledger } = harness();- ledger.upsertInstallation(record());+ ledger.upsertInstallation(record({+ manifestDigest: 'c'.repeat(64),+ rawManifestSha256: 'd'.repeat(64),+ }));expect(ledger.installationForGhost('cindy-test')).toMatchObject({pluginId: `c${'a'.repeat(24)}`,installed: true,source: 'market',+ manifestDigest: 'c'.repeat(64),+ rawManifestSha256: 'd'.repeat(64),});expect(ledger.lookupInstallationForOidc('cindy-test')).toMatchObject({kind: 'found',@@ -61,6 +66,48 @@ describe('PluginMarketLedger', () => {).toEqual([]);});+ it('backfills raw manifest identity without changing legacy routing fields', () => {+ const { ledger } = harness();+ const legacy = record({ manifestDigest: 'c'.repeat(64) });+ ledger.upsertInstallation(legacy);++ expect(ledger.backfillRawManifestSha256(legacy, 'd'.repeat(64))).toBe(true);+ expect(ledger.installationForGhost(legacy.ghostId)).toEqual({+ ...legacy,+ rawManifestSha256: 'd'.repeat(64),+ });+ expect(ledger.backfillRawManifestSha256(legacy, 'e'.repeat(64))).toBe(false);+ });++ it('replaces both identities after a package commit without changing route metadata', () => {+ const { ledger } = harness();+ const previous = record({+ manifestDigest: 'c'.repeat(64),+ rawManifestSha256: 'd'.repeat(64),+ });+ ledger.upsertInstallation(previous);++ expect(+ ledger.replaceManifestIdentityAfterPackageCommit(+ previous,+ 'e'.repeat(64),+ 'f'.repeat(64),+ ),+ ).toBe(true);+ expect(ledger.installationForGhost(previous.ghostId)).toEqual({+ ...previous,+ manifestDigest: 'e'.repeat(64),+ rawManifestSha256: 'f'.repeat(64),+ });+ expect(+ ledger.replaceManifestIdentityAfterPackageCommit(+ previous,+ 'a'.repeat(64),+ 'b'.repeat(64),+ ),+ ).toBe(false);+ });+it('records defaultInstall opt-out per authenticated user on removal', () => {const { ledger } = harness();ledger.upsertInstallation(record());@@ -77,14 +124,17 @@ describe('PluginMarketLedger', () => {it('atomically reconnects an unchanged server record and clears its false opt-out', () => {const { ledger } = harness();- ledger.upsertInstallation(record());+ ledger.upsertInstallation(record({ rawManifestSha256: 'd'.repeat(64) }));ledger.markRemoved('cindy-test', 'user-a');const disconnected = ledger.installationForGhost('cindy-test');expect(disconnected).not.toBeNull();if (!disconnected) return;expect(ledger.restoreDisconnectedInstallation(disconnected, 'user-a')).toBe(true);- expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: true });+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({+ installed: true,+ rawManifestSha256: 'd'.repeat(64),+ });expect(ledger.isDefaultInstallSuppressed('user-a', disconnected.pluginId),).toBe(false);@@ -197,6 +247,25 @@ describe('PluginMarketLedger', () => {expect(ledger.lookupInstallationForOidc('mivo-canvas')).toEqual({ kind: 'invalid' });});+ it('rejects malformed raw manifest identities while keeping legacy records valid', () => {+ const { filePath, ledger } = harness();+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(+ filePath,+ JSON.stringify({+ schemaVersion: 1,+ installations: {+ valid: record({ ghostId: 'valid', rawManifestSha256: undefined }),+ invalid: record({ ghostId: 'invalid', rawManifestSha256: 'ABC' }),+ },+ defaultInstallOptOuts: {},+ }),+ );++ expect(ledger.installationForGhost('valid')).not.toBeNull();+ expect(ledger.installationForGhost('invalid')).toBeNull();+ });+it('resolves the owner-scoped path for every operation', () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-ledger-owner-'));roots.push(root);diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex 1880f0b477..463b5a26b3 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -1,3 +1,4 @@+import crypto from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -34,6 +35,7 @@ const runtime = vi.hoisted(() => ({pendingCalls: false,runningErrand: false,cindyWork: false,+ generatedInstallDirs: [] as string[],boundaryPending: false,pluginApiBaseUrl: 'https://plugin.test.invalid' as string | null,session: {@@ -87,11 +89,41 @@ vi.mock('../../cindy-brain/index.js', () => ({installOrUpdateMarketGhostPackage: async (filePath: string,options: {- afterCommitInLock?: (installed: unknown) => void | Promise<void>;+ afterCommitInLock?: (+ installed: { manifest: Record<string, unknown>; dir: string },+ evidence: {+ rawManifestSha256: string;+ legacyManifestDigest: string;+ canonicalManifest: Record<string, unknown>;+ },+ ) => void | Promise<void>;},) => {const installed = await runtime.install(filePath, options);- await options.afterCommitInLock?.(installed);+ let bytes: Buffer;+ try {+ bytes = fs.readFileSync(path.join(installed.dir, 'ghost.json'));+ } catch {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-installed-'));+ runtime.generatedInstallDirs.push(dir);+ bytes = Buffer.from(JSON.stringify(installed.manifest));+ fs.writeFileSync(path.join(dir, 'ghost.json'), bytes);+ installed.dir = dir;+ const runtimeGhost = runtime.ghosts.find(+ (ghost) => ghost.manifest.id === installed.manifest.id,+ );+ if (runtimeGhost) runtimeGhost.dir = dir;+ }+ await options.afterCommitInLock?.(installed, {+ rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ legacyManifestDigest: ghostManifestDigest(+ ghostManifestToLegacyV2DigestFormat(+ installed.manifest,+ JSON.parse(bytes.toString('utf8')) as unknown,+ ),+ ),+ canonicalManifest: installed.manifest,+ });return installed;},hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),@@ -108,7 +140,11 @@ vi.mock('../download.js', () => ({import { downloadVerifiedPlugin } from '../download.js';import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';-import { GHOST_ICON_MAX_BYTES, type GhostManifest } from '../../../shared/ghost';+import {+ GHOST_ICON_MAX_BYTES,+ ghostManifestToLegacyV2DigestFormat,+ type GhostManifest,+} from '../../../shared/ghost';import {customMarketPluginId,customMarketReleaseId,@@ -141,6 +177,9 @@ afterEach(() => {runtime.pendingCalls = false;runtime.runningErrand = false;runtime.cindyWork = false;+ for (const dir of runtime.generatedInstallDirs.splice(0)) {+ fs.rmSync(dir, { recursive: true, force: true });+ }runtime.boundaryPending = false;runtime.pluginApiBaseUrl = 'https://plugin.test.invalid';runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 619df9ff49..9568b5d1bf 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -1,3 +1,4 @@+import crypto from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -5,6 +6,8 @@ import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import {+ ghostManifestToAuthorFormat,+ ghostManifestToLegacyV2DigestFormat,validateGhostManifest,type GhostInstallApproval,type GhostManifest,@@ -27,6 +30,7 @@ const runtime = vi.hoisted(() => ({pendingCalls: false,runningErrand: false,cindyWork: false,+ generatedInstallDirs: [] as string[],boundaryPending: false,approvedInstallEvidence: vi.fn(() => null as {packageSha256: string | null;@@ -68,19 +72,36 @@ vi.mock('../../logger.js', () => ({vi.mock('../../cindy-brain/index.js', () => ({getGhostManager: () => ({list: () =>- runtime.ghosts.map((ghost) => ({- ...ghost,- approval: ghost.approval ?? {- state: 'approved',- revision: '00000000-0000-4000-8000-000000000001',- },- trust: ghost.trust ?? {- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- },- })),+ runtime.ghosts.map((ghost) => {+ // Historical service tests used a production-looking placeholder path.+ // Materialize only that fixture shape so raw-byte identity is exercised;+ // explicit missing/unreadable temp-path cases remain untouched.+ if (+ ghost.dir.startsWith('/userData/cindy-brain/') &&+ !fs.existsSync(path.join(ghost.dir, 'ghost.json'))+ ) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-service-runtime-'));+ runtime.generatedInstallDirs.push(dir);+ fs.writeFileSync(+ path.join(dir, 'ghost.json'),+ JSON.stringify(ghostManifestToAuthorFormat(ghost.manifest as GhostManifest)),+ );+ ghost.dir = dir;+ }+ return {+ ...ghost,+ approval: ghost.approval ?? {+ state: 'approved',+ revision: '00000000-0000-4000-8000-000000000001',+ },+ trust: ghost.trust ?? {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ };+ }),approvedInstallEvidence: runtime.approvedInstallEvidence,inspect: runtime.inspect,}),@@ -88,11 +109,43 @@ vi.mock('../../cindy-brain/index.js', () => ({installOrUpdateMarketGhostPackage: async (filePath: string,options: {- afterCommitInLock?: (installed: unknown) => void | Promise<void>;+ afterCommitInLock?: (+ installed: { manifest: Record<string, unknown>; dir: string },+ evidence: {+ rawManifestSha256: string;+ legacyManifestDigest: string;+ canonicalManifest: Record<string, unknown>;+ },+ ) => void | Promise<void>;},) => {const installed = await runtime.install(filePath, options);- await options.afterCommitInLock?.(installed);+ let bytes: Buffer;+ try {+ bytes = fs.readFileSync(path.join(installed.dir, 'ghost.json'));+ } catch {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-service-installed-'));+ runtime.generatedInstallDirs.push(dir);+ bytes = Buffer.from(+ JSON.stringify(ghostManifestToAuthorFormat(installed.manifest as GhostManifest)),+ );+ fs.writeFileSync(path.join(dir, 'ghost.json'), bytes);+ installed.dir = dir;+ const runtimeGhost = runtime.ghosts.find(+ (ghost) => ghost.manifest.id === installed.manifest.id,+ );+ if (runtimeGhost) runtimeGhost.dir = dir;+ }+ await options.afterCommitInLock?.(installed, {+ rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ legacyManifestDigest: ghostManifestDigest(+ ghostManifestToLegacyV2DigestFormat(+ installed.manifest,+ JSON.parse(bytes.toString('utf8')) as unknown,+ ),+ ),+ canonicalManifest: installed.manifest,+ });return installed;},hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),@@ -115,6 +168,7 @@ import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';import {PluginMarketLedger,ghostManifestDigest,+ legacyNoSlotsGhostManifestDigest,type PluginMarketInstallationRecord,} from '../ledger';import { PluginMarketService } from '../service';@@ -146,6 +200,9 @@ afterEach(() => {runtime.pendingCalls = false;runtime.runningErrand = false;runtime.cindyWork = false;+ for (const dir of runtime.generatedInstallDirs.splice(0)) {+ fs.rmSync(dir, { recursive: true, force: true });+ }runtime.boundaryPending = false;runtime.approvedInstallEvidence.mockReset();runtime.approvedInstallEvidence.mockReturnValue(null);@@ -371,6 +428,242 @@ function mockUninstallDropsGhost(failFor?: string): void {}describe('PluginMarketService migration and defaultInstall', () => {+ it('backfills the exact raw identity for an unchanged v0.1.61 v2 card record', async () => {+ const rawManifest = {+ schemaVersion: 2 as const,+ id: 'cindy-test',+ name: 'Test Plugin',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['card'],+ };+ const canonicalManifest = normalizedManifest(rawManifest);+ const bytes = Buffer.from(`${JSON.stringify(rawManifest, null, 2)}\n`);+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-v2-card-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), bytes);+ runtime.ghosts = [{ manifest: canonicalManifest, dir: installDir, enabled: true }];+ const item = summary();+ const h = harness([item]);+ const legacyRecord = recordForTest(item, {+ manifestDigest: ghostManifestDigest(rawManifest),+ updatedAt: '2026-08-01T00:00:00.000Z',+ });+ h.ledger.upsertInstallation(legacyRecord);+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: canonicalManifest,+ legacyMigrated: false,+ });++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('installed');+ expect(h.ledger.installationForGhost(item.ghostId)).toEqual({+ ...legacyRecord,+ rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ });+ });++ it('does not backfill raw identity when the installed v2 manifest changed', async () => {+ const approvedRaw = {+ schemaVersion: 2 as const,+ id: 'cindy-test',+ name: 'Test Plugin',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['card'],+ };+ const changedRaw = { ...approvedRaw, description: 'changed locally' };+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-v2-changed-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(changedRaw));+ runtime.ghosts = [{+ manifest: normalizedManifest(changedRaw),+ dir: installDir,+ enabled: true,+ }];+ const item = summary();+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ manifestDigest: ghostManifestDigest(approvedRaw),+ }));+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: normalizedManifest(approvedRaw),+ legacyMigrated: false,+ });++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('conflict');+ expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBeUndefined();+ });++ it('backfills a pre-digest server record only from matching modern receipt evidence', async () => {+ const rawManifest = manifest();+ const bytes = Buffer.from(`${JSON.stringify(rawManifest, null, 2)}\n`);+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-no-digest-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), bytes);+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];+ const item = summary();+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item));+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: normalizedManifest(rawManifest),+ legacyMigrated: false,+ });++ await h.service.snapshot();++ expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBe(+ crypto.createHash('sha256').update(bytes).digest('hex'),+ );+ });++ it('does not mint raw identity when a modern receipt names a different manifest', async () => {+ const rawManifest = manifest();+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-receipt-manifest-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];+ const item = summary();+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ manifestDigest: ghostManifestDigest(rawManifest),+ }));+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: normalizedManifest({ ...rawManifest, description: 'receipt mismatch' }),+ legacyMigrated: false,+ });++ await h.service.snapshot();++ expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBeUndefined();+ });++ it.each(['market', 'local-market'] as const)(+ 'does not backfill a %s record while mutation recovery marks the install invalid',+ async (source) => {+ const rawManifest = manifest();+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-pending-mutation-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));+ runtime.ghosts = [{+ manifest: rawManifest,+ dir: installDir,+ enabled: false,+ approval: { state: 'invalid' },+ }];+ const item = summary();+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ source,+ ...(source === 'local-market' ? { sourceKey: 'local:pending-mutation' } : {}),+ manifestDigest: ghostManifestDigest(rawManifest),+ }));++ await h.service.snapshot();++ expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBeUndefined();+ },+ );++ it('backfills an affected record that was already reinstalled with the current digest', async () => {+ const rawManifest = {+ schemaVersion: 2 as const,+ id: 'cindy-test',+ name: 'Test Plugin',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['card'],+ };+ const canonicalManifest = normalizedManifest(rawManifest);+ const bytes = Buffer.from(JSON.stringify(rawManifest));+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-reinstalled-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), bytes);+ runtime.ghosts = [{ manifest: canonicalManifest, dir: installDir, enabled: true }];+ const item = summary();+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ manifestDigest: ghostManifestDigest(canonicalManifest),+ updatedAt: '2026-08-01T00:00:00.000Z',+ }));+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: canonicalManifest,+ legacyMigrated: false,+ });++ await h.service.snapshot();++ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ updatedAt: '2026-08-01T00:00:00.000Z',+ rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ });+ });++ it('backfills the released intermediate v2 digest that omitted slots', async () => {+ const rawManifest = {+ schemaVersion: 2 as const,+ id: 'cindy-test',+ name: 'Test Plugin',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['card'],+ };+ const canonicalManifest = normalizedManifest(rawManifest);+ const bytes = Buffer.from(JSON.stringify(rawManifest));+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-no-slots-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), bytes);+ runtime.ghosts = [{ manifest: canonicalManifest, dir: installDir, enabled: true }];+ const item = summary();+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ manifestDigest: legacyNoSlotsGhostManifestDigest(canonicalManifest),+ }));+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: canonicalManifest,+ legacyMigrated: false,+ });++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('installed');+ expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBe(+ crypto.createHash('sha256').update(bytes).digest('hex'),+ );+ });++ it('never overwrites an existing raw identity mismatch with a matching legacy digest', async () => {+ const rawManifest = manifest();+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-raw-mismatch-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(rawManifest));+ runtime.ghosts = [{ manifest: rawManifest, dir: installDir, enabled: true }];+ const item = summary();+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ manifestDigest: ghostManifestDigest(rawManifest),+ rawManifestSha256: 'f'.repeat(64),+ }));++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('conflict');+ expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBe('f'.repeat(64));+ });+it('projects same-release display metadata without reinstalling the package', async () => {runtime.ghosts = [{@@ -814,6 +1107,64 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).not.toHaveBeenCalled();});+ it('keeps a disconnected route detached when a modern receipt names another manifest', async () => {+ const canonicalManifest = normalizedManifest(manifest());+ const item = summary({+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID },+ });+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-recovery-manifest-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));+ runtime.ghosts = [{ manifest: canonicalManifest, dir: installDir, enabled: true }];+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: normalizedManifest({ ...manifest(), description: 'receipt mismatch' }),+ legacyMigrated: false,+ });+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ releaseId: RELEASE_ID,+ manifestDigest: ghostManifestDigest(canonicalManifest),+ }));+ h.ledger.markRemoved(item.ghostId, 'user-1');++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('conflict');+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);+ });++ it('never restores a disconnected route across an existing raw identity mismatch', async () => {+ const canonicalManifest = normalizedManifest(manifest());+ const item = summary({+ currentRelease: { ...summary().currentRelease, id: RELEASE_ID },+ });+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-recovery-raw-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));+ runtime.ghosts = [{ manifest: canonicalManifest, dir: installDir, enabled: true }];+ runtime.approvedInstallEvidence.mockReturnValue({+ packageSha256: item.currentRelease.sha256,+ approvedManifest: canonicalManifest,+ legacyMigrated: false,+ });+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item, {+ releaseId: RELEASE_ID,+ manifestDigest: ghostManifestDigest(canonicalManifest),+ rawManifestSha256: 'f'.repeat(64),+ }));+ h.ledger.markRemoved(item.ghostId, 'user-1');++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('conflict');+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ installed: false,+ rawManifestSha256: 'f'.repeat(64),+ });+ });+it.each([{ receiptCase: 'missing', receiptSha: null },{ receiptCase: 'different', receiptSha: 'f'.repeat(64) },@@ -911,6 +1262,7 @@ describe('PluginMarketService migration and defaultInstall', () => {source: 'market',releaseId: RELEASE_ID,});+ expect(h.ledger.installationForGhost(item.ghostId)?.rawManifestSha256).toBeUndefined();expect(h.api.download).not.toHaveBeenCalled();expect(runtime.install).not.toHaveBeenCalled();});@@ -1456,6 +1808,49 @@ describe('PluginMarketService migration and defaultInstall', () => {});});+ it('writes the v0.1.61 digest for a newly installed v2 card package', async () => {+ const rawManifest = {+ schemaVersion: 2 as const,+ id: 'cindy-test',+ name: 'Test Plugin',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['card'] as const,+ };+ const canonicalManifest = normalizedManifest(rawManifest);+ const bytes = Buffer.from(`${JSON.stringify(rawManifest, null, 2)}\n`);+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-new-v2-card-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), bytes);+ const item = summary();+ const h = harness([item]);+ h.api.detail.mockResolvedValue({+ ...item,+ currentRelease: {+ ...item.currentRelease,+ manifest: rawManifest as unknown as VisiblePluginDetail['currentRelease']['manifest'],+ },+ });+ runtime.inspectedManifest = canonicalManifest;+ runtime.install.mockResolvedValue({+ manifest: canonicalManifest,+ dir: installDir,+ enabled: true,+ });++ await h.service.install(item.id, {+ expectedReleaseId: item.currentRelease.id,+ expectedManifest: rawManifest as unknown as GhostManifest,+ allowSourceReplacement: false,+ });++ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ manifestDigest: ghostManifestDigest(rawManifest),+ rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ });+ });+it('Host receipt 未可信时,目录中的完整 trust 镜像也不能阻止官方回填', async () => {const item = summary({ ghostId: 'cindy-github' });const rawManifest = manifest('cindy-github');@@ -1511,15 +1906,61 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/cindy-plugin-trust-backfill-.*\.cindy$/),- {+ expect.objectContaining({ghostId: 'cindy-github',version: item.currentRelease.version,expectedInstalledApproval: APPROVED_INSTALL_TOKEN,officialCindyGithub: true,- },+ afterCommitInLock: expect.any(Function),+ }),);});+ it('refreshes both manifest identities when cindy-github trust backfill replaces the package', async () => {+ const item = summary({ ghostId: 'cindy-github' });+ const rawManifest = manifest('cindy-github');+ const oldBytes = Buffer.from(`${JSON.stringify(rawManifest, null, 2)}\n`);+ const packageBytes = Buffer.from(JSON.stringify(rawManifest));+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-github-raw-'));+ roots.push(installDir);+ fs.writeFileSync(path.join(installDir, 'ghost.json'), oldBytes);+ runtime.ghosts = [{+ manifest: rawManifest,+ dir: installDir,+ enabled: true,+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ }];+ const h = harness([item]);+ const original = recordForTest(item, {+ updatedAt: '2026-08-07T00:00:00.000Z',+ manifestDigest: ghostManifestDigest(rawManifest),+ rawManifestSha256: crypto.createHash('sha256').update(oldBytes).digest('hex'),+ });+ h.ledger.upsertInstallation(original);+ runtime.install.mockImplementation(async () => {+ fs.writeFileSync(path.join(installDir, 'ghost.json'), packageBytes);+ return {+ manifest: rawManifest,+ dir: installDir,+ enabled: true,+ trust: { level: 'cindy-official' },+ };+ });++ await h.service.snapshot();++ expect(h.ledger.installationForGhost('cindy-github')).toEqual({+ ...original,+ manifestDigest: ghostManifestDigest(rawManifest),+ rawManifestSha256: crypto.createHash('sha256').update(packageBytes).digest('hex'),+ });+ });+it('完整官方 receipt 已存在时不会重复回填 cindy-github trust', async () => {const item = summary({ ghostId: 'cindy-github' });const rawManifest = manifest('cindy-github');diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.tsindex f31517c74a..02a8b33c1d 100644--- a/apps/desktop/src/main/plugin-market/install.ts+++ b/apps/desktop/src/main/plugin-market/install.ts@@ -31,6 +31,7 @@ import {getGhostManager,installOrUpdateMarketGhostPackage,rejectReservedGhostIdForCustomMarket,+ type MarketGhostPackageCommitEvidence,} from '../cindy-brain/index.js';import type { PluginMarketInstallResult } from '../../shared/pluginMarket.js';import { packGhostDirToFile } from '../cindy-brain/forge.js';@@ -98,6 +99,7 @@ export async function installCustomMarketPlugin(input: {afterCommit?: (installed: InstalledGhost,packagedManifest: GhostManifest,+ evidence: MarketGhostPackageCommitEvidence,) => Promise<void>;}): Promise<PluginMarketInstallResult> {// input.pluginDir 是发现层已 realpath、且已校验落在市场根内的规范路径。@@ -240,8 +242,8 @@ export async function installCustomMarketPlugin(input: {: {}),...(input.afterCommit? {- afterCommitInLock: (committed) =>- input.afterCommit!(committed, packed.manifest),+ afterCommitInLock: (committed, evidence) =>+ input.afterCommit!(committed, packed.manifest, evidence),}: {}),});diff --git a/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts b/apps/desktop/src/main/plugin-market/installedManifestIdentity.tsnew file mode 100644index 0000000000..a3581d60e2--- /dev/null+++ b/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts@@ -0,0 +1,75 @@+import type { GhostManifest } from '../../shared/ghost.js';+import type { InstalledGhostManifestSnapshot } from '../installedGhostManifest.js';+import {+ ghostManifestDigest,+ legacyNoSlotsGhostManifestDigest,+ type PluginMarketInstallationRecord,+} from './ledger.js';++export interface InstalledMarketManifestIdentity {+ manifest: GhostManifest;+ rawManifestSha256: string;+ /** Digest written by released clients; keep it stable for downgrade reads. */+ legacyManifestDigest: string;+ legacyManifestDigests: readonly string[];+}++/**+ * Convert the single-read installed snapshot into the market identity view.+ * Historical digests stay inside this adapter so normal callers cannot grow+ * their own compatibility candidate lists.+ */+export function installedMarketManifestIdentity(+ snapshot: InstalledGhostManifestSnapshot,+): InstalledMarketManifestIdentity {+ const legacyManifestDigests = new Set<string>();+ for (const format of snapshot.legacyDigestFormats) {+ legacyManifestDigests.add(ghostManifestDigest(format));+ legacyManifestDigests.add(legacyNoSlotsGhostManifestDigest(format));+ }+ return {+ manifest: snapshot.manifest,+ rawManifestSha256: snapshot.rawManifestSha256,+ legacyManifestDigest: ghostManifestDigest(snapshot.releasedLegacyDigestFormat),+ legacyManifestDigests: [...legacyManifestDigests],+ };+}++/**+ * New records are matched only by exact raw ghost.json bytes. Records written+ * by released clients enter the isolated legacy path until stable-owner+ * reconciliation can safely backfill the raw identity.+ */+export function verifyInstalledMarketManifest(+ record: PluginMarketInstallationRecord,+ identity: InstalledMarketManifestIdentity,+ options: { allowLegacyRecordWithoutDigest?: boolean } = {},+): boolean {+ if (record.rawManifestSha256 !== undefined) {+ return record.rawManifestSha256 === identity.rawManifestSha256;+ }+ if (record.manifestDigest !== undefined) {+ return identity.legacyManifestDigests.includes(record.manifestDigest);+ }+ return options.allowLegacyRecordWithoutDigest === true;+}++/** A missing raw field may be backfilled only from an exact released digest. */+export function legacyManifestIdentityMatches(+ record: PluginMarketInstallationRecord,+ identity: InstalledMarketManifestIdentity,+): boolean {+ return (+ record.rawManifestSha256 === undefined &&+ record.manifestDigest !== undefined &&+ identity.legacyManifestDigests.includes(record.manifestDigest)+ );+}++/** Compare a receipt's normalized Manifest with the installed legacy projections. */+export function installedIdentityMatchesManifest(+ identity: InstalledMarketManifestIdentity,+ manifest: GhostManifest,+): boolean {+ return identity.legacyManifestDigests.includes(ghostManifestDigest(manifest));+}diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.tsindex 9997da8b82..e4b1f1fb7e 100644--- a/apps/desktop/src/main/plugin-market/ledger.ts+++ b/apps/desktop/src/main/plugin-market/ledger.ts@@ -41,6 +41,12 @@ export interface PluginMarketInstallationRecord {* 更新覆盖。新写入的市场、自定义市场和 legacy adoption 记录均应携带。*/manifestDigest?: string;+ /**+ * SHA-256 of the exact installed ghost.json bytes. New clients use this+ * serialization-exact identity; manifestDigest remains unchanged for released+ * clients that still interpret it as a normalized digest.+ */+ rawManifestSha256?: string;}/** 递归按键排序的规范化 JSON(摘要必须与对象键序无关,两侧独立算也一致)。 */@@ -63,6 +69,15 @@ export function ghostManifestDigest(manifest: unknown): string {.digest('hex');}+/**+ * Exact digest emitted by the released capability-decoupling build before v2+ * rollback projection was restored. Migration-only: normal writers must keep+ * using ghostManifestDigest so released clients can read the ledger.+ */+export function legacyNoSlotsGhostManifestDigest(manifest: unknown): string {+ return crypto.createHash('sha256').update(canonicalJson(manifest)).digest('hex');+}+interface PluginMarketLedgerData {schemaVersion: typeof LEDGER_SCHEMA_VERSION;installations: Record<string, PluginMarketInstallationRecord>;@@ -115,7 +130,10 @@ function validRecord(value: unknown): value is PluginMarketInstallationRecord {typeof record.installed === 'boolean' &&typeof record.updatedAt === 'string' &&(record.sourceKey === undefined || typeof record.sourceKey === 'string') &&- (record.manifestDigest === undefined || typeof record.manifestDigest === 'string')+ (record.manifestDigest === undefined || typeof record.manifestDigest === 'string') &&+ (record.rawManifestSha256 === undefined ||+ (typeof record.rawManifestSha256 === 'string' &&+ /^[a-f0-9]{64}$/.test(record.rawManifestSha256))));}@@ -290,6 +308,53 @@ export class PluginMarketLedger {this.write(data);}+ /**+ * Add the serialization-exact manifest identity without changing+ * routing order or any legacy field. Full-record comparison makes this a CAS:+ * an install/update/source change that won the race is never overwritten.+ */+ backfillRawManifestSha256(+ expected: PluginMarketInstallationRecord,+ rawManifestSha256: string,+ ): boolean {+ if (!/^[a-f0-9]{64}$/.test(rawManifestSha256)) return false;+ const data = this.read();+ const current = data.installations[expected.ghostId];+ if (!current || canonicalJson(current) !== canonicalJson(expected)) return false;+ if (current.rawManifestSha256 !== undefined) {+ return current.rawManifestSha256 === rawManifestSha256;+ }+ data.installations[current.ghostId] = { ...current, rawManifestSha256 };+ this.write(data);+ return true;+ }++ /**+ * Replace both Manifest identities after an authorized package commit. Unlike+ * migration backfill, this may replace an existing raw hash because the+ * package itself was just atomically replaced. Full-record CAS prevents a+ * concurrent route change from being overwritten.+ */+ replaceManifestIdentityAfterPackageCommit(+ expected: PluginMarketInstallationRecord,+ manifestDigest: string,+ rawManifestSha256: string,+ ): boolean {+ if (!/^[a-f0-9]{64}$/.test(manifestDigest) || !/^[a-f0-9]{64}$/.test(rawManifestSha256)) {+ return false;+ }+ const data = this.read();+ const current = data.installations[expected.ghostId];+ if (!current || canonicalJson(current) !== canonicalJson(expected)) return false;+ data.installations[current.ghostId] = {+ ...current,+ manifestDigest,+ rawManifestSha256,+ };+ this.write(data);+ return true;+ }+/** 换源落位前失败时,将旧路由和原有默认安装退订状态一起原子恢复。 */restoreInstallation(record: PluginMarketInstallationRecord,@@ -324,7 +389,11 @@ export class PluginMarketLedger {restoreDisconnectedInstallation(expected: PluginMarketInstallationRecord,userId: string,+ rawManifestSha256?: string,): boolean {+ if (rawManifestSha256 !== undefined && !/^[a-f0-9]{64}$/.test(rawManifestSha256)) {+ return false;+ }const data = this.read();const current = data.installations[expected.ghostId];if (@@ -343,6 +412,7 @@ export class PluginMarketLedger {: current.source,installed: true,updatedAt: new Date().toISOString(),+ ...(rawManifestSha256 !== undefined ? { rawManifestSha256 } : {}),};const remainingOptOuts = (data.defaultInstallOptOuts[userId] ?? []).filter((pluginId) => pluginId !== current.pluginId,diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 3f21d6c658..771d0e7c87 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -19,7 +19,6 @@ import {isOfficialGhostId,isValidGhostId,validateGhostManifest,- type GhostManifest,type InstalledGhost,} from '../../shared/ghost.js';import { isIpcError } from '../../shared/ipc-errors.js';@@ -73,8 +72,7 @@ import {readBoundedFileNoFollowWithStat,} from '../utils/readBoundedFile.js';import {- readInstalledGhostManifest,- readInstalledGhostManifestDigestFormats,+ readInstalledGhostManifestSnapshot,} from '../installedGhostManifest.js';import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';import { ghostBrokerRedirectPortInstallError } from '../cindy-brain/ghostBrokerRedirectPort.js';@@ -87,6 +85,13 @@ import {ghostManifestDigest,type PluginMarketInstallationRecord,} from './ledger.js';+import {+ installedMarketManifestIdentity,+ installedIdentityMatchesManifest,+ legacyManifestIdentityMatches,+ verifyInstalledMarketManifest,+ type InstalledMarketManifestIdentity,+} from './installedManifestIdentity.js';import type { DiscoveredMarketPlugin } from './sources/discover.js';import { checkGitPreflight, type GitPreflightResult } from './sources/preflight.js';import { MarketSourceManager } from './sources/index.js';@@ -183,9 +188,8 @@ function defaultInstallSubject(owner: ActiveAppSession): string {function recordFrom(plugin: VisiblePluginSummary | VisiblePluginDetail,source: PluginMarketInstallationRecord['source'],- installed: InstalledGhost,+ identity: InstalledMarketManifestIdentity,): PluginMarketInstallationRecord {- const rawManifest = installedGhostRawManifest(installed.dir);return {pluginId: plugin.id,ghostId: plugin.ghostId,@@ -197,7 +201,8 @@ function recordFrom(source,installed: true,updatedAt: new Date().toISOString(),- ...(rawManifest ? { manifestDigest: ghostManifestDigest(rawManifest) } : {}),+ manifestDigest: identity.legacyManifestDigest,+ rawManifestSha256: identity.rawManifestSha256,};}@@ -229,8 +234,8 @@ function assertDetailMatchesSummary(function legacyRecordFrom(plugin: VisiblePluginSummary,ghost: InstalledGhost,+ identity: InstalledMarketManifestIdentity,): PluginMarketInstallationRecord {- const rawManifest = installedGhostRawManifest(ghost.dir);return {pluginId: plugin.id,ghostId: plugin.ghostId,@@ -242,7 +247,8 @@ function legacyRecordFrom(source: 'legacy-adopted',installed: true,updatedAt: new Date().toISOString(),- ...(rawManifest ? { manifestDigest: ghostManifestDigest(rawManifest) } : {}),+ manifestDigest: identity.legacyManifestDigest,+ rawManifestSha256: identity.rawManifestSha256,};}@@ -302,20 +308,11 @@ function stripDirectionalControls(text: string): string {}/* eslint-enable no-control-regex */-function installedGhostRawManifest(dir: string): GhostManifest | null {- const parsed = readInstalledGhostManifest(dir, GHOST_MANIFEST_MAX_BYTES);- return parsed.ok ? parsed.manifest : null;-}--function installedGhostRawManifestDigest(+function readInstalledMarketManifestIdentity(dir: string,- expectedDigest?: string,-): string | null {- const digests = readInstalledGhostManifestDigestFormats(dir, GHOST_MANIFEST_MAX_BYTES).map(- ghostManifestDigest,- );- if (expectedDigest !== undefined && digests.includes(expectedDigest)) return expectedDigest;- return digests[0] ?? null;+): InstalledMarketManifestIdentity | null {+ const result = readInstalledGhostManifestSnapshot(dir, GHOST_MANIFEST_MAX_BYTES);+ return result.ok ? installedMarketManifestIdentity(result.snapshot) : null;}/**@@ -430,6 +427,7 @@ function serverRecordMatchesInstalledGhost(pluginId: string,ghost: InstalledGhost,record: PluginMarketInstallationRecord | null,+ identity = readInstalledMarketManifestIdentity(ghost.dir),): boolean {if (!record?.installed ||@@ -438,9 +436,11 @@ function serverRecordMatchesInstalledGhost() {return false;}- return (- record.manifestDigest === undefined ||- record.manifestDigest === installedGhostRawManifestDigest(ghost.dir, record.manifestDigest)+ return Boolean(+ identity &&+ verifyInstalledMarketManifest(record, identity, {+ allowLegacyRecordWithoutDigest: true,+ }));}@@ -470,7 +470,8 @@ function sameMarketInstallation(current.releaseId === expected.releaseId &¤t.version === expected.version &¤t.sha256 === expected.sha256 &&- current.manifestDigest === expected.manifestDigest+ current.manifestDigest === expected.manifestDigest &&+ current.rawManifestSha256 === expected.rawManifestSha256);}@@ -491,7 +492,8 @@ function sameDisconnectedMarketInstallation(&& current.source === expected.source&& current.updatedAt === expected.updatedAt&& current.sourceKey === expected.sourceKey- && current.manifestDigest === expected.manifestDigest,+ && current.manifestDigest === expected.manifestDigest+ && current.rawManifestSha256 === expected.rawManifestSha256,);}@@ -501,15 +503,15 @@ interface LocalInstallSnapshot {ghostsById: ReadonlyMap<string, InstalledGhost>;/** Parsed provenance records from one ledger read. */installations: Readonly<Record<string, PluginMarketInstallationRecord>>;- /** 每个已装插件的 locale 无关 manifest 摘要(一次快照只读一遍盘)。 */- rawDigestByGhostId: ReadonlyMap<string, string | null>;+ /** 每个已装插件的 locale 无关 Manifest 身份(一次快照只读一遍盘)。 */+ manifestIdentityByGhostId: ReadonlyMap<string, InstalledMarketManifestIdentity | null>;}/** 未登录浏览公开目录时不读本机账本 / 已装列表,避免带出上一账号的安装态。 */const EMPTY_LOCAL_INSTALL_SNAPSHOT: LocalInstallSnapshot = {ghostsById: new Map(),installations: {},- rawDigestByGhostId: new Map(),+ manifestIdentityByGhostId: new Map(),};/**@@ -635,6 +637,7 @@ export class PluginMarketService {requireSameMarketOwner(owner);const ledger = this.ledgerForOwner(owner);await this.ledgerMutation;+ await this.backfillInstalledManifestIdentities(ledger, owner);const reconcileCustomUpdates = async (): Promise<'completed' | 'failed'> => {const completed = await this.applyAutomaticUpgrades([],@@ -700,6 +703,7 @@ export class PluginMarketService {requireSameMarketOwner(owner);this.rememberCurrentOrganization(currentOrganization);const ledger = this.ledgerForOwner(owner);+ await this.backfillInstalledManifestIdentities(ledger, owner);await this.adoptLegacyInstallations(plugins, ledger, owner);await this.recoverDisconnectedMarketInstallations(plugins, ledger, owner);await this.backfillOfficialCindyGithubTrust(ledger, owner);@@ -1293,18 +1297,18 @@ export class PluginMarketService {.find((ghost) => ghost.manifest.id === plugin.ghostId);const sourceKey = marketSourceKey(discovered.config.source);const currentRecord = ledger.installationForGhost(plugin.ghostId);- // 选择时刻的已装内容摘要:打包窗口内不能换掉当前包。v2 存量记录可继续- // 使用升级前的 slots 摘要;新记录使用当前稳定投影。- const reviewInstalledDigest = existing- ? installedGhostRawManifestDigest(existing.dir, currentRecord?.manifestDigest)+ // 选择时刻的已装 Manifest 身份:打包窗口内不能换掉当前包。raw 字段+ // 存在时只认原始字节;旧记录由集中 legacy adapter 兼容核对。+ const reviewInstalledIdentity = existing+ ? readInstalledMarketManifestIdentity(existing.dir): null;const matchesSelectedRoute = Boolean(existing &¤tRecord?.installed &¤tRecord.pluginId === pluginId &¤tRecord.sourceKey === sourceKey &&- currentRecord.manifestDigest != null &&- currentRecord.manifestDigest === reviewInstalledDigest,+ reviewInstalledIdentity &&+ verifyInstalledMarketManifest(currentRecord, reviewInstalledIdentity),);if (existing && !matchesSelectedRoute && options.allowSourceReplacement !== true) {throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');@@ -1370,13 +1374,20 @@ export class PluginMarketService {: 'Plugin was uninstalled while the install was packaging',);}+ const currentIdentity = current+ ? readInstalledMarketManifestIdentity(current.dir)+ : null;if (current &&- installedGhostRawManifestDigest(current.dir, reviewInstalledDigest ?? undefined) !==- reviewInstalledDigest+ reviewInstalledIdentity &&+ (!currentIdentity ||+ currentIdentity.rawManifestSha256 !== reviewInstalledIdentity.rawManifestSha256)) {throwIpcError('PRECONDITION_FAILED', 'Installed Plugin changed during the install');}+ if (current && !reviewInstalledIdentity && options.allowSourceReplacement !== true) {+ throwIpcError('PRECONDITION_FAILED', 'Installed Plugin manifest is unreadable');+ }// raw manifest 摘要不含 Host receipt;内容未变但批准态变化也必须拒绝。assertCustomApprovalStateUnchanged(current ?? null);},@@ -1392,8 +1403,8 @@ export class PluginMarketService {record?.installed &&record.pluginId === pluginId &&record.sourceKey === sourceKey &&- record.manifestDigest != null &&- record.manifestDigest === reviewInstalledDigest,+ reviewInstalledIdentity &&+ verifyInstalledMarketManifest(record, reviewInstalledIdentity),);if (existing && !routeStillMatches && options.allowSourceReplacement !== true) {throwIpcError('PRECONDITION_FAILED', 'Installed Plugin source changed');@@ -1421,14 +1432,14 @@ export class PluginMarketService {// 溯源写入仍在上面那把 ghost 锁内(afterCommit 由 commit 段调用):// 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。// 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation。- afterCommit: async (_installed, packagedManifest) => {+ afterCommit: async (_installed, _packagedManifest, evidence) => {// 这里已在 owner mutation lease 与同 id 安装锁内,且 ledger 绑定的是操作// 开始时捕获的 owner。切号终止等待超时后当前 generation 可能已经推进,// 但包既已落位,就仍须把溯源写回旧 owner;不能再读取当前 session 拒绝。- // packGhostDirToFile 返回的是写入真实临时包的 canonical manifest;- // Main 随后复验并用包 SHA 钉死同一文件,因此无需在包已经落位后- // 再读一次目录。后置 I/O 失败不应把成功安装误报成失败或漏写来源。- const manifestDigest = ghostManifestDigest(packagedManifest);+ // evidence 来自 Main 对真实临时包的复验,且包 SHA 钉死后续落位的+ // 同一文件,因此无需在包已经落位后再读一次目录。后置 I/O 失败+ // 不应把成功安装误报成失败或漏写来源。+ const manifestDigest = evidence.legacyManifestDigest;await this.withCapturedLedgerMutation(ledger, () => {ledger.upsertInstallation({pluginId,@@ -1447,6 +1458,7 @@ export class PluginMarketService {// 摘要来自实际临时包的 canonical manifest,不是发现快照,也不是// 安装返回的本地化 ghost.manifest;包被替换后不会被当成同源更新。manifestDigest,+ rawManifestSha256: evidence.rawManifestSha256,});});replacedRoute = null;@@ -1597,6 +1609,7 @@ export class PluginMarketService {const releaseId = customMarketReleaseId(config.name, plugin.ghostId, plugin.version);const ghost = local.ghostsById.get(plugin.ghostId);const record = local.installations[plugin.ghostId];+ const identity = local.manifestIdentityByGhostId.get(plugin.ghostId) ?? null;// pluginId + 来源指纹 + 安装时 manifest 摘要全部对上时,// 该条目才是当前自动更新路由。其它同 id 条目仍可被用户显式选择替换。const matchesUpdateRoute = Boolean(@@ -1604,8 +1617,8 @@ export class PluginMarketService {record?.installed &&record.pluginId === pluginId &&record.sourceKey === marketSourceKey(config.source) &&- record.manifestDigest != null &&- record.manifestDigest === local.rawDigestByGhostId.get(plugin.ghostId),+ identity &&+ verifyInstalledMarketManifest(record, identity),);// conflict 是「不能作为自动更新」的内部投影,不是不可安装;// Renderer 会把它呈现为用户显式的「替换」操作。@@ -1875,11 +1888,16 @@ export class PluginMarketService {},}: {}),- afterCommitInLock: async (committed) => {+ afterCommitInLock: async (_committed, evidence) => {// 包已落位且仍持原 owner mutation lease;即使切号终止等待超时推进了// 当前 generation,也必须把来源写进操作开始时捕获的旧 owner 账本。await this.withCapturedLedgerMutation(ledger, () => {- ledger.upsertInstallation(recordFrom(plugin, 'market', committed));+ ledger.upsertInstallation(recordFrom(plugin, 'market', {+ manifest: evidence.canonicalManifest,+ rawManifestSha256: evidence.rawManifestSha256,+ legacyManifestDigest: evidence.legacyManifestDigest,+ legacyManifestDigests: [],+ }));});},}).catch((error) => {@@ -1909,8 +1927,9 @@ export class PluginMarketService {): PluginMarketItem {const ghost = local.ghostsById.get(plugin.ghostId);const record = local.installations[plugin.ghostId];+ const identity = local.manifestIdentityByGhostId.get(plugin.ghostId) ?? null;const matchesUpdateRoute = Boolean(- ghost && serverRecordMatchesInstalledGhost(plugin.id, ghost, record ?? null),+ ghost && serverRecordMatchesInstalledGhost(plugin.id, ghost, record ?? null, identity),);// 其它同 id 条目不进入自动更新,但仍可由用户显式选择替换。const conflict = Boolean(ghost && !matchesUpdateRoute);@@ -1941,6 +1960,91 @@ export class PluginMarketService {};}+ /**+ * Add raw manifest identity to released-client records without changing their+ * routing timestamp or legacy digest. This is deliberately per-record and+ * idempotent: a downgraded client may later replace one record and drop the+ * unknown field, so there is no permanent global "migration complete" gate.+ */+ private async backfillInstalledManifestIdentities(+ ledger: PluginMarketLedger,+ owner: ActiveAppSession,+ ): Promise<void> {+ const candidates = Object.values(ledger.read().installations).filter(+ (record) => record.installed && record.rawManifestSha256 === undefined,+ );+ for (const candidate of candidates) {+ await this.withMutation(candidate.pluginId, () =>+ withGhostInstallLock(candidate.ghostId, async () => {+ requireSameMarketOwner(owner);+ const record = ledger.installationForGhost(candidate.ghostId);+ if (!record?.installed || record.rawManifestSha256 !== undefined) return;+ const installed = getGhostManager()+ .list()+ .find((ghost) => ghost.manifest.id === record.ghostId);+ if (!installed) return;+ const identity = readInstalledMarketManifestIdentity(installed.dir);+ if (!identity) return;++ const isServerRecord = record.source === 'market' || record.source === 'legacy-adopted';+ const manager = getGhostManager();+ const approvalEvidence = manager.approvedInstallEvidence?.(record.ghostId) ?? null;+ // Pending or failed mutation recovery is projected as invalid. Never+ // mint a baseline from that intermediate directory for any source.+ if (installed.approval.state === 'invalid') return;+ // An approved server state with no readable evidence can also be a+ // pending mutation journal. Only genuine legacy-unapproved installs+ // may use the legacy digest without receipt evidence.+ if (isServerRecord && installed.approval.state === 'approved' && !approvalEvidence) {+ return;+ }+ const approvedManifestMatches = Boolean(+ approvalEvidence &&+ installedIdentityMatchesManifest(identity, approvalEvidence.approvedManifest),+ );+ if (+ isServerRecord &&+ approvalEvidence &&+ !approvedManifestMatches+ ) {+ return;+ }+ if (+ isServerRecord &&+ approvalEvidence?.packageSha256 !== null &&+ approvalEvidence?.packageSha256 !== undefined &&+ approvalEvidence.packageSha256 !== record.sha256+ ) {+ return;+ }+ if (isServerRecord && approvalEvidence?.packageSha256 === null) {+ if (!approvalEvidence.legacyMigrated) return;+ }+ const legacyDigestMatches = legacyManifestIdentityMatches(record, identity);+ const strongReceiptCanFillMissingLegacyDigest = Boolean(+ isServerRecord &&+ record.manifestDigest === undefined &&+ approvalEvidence &&+ approvalEvidence.packageSha256 === record.sha256 &&+ approvedManifestMatches,+ );+ if (!legacyDigestMatches && !strongReceiptCanFillMissingLegacyDigest) return;++ const backfilled = await this.withLedgerMutation(owner, () =>+ ledger.backfillRawManifestSha256(record, identity.rawManifestSha256),+ );+ if (backfilled) {+ log.info('plugin manifest raw identity backfilled', {+ pluginId: record.pluginId,+ ghostId: record.ghostId,+ source: record.source,+ });+ }+ }),+ );+ }+ }+private async adoptLegacyInstallations(plugins: readonly VisiblePluginSummary[],ledger: PluginMarketLedger,@@ -1958,16 +2062,32 @@ export class PluginMarketService {plugin.ghostId === ghost.manifest.id,);if (matches.length !== 1) continue;- const record = legacyRecordFrom(matches[0], ghost);- await this.withLedgerMutation(owner, () => {- ledger.upsertInstallation(record);- });- installations[record.ghostId] = record;- log.info('legacy plugin adopted into market ledger', {- ghostId: ghost.manifest.id,- pluginId: matches[0].id,- exactCurrentRelease: record.releaseId === matches[0].currentRelease.id,- });+ const plugin = matches[0];+ await this.withMutation(plugin.id, () =>+ withGhostInstallLock(ghost.manifest.id, async () => {+ requireSameMarketOwner(owner);+ if (ledger.installationForGhost(ghost.manifest.id)) return;+ const currentGhost = getGhostManager()+ .list()+ .find((candidate) => candidate.manifest.id === ghost.manifest.id);+ if (!currentGhost) return;+ const identity = readInstalledMarketManifestIdentity(currentGhost.dir);+ if (!identity) return;+ const record = legacyRecordFrom(plugin, currentGhost, identity);+ const adopted = await this.withLedgerMutation(owner, () => {+ if (ledger.installationForGhost(record.ghostId)) return false;+ ledger.upsertInstallation(record);+ return true;+ });+ if (!adopted) return;+ installations[record.ghostId] = record;+ log.info('legacy plugin adopted into market ledger', {+ ghostId: ghost.manifest.id,+ pluginId: plugin.id,+ exactCurrentRelease: record.releaseId === plugin.currentRelease.id,+ });+ }),+ );}}@@ -2050,10 +2170,20 @@ export class PluginMarketService {});return;}- const installedManifestDigest = installedGhostRawManifestDigest(- currentInstalled.dir,- record.manifestDigest,+ const identity = readInstalledMarketManifestIdentity(currentInstalled.dir);+ if (!identity) return;+ const approvedManifestMatches = installedIdentityMatchesManifest(+ identity,+ approvalEvidence.approvedManifest,);+ if (!approvedManifestMatches) {+ log.info('disconnected market recovery skipped', {+ pluginId: record.pluginId,+ ghostId: record.ghostId,+ reason: 'approved-manifest-mismatch',+ });+ return;+ }if (approvalEvidence.packageSha256 === null) {if (!approvalEvidence.legacyMigrated) {log.info('disconnected market recovery skipped', {@@ -2063,23 +2193,23 @@ export class PluginMarketService {});return;}- if (- installedManifestDigest === null- || installedManifestDigest !== ghostManifestDigest(- approvalEvidence.approvedManifest,- )- ) {- log.info('disconnected market recovery skipped', {- pluginId: record.pluginId,- ghostId: record.ghostId,- reason: 'legacy-approved-manifest-mismatch',- });- return;- }}+ const identityMatches = verifyInstalledMarketManifest(record, identity);+ const strongReceiptCanFillMissingLegacyDigest =+ record.rawManifestSha256 === undefined &&+ record.manifestDigest === undefined &&+ approvalEvidence.packageSha256 === record.sha256 &&+ approvedManifestMatches;+ const legacyReceiptCanRestoreWithoutMintingIdentity =+ record.rawManifestSha256 === undefined &&+ record.manifestDigest === undefined &&+ approvalEvidence.packageSha256 === null &&+ approvalEvidence.legacyMigrated &&+ approvedManifestMatches;if (- record.manifestDigest !== undefined- && installedManifestDigest !== record.manifestDigest+ !identityMatches &&+ !strongReceiptCanFillMissingLegacyDigest &&+ !legacyReceiptCanRestoreWithoutMintingIdentity) {log.info('disconnected market recovery skipped', {pluginId: record.pluginId,@@ -2089,7 +2219,13 @@ export class PluginMarketService {return;}const restored = await this.withLedgerMutation(owner, () =>- ledger.restoreDisconnectedInstallation(record, installSubject));+ ledger.restoreDisconnectedInstallation(+ record,+ installSubject,+ legacyReceiptCanRestoreWithoutMintingIdentity+ ? undefined+ : identity.rawManifestSha256,+ ));if (restored) {log.info('disconnected market installation recovered', {pluginId: record.pluginId,@@ -2165,6 +2301,21 @@ export class PluginMarketService {version: currentRecord.version,expectedInstalledApproval: ghostInstallApprovalToken(currentInstalled.approval),officialCindyGithub: true,+ afterCommitInLock: async (_committed, evidence) => {+ const replaced = await this.withCapturedLedgerMutation(ledger, () =>+ ledger.replaceManifestIdentityAfterPackageCommit(+ currentRecord,+ evidence.legacyManifestDigest,+ evidence.rawManifestSha256,+ ),+ );+ if (!replaced) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'cindy-github market record changed during trust backfill',+ );+ }+ },});});requireSameMarketOwner(owner);@@ -2242,10 +2393,13 @@ export class PluginMarketService {// (含 ghost.json 读不出)即视为非服务端安装,不删,与更新路径/连接授权// 的 fail-closed 判据同口径。缺摘要的存量记录放行:被下架的插件已不在// 目录里,digest 迁移永远补不上,fail-closed 会让老安装的合法清理永久失效。+ const identity = readInstalledMarketManifestIdentity(installed.dir);if (- record?.manifestDigest != null &&- installedGhostRawManifestDigest(installed.dir, record.manifestDigest) !==- record.manifestDigest+ !record ||+ !identity ||+ !verifyInstalledMarketManifest(record, identity, {+ allowLegacyRecordWithoutDigest: true,+ })) {return skip(removal, 'manifest-digest-mismatch');}@@ -2504,14 +2658,11 @@ export class PluginMarketService {return {ghostsById: new Map(ghosts.map((ghost) => [ghost.manifest.id, ghost])),installations,- rawDigestByGhostId: new Map(- ghosts.map((ghost) => {- const record = installations[ghost.manifest.id];- return [- ghost.manifest.id,- installedGhostRawManifestDigest(ghost.dir, record?.manifestDigest),- ];- }),+ manifestIdentityByGhostId: new Map(+ ghosts.map((ghost) => [+ ghost.manifest.id,+ readInstalledMarketManifestIdentity(ghost.dir),+ ]),),};}diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex a0628b9001..f6faffc63a 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -6088,10 +6088,24 @@ export function ghostManifestToLegacyV2DigestFormat(source.schemaVersion === 2 &&Array.isArray(source.slots)) {- return withLegacyAuthorSlots({+ const legacy = withLegacyAuthorSlots({...manifest,slots: source.slots.map((slot) => (slot === 'model' ? 'cindy' : slot)),});+ // Reproduce the released v0.1.61 normalized output exactly. Its validator+ // omitted card unless externalLinks was true, and omitted false agent flags;+ // current validators may synthesize empty capability objects from slots.+ const sourceCard = isPlainObject(source.card) ? source.card : null;+ if (sourceCard?.externalLinks === true) legacy.card = { externalLinks: true };+ else delete legacy.card;+ const sourceAgent = isPlainObject(source.agent) ? source.agent : null;+ const legacyAgent: Record<string, true> = {};+ for (const field of ['background', 'errand', 'schedule'] as const) {+ if (sourceAgent?.[field] === true) legacyAgent[field] = true;+ }+ if (Object.keys(legacyAgent).length > 0) legacy.agent = legacyAgent;+ else delete legacy.agent;+ return legacy;}return withLegacyAuthorSlots(manifest);}diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 27655e793c..5e669d17bc 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -118,7 +118,10 @@`defaultInstall`。安装成功默认启用;插件声明哪些能力不改变安装动作是否需要确认,因为安装不设能力确认弹窗。- 市场安装账本是后续更新来源的唯一事实:服务端市场按 `pluginId + releaseId` 路由,- 自定义市场还必须匹配 `sourceKey`;已装目录的 canonical manifest digest 必须与账本一致。+ 自定义市场还必须匹配 `sourceKey`;已装目录的原始 `ghost.json` 字节 SHA-256 必须与账本+ 一致。旧记录缺少 raw 字段时,Host 只能按已发布的 legacy digest 编码核对同一份受限读取+ 的字节,命中后原地补字段且不改 `updatedAt`;raw 字段已经存在但不匹配时必须 fail closed,+ 不得用当前目录覆盖基线。`manifestDigest` 保留旧语义供降级客户端读取,不能改写成 raw SHA。任何同 id 来源冲突或目录漂移都不得被自动覆盖,只能由用户显式选择替换来源。- 所有仍匹配稳定来源的已装插件都静默自动更新,不限 public/organization、也不限`defaultInstall`。更新保持现有启用状态,不弹成功 toast;插件正有调用、派活或 Cindy@@ -230,7 +233,8 @@不允许 `exchange` 或 `setup.requires` 引用,第三方插件不得声明。- `source: "oidc-token"` 是 Host 托管的短时 Cindy Connection JWT:只对当前企业Membership 生效。资格有两条默认基座:当前组织的 Plugin Market organization 安装记录仍有效、- 且安装目录 manifest digest 与记录一致;或企业作者显式使用 `ghost_forge_install`+ 且安装目录 `ghost.json` 的 raw SHA(旧记录迁移前为集中 legacy digest)与记录一致;+ Manifest 与身份必须来自同一次受限读取,禁止分两次读取后分别校验与消费;或企业作者显式使用 `ghost_forge_install`安装、在提交前核对插件 id 与精确注入域名,且插件 id 命中当前组织前缀。手动导入不取得Forge 作者资格。另有一条点名例外:`ghostId` 精确等于 `mivo-canvas` 的组织成员本地安装,在已装 manifest 声明的精确 `oidc-token` host 仅为 `mivo-canvas.dsworks.cn` 时可解析 audience;其它本地插件、个人账号、