Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(plugins): 修复插件核对遗漏并减少切回应用时的重复扫描 (#6667)

bobo573269dfcc72
diff --git a/apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts b/apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts
index 29cf8021f4..d47770d34b 100644
--- a/apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts
+++ b/apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts
@@ -77,11 +77,16 @@ function pipeline() {
source.indexOf('function syncPluginMarketForActiveOwner('),
source.indexOf('function parseOptionalDeviceLinkDeviceId('),
);
+ const scheduleState = source.slice(
+ source.indexOf('let disposeSkillhubAutoSyncAuthListener:'),
+ source.indexOf('let startupDatabaseSizeWarningStatus:'),
+ );
let scope = 'cloud:first:1';
let owner: string | null = 'first';
const market = deferred<'completed'>();
const builtin = vi.fn(async () => 'completed' as const);
const syncMarket = vi.fn(() => market.promise);
+ const foreground = vi.fn(async () => 'completed' as const);
const oauth = vi.fn(async () => true);
const refreshUsage = vi.fn(async () => undefined);
const warn = vi.fn();
@@ -101,15 +106,14 @@ function pipeline() {
getActiveAppSession: () => ({ dataOwnerId: owner }),
runStableOwnerPostCommitTask: builtin,
syncDefaultMarketPlugins: syncMarket,
+ refreshForegroundMarketPlugins: foreground,
refreshPluginUsageBindings: refreshUsage,
reconcileGhostOauthAccountsForActiveOwner: oauth,
};
const compiled = transpileModule(
`
${setup}
- let pluginMarketSyncInFlightScope = null;
- let lastPluginMarketSyncScope = null;
- let lastPluginMarketSyncAt = 0;
+ ${scheduleState}
${sync}
return { syncPluginMarketForActiveOwner };
`,
@@ -121,6 +125,7 @@ function pipeline() {
coordinator,
market,
syncMarket,
+ foreground,
builtin,
oauth,
refreshUsage,
@@ -133,6 +138,50 @@ function pipeline() {
}
describe('production background pipeline', () => {
+ // PR #6667: foreground metadata checks must not reset the full-maintenance
+ // clock or take its writer slot. Fake time verifies the real bootstrap entry
+ // without waiting or introducing any plugin/disk work on focus.
+ it('keeps periodic maintenance due during continuous foreground checks', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ const run = pipeline();
+ run.market.resolve('completed');
+ run.syncPluginMarketForActiveOwner(0, 'periodic');
+ await vi.advanceTimersByTimeAsync(0);
+ for (let i = 0; i < 6; i += 1) {
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ run.syncPluginMarketForActiveOwner(30_000, 'foreground');
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ expect(run.foreground).toHaveBeenCalledTimes(6);
+ expect(run.syncMarket).toHaveBeenCalledTimes(1);
+ run.syncPluginMarketForActiveOwner(30 * 60_000, 'periodic');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(run.syncMarket).toHaveBeenCalledTimes(2);
+ expect(run.syncMarket).toHaveBeenLastCalledWith('periodic');
+ });
+
+ it.each(['resume', 'periodic'] as const)('does not let a pending foreground check suppress %s maintenance', async (trigger) => {
+ vi.useFakeTimers();
+ const run = pipeline();
+ const foreground = deferred<'completed'>();
+ run.foreground.mockImplementation(() => foreground.promise);
+ run.syncPluginMarketForActiveOwner(30_000, 'foreground');
+ await vi.advanceTimersByTimeAsync(0);
+ run.syncPluginMarketForActiveOwner(30_000, trigger);
+ run.syncPluginMarketForActiveOwner(30_000, trigger);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(run.syncMarket).toHaveBeenCalledExactlyOnceWith(trigger);
+ expect(run.foreground).toHaveBeenCalledOnce();
+ foreground.resolve('completed');
+ run.market.resolve('completed');
+ await vi.advanceTimersByTimeAsync(0);
+ run.syncPluginMarketForActiveOwner(30_000, trigger);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(run.syncMarket).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
it('continues OAuth after market timeout and shares its pending writer with wakeup/periodic retries', async () => {
vi.useFakeTimers();
const run = pipeline();
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 354cc1aca1..0fe0c2eacb 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1130,7 +1130,7 @@ import { listActiveClaudeBackgroundActivitySessions } from './maker-host/claude-
import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';
import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';
import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractionBridge.js';
-import { registerPluginMarketIpc, syncDefaultMarketPlugins } from './plugin-market/registerIpc.js';
+import { registerPluginMarketIpc, syncDefaultMarketPlugins, refreshForegroundMarketPlugins } from './plugin-market/registerIpc.js';
import { getPluginMarketService } from './plugin-market/service.js';
import { StableOwnerPostCommitStep } from './stableOwnerPostCommit.js';
import { registerPluginPublisherIpc } from './plugin-publisher/registerIpc.js';
@@ -2542,6 +2542,12 @@ const marketPostCommitStep = new StableOwnerPostCommitStep({
name: 'plugin-market', timeoutMs: 180_000,
warn: (message, meta) => ownerBackgroundLog.warn(message, meta),
});
+// A lightweight catalog request must not occupy the full maintenance slot.
+// The service still coalesces catalog fetches and any overlapping full writes.
+const foregroundMarketPostCommitStep = new StableOwnerPostCommitStep({
+ name: 'plugin-market-foreground', timeoutMs: 180_000,
+ warn: (message, meta) => ownerBackgroundLog.warn(message, meta),
+});
const oauthPostCommitStep = new StableOwnerPostCommitStep({
name: 'plugin-oauth', timeoutMs: 30_000,
warn: (message, meta) => ownerBackgroundLog.warn(message, meta),
@@ -2568,7 +2574,7 @@ authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId
let deferred = false;
const marketOutcome = await marketPostCommitStep.run(scopeKey, async () => {
if (!isCurrent()) return 'deferred';
- return syncDefaultMarketPlugins();
+ return syncDefaultMarketPlugins('owner-ready');
});
if (!isCurrent()) return 'deferred';
if (marketOutcome === 'failed') needsRetry = true;
@@ -3586,7 +3592,7 @@ app.on('browser-window-focus', (_event, win) => {
const focusedAppContent = isAppContentWindow(win);
syncAppFocusState();
if (focusedAppContent) {
- syncPluginMarketForActiveOwner(30_000);
+ syncPluginMarketForActiveOwner(30_000, 'foreground');
// OAuth and system settings may complete outside Cindy. Focus is a
// metadata-only fallback wake-up: each pending plugin is re-assessed, but
// no stored value crosses the change bus.
@@ -4301,6 +4307,8 @@ let disposeProviderAccessAuthListener: (() => void) | null = null;
let pluginMarketSyncInFlightScope: string | null = null;
let lastPluginMarketSyncScope: string | null = null;
let lastPluginMarketSyncAt = 0;
+let lastPluginMarketForegroundScope: string | null = null;
+let lastPluginMarketForegroundAt = 0;
let pluginMarketPeriodicSyncTimer: ReturnType<typeof setInterval> | null = null;
const PLUGIN_MARKET_PERIODIC_SYNC_MS = 30 * 60 * 1000;
@@ -4353,21 +4361,31 @@ function checkDatabaseSizeWarningAtStartup(): void {
}
/** Run market discovery and automatic updates for the current stable owner. */
-function syncPluginMarketForActiveOwner(minIntervalMs = 0): void {
+function syncPluginMarketForActiveOwner(minIntervalMs = 0, trigger: 'foreground' | 'resume' | 'periodic' = 'periodic'): void {
const session = getActiveAppSession();
if (!session.dataOwnerId || isAppSessionBoundaryPending()) return;
const scope = activeOwnerScopeKey();
+ if (trigger === 'foreground') {
+ if (scope === lastPluginMarketForegroundScope && Date.now() - lastPluginMarketForegroundAt < minIntervalMs) return;
+ void foregroundMarketPostCommitStep.run(scope, async () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scope) return 'deferred';
+ lastPluginMarketForegroundScope = scope;
+ lastPluginMarketForegroundAt = Date.now();
+ return refreshForegroundMarketPlugins();
+ });
+ return;
+ }
if (scope === pluginMarketSyncInFlightScope) return;
const now = Date.now();
if (scope === lastPluginMarketSyncScope && now - lastPluginMarketSyncAt < minIntervalMs) {
return;
}
pluginMarketSyncInFlightScope = scope;
- lastPluginMarketSyncScope = scope;
- lastPluginMarketSyncAt = now;
void marketPostCommitStep.run(scope, async () => {
if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scope) return 'deferred';
- return syncDefaultMarketPlugins();
+ lastPluginMarketSyncScope = scope;
+ lastPluginMarketSyncAt = Date.now();
+ return syncDefaultMarketPlugins(trigger);
}).finally(() => {
if (pluginMarketSyncInFlightScope === scope) pluginMarketSyncInFlightScope = null;
});
@@ -9846,7 +9864,7 @@ app.on('ready', async () => {
authCredentialRecovery.request();
authManager.handleResume();
handleProviderModelSystemResume();
- syncPluginMarketForActiveOwner(30_000);
+ syncPluginMarketForActiveOwner(30_000, 'resume');
// device-link:睡醒立即重连 relay,不干等退避计时器 + 心跳判死(最坏合计 ~75s)。
handleDeviceLinkSystemResume();
});
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 9a1f835480..81618d92bf 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -311,6 +311,8 @@ export interface GhostManagerOptions {
namespace: string | null;
packageSha256: string | null;
}) => { pluginId: string } | null;
+ /** Capture ledger facts only for one uninterrupted synchronous registry scan. */
+ marketIdentityForScan?: () => NonNullable<GhostManagerOptions['marketIdentityForInstance']>;
/**
* Market evidence that a bare-id library left by an organization install
* removed before the registry existed belongs to this organization plugin.
@@ -692,6 +694,7 @@ export class GhostManager {
ensureOwner: () => this.ensureCurrentOwnerContextSync(),
registryStore: () => this.instanceRegistryStore(),
listContentEntries: () => this.listContentEntries(),
+ isPresenceUnknown: (relId) => this.isContentPresenceUnknown(relId),
receiptFact: (relId) => this.receiptFact(relId),
censusCandidates: () => collectRootInstallCensusCandidates({
contentRoot: this.contentRootDir(),
@@ -708,6 +711,8 @@ export class GhostManager {
this.receiptStore.captureLegacyFirstPartyEligibilitySync(relId, revision);
},
marketIdentityForInstance: (instance) => this.options.marketIdentityForInstance?.(instance) ?? null,
+ marketIdentityForScan: () => this.options.marketIdentityForScan?.()
+ ?? ((instance) => this.options.marketIdentityForInstance?.(instance) ?? null),
log: {
warn: (message, meta) => { this.options.log?.warn(message, meta); },
},
@@ -837,13 +842,25 @@ export class GhostManager {
return createPluginInstanceRegistryStore(pluginInstanceRegistryPath(this.stateRootDir()));
}
+ private readonly unavailableContentRoots = new Set<string>();
+
+ isInstallationScanComplete(): boolean {
+ return this.unavailableContentRoots.size === 0;
+ }
+
+ private isContentPresenceUnknown(relId: string): boolean {
+ return [...this.unavailableContentRoots].some((root) => relId === root || relId.startsWith(root + '/'));
+ }
+
private listContentEntries(): Array<{ relId: string; dir: string }> {
+ this.unavailableContentRoots.clear();
const root = this.contentRootDir();
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(root, { withFileTypes: true });
- } catch {
- return [];
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
}
const listed = this.listManagedInstallDirs(root);
for (const entry of entries) {
@@ -851,7 +868,9 @@ export class GhostManager {
const dir = path.join(root, entry.name);
try {
if (classifyGhostDirEntrySync(dir) !== 'directory') continue;
- } catch {
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ this.unavailableContentRoots.add(entry.name);
continue;
}
if (!isValidGhostId(entry.name)) {
@@ -1077,12 +1096,23 @@ export class GhostManager {
private async confirmUnconfirmedInstances(): Promise<void> {
- await confirmUnconfirmedInstances({
+ const result = await confirmUnconfirmedInstances({
readEvidence: this.options.readUnconfirmedConfirmationEvidence,
isBlocked: () => this.instanceRegistryService.isBlocked(),
sync: () => this.syncInstanceRegistry(),
ownerContextKey: () => this.currentOwnerContextKey(),
readApproval: (relId) => this.readApproval(relId),
+ orphanPendingNamespace: (record, approval) => {
+ if (approval.state !== 'approved') return undefined;
+ if (hasDeliveryNamespace(approval.receipt)) return { namespace: approval.receipt.namespace ?? null };
+ const classification = this.options.classifyPendingNamespace?.(record.ghostId, true);
+ // An orphan cannot gain census-only Forge-prefix or manual adoption
+ // privileges. A market-derived candidate still needs independent positive
+ // evidence (same approved package, namespace and current organization).
+ if (classification?.kind !== 'commit' || classification.basis === 'forge-current-org' ||
+ classification.basis === 'manual-after-sync' || classification.basis === 'builtin') return undefined;
+ return { namespace: classification.namespace };
+ },
log: this.options.log,
runExclusive: (body) => this.runExclusiveMutation(body),
contentPath: (relId) => this.contentPath(relId),
@@ -1096,6 +1126,17 @@ export class GhostManager {
this.instanceRegistryService.replaceCache(registry);
},
});
+ if (result.mutationFailures > 0) {
+ throw new Error('plugin instance namespace confirmation failed');
+ }
+ if (result.unresolvedPending > 0) {
+ // Evidence may stay absent until the owner/market changes. Preserve the
+ // pending install and let independent maintenance retry, rather than
+ // triggering the startup coordinator's full-batch retry loop.
+ this.options.log?.warn('pending plugin instances await namespace evidence', {
+ pendingCount: result.unresolvedPending,
+ });
+ }
}
resumePendingResidentsOffline(): void {
@@ -1173,7 +1214,9 @@ export class GhostManager {
parents = fs.readdirSync(managedRoot)
.filter((namespace) => namespace === PLUGIN_ROOT_INSTALL_DIR || isValidPluginNamespace(namespace))
.map((namespace) => PLUGIN_NS_INSTALL_ROOT + '/' + namespace);
- } catch {
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return listed;
+ this.unavailableContentRoots.add(PLUGIN_NS_INSTALL_ROOT);
return listed;
}
for (const parent of parents) {
@@ -1182,7 +1225,9 @@ export class GhostManager {
try {
if (classifyGhostDirEntrySync(parentDir) !== 'directory') continue;
entries = fs.readdirSync(parentDir);
- } catch {
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ this.unavailableContentRoots.add(parent);
continue;
}
for (const entry of entries) {
@@ -1191,7 +1236,9 @@ export class GhostManager {
const dir = path.join(parentDir, entry);
try {
if (classifyGhostDirEntrySync(dir) === 'directory') listed.push({ relId, dir });
- } catch {
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ this.unavailableContentRoots.add(relId);
continue;
}
}
@@ -2630,6 +2677,7 @@ export class GhostManager {
const registry = this.instanceRegistryService.sync({
listContentEntries: () => entries,
receiptFact: (relId) => this.receiptFact(relId, readReceipt(relId)),
+ isPresenceUnknown: (relId) => this.isContentPresenceUnknown(relId),
});
const result = this.projectListedEntries(entries, readReceipt);
result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));
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 0eb24e182f..af1fc41072 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -104,6 +104,35 @@ function goodManifest(id = 'hello'): Record<string, unknown> {
}
describe('GhostManager enable revision boundary', () => {
+ // Unit regression: an unreadable installation subtree used to become an empty
+ // scan and persist active:false. Exercise list(), retain the approved install
+ // and registry bytes, then recover without reinstalling (compatibility §5).
+ it.each(['root', 'namespaces', 'namespace'] as const)(
+ 'does not persist missing installations when the %s directory cannot be read',
+ async (scope) => {
+ await manager.install(await makeCindy('unreadable.cindy', goodManifest()));
+ expect(manager.list()[0].enabled).toBe(true);
+ const registryPath = path.join(workDir, 'ghosts-install-state', 'plugin-instances.v2.json');
+ const before = fs.readFileSync(registryPath, 'utf8');
+ const target = scope === 'root' ? rootDir : scope === 'namespaces'
+ ? path.join(rootDir, '_ns') : path.join(rootDir, '_ns', '_root');
+ const realReaddir = fs.readdirSync;
+ const read = vi.spyOn(fs, 'readdirSync').mockImplementation(((dir: never, options: never) => {
+ if (String(dir) === target) throw Object.assign(new Error('scan unavailable'), { code: 'EACCES' });
+ return realReaddir(dir, options);
+ }) as never);
+ try {
+ if (scope === 'root') expect(() => manager.list()).toThrow('scan unavailable');
+ else {
+ expect(manager.list()).toEqual([]);
+ expect(manager.isInstallationScanComplete()).toBe(false);
+ }
+ expect(fs.readFileSync(registryPath, 'utf8')).toBe(before);
+ } finally { read.mockRestore(); }
+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });
+ },
+ );
+
// Regression: one list() used two validated receipt reads per plugin. Unit
// coverage also rejects a cross-call cache: the next scan must see revocation.
it('reads each receipt once per scan and observes changed approval on the next scan', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostDisplayListIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostDisplayListIpc.test.ts
new file mode 100644
index 0000000000..62a4e917a4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostDisplayListIpc.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { InstalledGhost } from '../../../shared/ghost.js';
+import { createGhostDisplayListHandler } from '../ghostDisplayListIpc.js';
+
+// Unit: sendSync must reply during filesystem failures without leaking the last
+// account's roster or hiding a genuine empty installation list after recovery.
+describe('plugin display list recovery', () => {
+ const ghost = { manifest: { id: 'hello' }, enabled: true } as InstalledGhost;
+ function harness() {
+ const state = { scope: 'owner-a:1', pending: false, complete: true };
+ const list = vi.fn(() => [ghost]);
+ const warn = vi.fn();
+ const handler = createGhostDisplayListHandler({
+ scopeKey: () => state.scope, isBoundaryPending: () => state.pending,
+ isScanComplete: () => state.complete, list, warn,
+ });
+ return { state, list, warn, handler };
+ }
+
+ it('retains a complete roster during partial and failed scans, then observes a genuine removal', () => {
+ const h = harness();
+ expect(h.handler().ghosts).toEqual([ghost]);
+ h.state.complete = false;
+ h.list.mockReturnValue([]);
+ expect(h.handler().ghosts).toEqual([ghost]);
+ h.list.mockImplementationOnce(() => { throw new Error('unavailable'); });
+ expect(h.handler().ghosts).toEqual([ghost]);
+ expect(h.warn).toHaveBeenCalledOnce();
+ h.state.complete = true;
+ expect(h.handler().ghosts).toEqual([]);
+ });
+
+ it.each(['boundary', 'owner'] as const)('never reuses a previous roster after an %s change', (change) => {
+ const h = harness();
+ h.handler();
+ if (change === 'boundary') h.state.pending = true;
+ else h.state.scope = 'owner-b:2';
+ h.list.mockImplementation(() => { throw new Error('unavailable'); });
+ expect(h.handler().ghosts).toEqual([]);
+ h.state.pending = false;
+ expect(h.handler().ghosts).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistryService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistryService.test.ts
index 0c089858fd..51d7a5635f 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistryService.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginInstanceRegistryService.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
emptyPluginInstanceRegistry,
@@ -26,6 +26,8 @@ function memoryStore(initial: PluginInstanceRegistry): PluginInstanceRegistrySto
function service(options: {
registry: PluginInstanceRegistry;
relIds?: string[];
+ log?: { warn(message: string, meta?: Record<string, unknown>): void };
+ receiptRevision?: string;
marketIdentityForInstance?: (instance: {
ghostId: string;
contentRelId: string;
@@ -42,13 +44,14 @@ function service(options: {
ghostId: relId,
hasNamespace: false,
namespace: null,
- revision: 'rev-1',
+ revision: options.receiptRevision ?? 'rev-1',
packageSha256: 'ab'.repeat(32),
}),
censusCandidates: () => [],
readApproval: () => ({ state: 'missing' }),
recordLegacyEligibility: () => {},
marketIdentityForInstance: options.marketIdentityForInstance,
+ log: options.log,
});
return { created, store };
}
@@ -79,13 +82,85 @@ describe('plugin instance registry service', () => {
namespaceState: 'pending',
pluginId: null,
source: 'legacy',
- receiptRevision: null,
+ receiptRevision: 'rev-1',
packageSha256: null,
active: true,
},
},
};
expect(pendingCensusMismatches(registry)).toEqual(['hello:pending-but-not-listed']);
+ // Repeated scans of one defect should not flood logs; periodic summaries
+ // and a new owner/cache lifecycle still report the outstanding problem.
+ const warn = vi.fn();
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000);
+ try {
+ const options = { registry, relIds: ['hello'], log: { warn }, receiptRevision: 'rev-1' };
+ const { created } = service(options);
+ created.sync();
+ created.sync();
+ created.sync();
+ expect(warn).toHaveBeenCalledTimes(1);
+ clock.mockReturnValue(301_000);
+ created.sync();
+ expect(warn).toHaveBeenLastCalledWith(expect.any(String), {
+ mismatches: ['hello:pending-but-not-listed'], repeatedChecks: 3,
+ });
+ created.sync();
+ created.sync();
+ options.receiptRevision = 'rev-2';
+ created.sync();
+ expect(warn).toHaveBeenCalledTimes(3);
+ // A changed receipt is a new anomaly, not another repeat of the old one.
+ expect(warn).toHaveBeenLastCalledWith(expect.any(String), {
+ mismatches: ['hello:pending-but-not-listed'], repeatedChecks: 1,
+ });
+ created.clear();
+ created.sync();
+ expect(warn).toHaveBeenCalledTimes(4);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
+ // Unit regression for PR #6667: even suppressed warnings used to search
+ // every instance again for each mismatch. Count record reads through sync(),
+ // not wall-clock time; the existing single-row test cannot expose this cost.
+ it('bounds mismatch diagnostic work by the number of registered instances', () => {
+ const relIds = Array.from({ length: 8 }, (_, index) => `plugin-${index}`);
+ let relIdReads = 0;
+ const registry: PluginInstanceRegistry = {
+ ...emptyPluginInstanceRegistry(),
+ census: { completedAt: NOW, pendingRelIds: [] },
+ instances: Object.fromEntries(relIds.map((relId) => [relId, {
+ instanceKey: relId,
+ get contentRelId() { relIdReads += 1; return relId; },
+ ghostId: relId,
+ namespace: null,
+ namespaceState: 'pending' as const,
+ pluginId: null,
+ source: 'legacy' as const,
+ receiptRevision: 'rev-1',
+ packageSha256: null,
+ active: true,
+ }])),
+ };
+ const warn = vi.fn();
+ const { created } = service({ registry, log: { warn } });
+ const scan = {
+ listContentEntries: () => [],
+ receiptFact: () => null,
+ isPresenceUnknown: () => true,
+ };
+ for (let round = 0; round < 2; round += 1) {
+ relIdReads = 0;
+ created.sync(scan);
+ expect(relIdReads).toBeLessThanOrEqual(relIds.length * 5);
+ }
+ expect(warn).toHaveBeenCalledOnce();
+ expect(warn).toHaveBeenCalledWith(expect.any(String), {
+ mismatches: relIds.map((relId) => `${relId}:pending-but-not-listed`),
+ repeatedChecks: 1,
+ });
});
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
index 0096c0468a..7e3b03d040 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost.js';
import { PluginMarketLedger } from '../../plugin-market/ledger.js';
+import { StableOwnerPostCommitCoordinator } from '../../stableOwnerPostCommit.js';
import { GhostManager, type GhostManagerOptions } from '../GhostManager.js';
import { resolveGhostFirstPartyPrivilege } from '../ghostFirstPartyPrivilege.js';
import {
@@ -173,6 +174,87 @@ async function stampLegacyOrganizationInstall(id = 'hello', withSkill = false):
}
describe('GhostManager namespace migration census', () => {
+ // Unit regression: a persisted pending row outside the census was skipped by
+ // both migration and confirmation. Recover only from positive market facts;
+ // keep the physical instance, approval, enabled state and skill snapshot.
+ it.each(['market', 'missing', 'forge-stamped', 'write-failed', 'binding-before-lock', 'binding-before-commit'])('handles an orphan pending record without inventing migration eligibility (evidence=%s)', async (evidence) => {
+ const positive = evidence === 'market';
+ const bindingChanged = evidence.startsWith('binding-');
+ await plantLegacyInstall('hello', true, evidence === 'forge-stamped' ? 'agent-forge' : undefined);
+ const approved = receiptStore().read('hello');
+ if (approved.state !== 'approved') throw new Error('expected approved install');
+ await receiptStore(mutateSnapshot).write({ ...approved.receipt, packageSha256: 'a'.repeat(64) }, {
+ skillSourceDir: path.join(rootDir, 'hello'),
+ });
+ manager.ensureNamespaceMigrationCensus();
+ manager.list();
+ const registryPath = path.join(workDir, 'ghosts-install-state', 'plugin-instances.v2.json');
+ const registry = JSON.parse(fs.readFileSync(registryPath, 'utf8'));
+ registry.census.pendingRelIds = [];
+ if (bindingChanged) registry.instances.hello.pluginId = 'plugin-a';
+ fs.writeFileSync(registryPath, JSON.stringify(registry));
+ if (evidence === 'forge-stamped') {
+ const current = receiptStore().read('hello');
+ if (current.state !== 'approved') throw new Error('expected approved install');
+ await receiptStore(mutateSnapshot).write({ ...current.receipt, namespace: 'acme' }, {
+ skillSourceDir: path.join(rootDir, 'hello'),
+ });
+ }
+ let evidenceReads = 0;
+ manager = createManager({
+ mutateSnapshot,
+ classifyPendingNamespace: () => ({ kind: 'commit', namespace: 'acme', basis: 'market-organization' }),
+ readUnconfirmedConfirmationEvidence: () => {
+ evidenceReads += 1;
+ // Simulate a binding replacement at either async commit boundary.
+ // A matching old package must not confirm the replacement plugin.
+ if (bindingChanged && evidenceReads === (evidence === 'binding-before-lock' ? 1 : 2)) {
+ const changed = JSON.parse(fs.readFileSync(registryPath, 'utf8'));
+ changed.instances.hello.pluginId = 'plugin-b';
+ fs.writeFileSync(registryPath, JSON.stringify(changed));
+ }
+ return {
+ marketRecords: positive || evidence === 'write-failed' || bindingChanged ? [{ namespace: 'acme', organizationId: 'org-acme', scope: 'organization' as const, installed: true, packageSha256: 'a'.repeat(64) }] : undefined,
+ packageSha256: 'a'.repeat(64),
+ forgeSelfTest: evidence === 'forge-stamped',
+ currentOrganization: { organizationId: 'org-acme', orgSlug: 'acme' },
+ };
+ },
+ });
+ // Waiting for positive evidence must preserve the install without making
+ // the startup coordinator repeatedly scan the entire plugin market.
+ const scheduleRetry = vi.fn();
+ const startup = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey: 'owner:1', dataOwnerId: 'owner', stable: true }),
+ warn: vi.fn(), scheduleRetry,
+ });
+ const maintenance = vi.fn(async () => {
+ await manager.reconcilePendingRootNamespaces(true);
+ return 'completed' as const;
+ });
+ startup.setTask(maintenance);
+ const failedWrite = evidence === 'write-failed'
+ ? vi.spyOn(GhostInstallReceiptStore.prototype, 'write').mockRejectedValueOnce(new Error('receipt write failed'))
+ : null;
+ try {
+ await expect(startup.ensure('startup')).resolves.toBe(failedWrite ? 'failed' : 'completed');
+ if (failedWrite) expect(scheduleRetry).toHaveBeenCalledOnce();
+ else {
+ await startup.ensure('stable-again');
+ expect(scheduleRetry).not.toHaveBeenCalled();
+ }
+ } finally {
+ failedWrite?.mockRestore();
+ }
+ expect(maintenance).toHaveBeenCalledOnce();
+ const installed = manager.list()[0];
+ expect(installed).toMatchObject({ enabled: true, namespaceState: positive ? 'confirmed' : 'pending' });
+ expect(installedGhostStoragePart(installed)).toBe('hello');
+ expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);
+ expect(await manager.verifyApprovedSkillSnapshot(installed)).toBe(true);
+ if (positive) expect(installed.namespace).toBe('acme');
+ });
+
it.each([false, true])('repairs the same release in a migrated bare directory without changing storage identity (enabled=%s)', async (enabled) => {
const archive = vi.fn();
manager = createManager({ mutateSnapshot, onArchiveSourceState: archive });
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
index 9011fadfb1..a4044465e4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import { createNamespaceMigrationHost, type NamespaceMigrationHostDeps } from '../pluginNamespaceMigrationHost.js';
+import { parseInstalledGhostManifest } from '../../installedGhostManifest.js';
+import { confirmUnconfirmedInstance, type PluginInstanceRecord } from '../pluginInstanceRegistry.js';
function deps(overrides: Partial<NamespaceMigrationHostDeps> = {}): NamespaceMigrationHostDeps {
return {
@@ -160,3 +162,58 @@ describe('legacy bare instance reclaim', () => {
expect(host.canReclaimLegacyBareInstance({ ghostId: 'hello', namespace: 'acme', pluginId: 'plugin-a' })).toBe(false);
});
});
+
+// Unit regression: confirmation must keep market identity as well as package
+// identity. Legacy receipts also require approved/stored manifest identities.
+describe('namespace confirmation evidence', () => {
+ it.each([
+ 'matching', 'no-digest', 'changed-content', 'changed-approval', 'not-migrated', 'duplicate', 'other-org',
+ 'other-plugin', 'modern-matching', 'modern-other-plugin', 'unbound-legacy',
+ ])(
+ 'confirms only independently matched installation facts (%s)', (condition) => {
+ const modern = condition.startsWith('modern-');
+ const parsed = parseInstalledGhostManifest({
+ schemaVersion: 2, id: 'hello', name: 'Hello', version: '1.0.0',
+ kind: 'chip', entry: 'main.js', slots: ['tool'], tools: [{ name: 'hello', description: 'Hello' }],
+ });
+ if (!parsed.ok) throw new Error(parsed.reason);
+ const manifest = parsed.manifest;
+ const record: PluginInstanceRecord = {
+ instanceKey: 'hello', contentRelId: 'hello', ghostId: 'hello', namespace: 'acme',
+ namespaceState: 'unconfirmed', pluginId: condition === 'unbound-legacy' ? null : 'plugin-a', source: 'market',
+ receiptRevision: 'rev-1', packageSha256: modern ? 'a'.repeat(64) : null, active: true,
+ };
+ const market = {
+ pluginId: condition.endsWith('other-plugin') ? 'plugin-b' : 'plugin-a',
+ ghostId: 'hello', namespace: 'acme', releaseId: 'release-a', version: '1.0.0',
+ sha256: 'a'.repeat(64), scope: 'organization' as const, organizationId: 'org-acme',
+ source: 'market' as const, installed: true, updatedAt: '2026-10-01T00:00:00.000Z',
+ ...(condition !== 'no-digest' ? { rawManifestSha256: 'b'.repeat(64) } : {}),
+ };
+ const defaults = deps();
+ const readManifest = vi.fn(() => ({ ok: true, snapshot: {
+ manifest, legacyManualIgnored: false,
+ rawManifestSha256: (condition === 'changed-content' ? 'c' : 'b').repeat(64),
+ releasedLegacyDigestFormat: manifest, legacyDigestFormats: [manifest],
+ } }));
+ const host = createNamespaceMigrationHost(deps({
+ getAuthState: () => ({ isAuthenticated: true, user: {
+ membershipKind: 'org', orgId: condition === 'other-org' ? 'org-other' : 'org-acme', orgSlug: 'acme',
+ } }),
+ getGhostManager: () => ({ ...defaults.getGhostManager(), approvedInstallEvidence: () => ({
+ packageSha256: modern ? 'a'.repeat(64) : null,
+ legacyMigrated: !modern && condition !== 'not-migrated',
+ approvedManifest: condition === 'changed-approval' ? { ...manifest, version: '0.9.0' } : manifest,
+ }) }),
+ getPluginMarketLedger: () => ({ lookupInstallationsForNamespaceMigration: () => ({
+ kind: 'found', records: condition === 'duplicate' ? [market, market] : [market],
+ }) }),
+ readInstalledGhostManifestSnapshot: readManifest,
+ }));
+ const decision = confirmUnconfirmedInstance(record, host.readUnconfirmedConfirmationEvidence(record)!);
+ const confirms = ['matching', 'modern-matching', 'unbound-legacy'].includes(condition);
+ expect(decision).toEqual(confirms ? { namespace: 'acme' } : null);
+ if (modern) expect(readManifest).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/apps/desktop/src/main/cindy-brain/ghostDisplayListIpc.ts b/apps/desktop/src/main/cindy-brain/ghostDisplayListIpc.ts
new file mode 100644
index 0000000000..4bf6445ddd
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostDisplayListIpc.ts
@@ -0,0 +1,36 @@
+import type { InstalledGhost } from '../../shared/ghost.js';
+
+/** Display-only recovery; runtime capability checks must never consume this cache. */
+export function createGhostDisplayListHandler(deps: {
+ scopeKey(): string;
+ isBoundaryPending(): boolean;
+ list(): InstalledGhost[];
+ isScanComplete(): boolean;
+ warn(): void;
+}): () => { ghosts: InstalledGhost[] } {
+ let cached: { scope: string; ghosts: InstalledGhost[] } | null = null;
+ return () => {
+ if (deps.isBoundaryPending()) {
+ cached = null;
+ return { ghosts: [] };
+ }
+ const scope = deps.scopeKey();
+ const previous = cached?.scope === scope ? cached.ghosts : null;
+ const stillCurrent = () => !deps.isBoundaryPending() && deps.scopeKey() === scope;
+ try {
+ const ghosts = deps.list();
+ if (!stillCurrent()) {
+ cached = null;
+ return { ghosts: [] };
+ }
+ if (deps.isScanComplete()) {
+ cached = { scope, ghosts };
+ return { ghosts };
+ }
+ return { ghosts: previous ?? ghosts };
+ } catch {
+ deps.warn();
+ return { ghosts: stillCurrent() ? previous ?? [] : [] };
+ }
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 35a2490d43..46f476015c 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -577,6 +577,7 @@ import { resolveOneshotCatalogModel } from '../utility-model/textOneshotPinOptio
import { hasOneshotProviderCredential } from '../utility-model/oneshotProviderUsability.js';
import { readGhostCindyInflightLimit, relocateGhostCindyPrefs } from './cindyPrefsStore.js';
import { createGhostComposerListHandler } from './ghostComposerIpc.js';
+import { createGhostDisplayListHandler } from './ghostDisplayListIpc.js';
import { GHOST_COMPOSER_LIST_CHANNEL } from '../../shared/ghostComposer.js';
import {
isGhostDisabledForWorkdir,
@@ -1895,14 +1896,17 @@ export function getGhostManager(): GhostManager {
canReclaimLegacyBareInstance: (input) =>
getNamespaceMigrationHost().canReclaimLegacyBareInstance(input),
isNamespaceMigrationBusy: (ghostId) => getNamespaceMigrationHost().isNamespaceMigrationBusy(ghostId),
- marketIdentityForInstance: (instance) => {
+ marketIdentityForScan: () => {
try {
- const lookup = getPluginMarketLedger().lookupInstallationsForNamespaceMigration(instance.ghostId);
- if (lookup.kind !== 'found') return null;
- const pluginId = selectMarketPluginIdForInstance(instance, lookup.records ?? []);
- return pluginId ? { pluginId } : null;
+ const read = getPluginMarketLedger().createNamespaceMigrationLookup();
+ return (instance) => {
+ const lookup = read(instance.ghostId);
+ if (lookup.kind !== 'found') return null;
+ const pluginId = selectMarketPluginIdForInstance(instance, lookup.records ?? []);
+ return pluginId ? { pluginId } : null;
+ };
} catch {
- return null;
+ return () => null;
}
},
canResumePendingResidentOffline: (ghostId) => getNamespaceMigrationHost().canResumePendingResidentOffline(ghostId),
@@ -8974,8 +8978,15 @@ export function registerGhostIpc(): void {
return { ok: true };
});
+ const displayList = createGhostDisplayListHandler({
+ scopeKey: activeOwnerScopeKey,
+ isBoundaryPending: isAppSessionBoundaryPending,
+ list: () => availableGhosts().map(projectGhostForRenderer),
+ isScanComplete: () => getGhostManager().isInstallationScanComplete(),
+ warn: () => log.warn('plugin display roster scan unavailable; retaining last owner projection'),
+ });
ipcMain.on('ghosts:list', (event) => {
- event.returnValue = { ghosts: availableGhosts().map(projectGhostForRenderer) };
+ event.returnValue = displayList();
});
ipcMain.handle(GHOST_COMPOSER_LIST_CHANNEL, createGhostComposerListHandler({
list: availableGhosts,
diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts
index 0954397d62..a39f02115a 100644
--- a/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts
@@ -19,6 +19,7 @@ import {
} from './pluginInstanceRegistry.js';
interface ConfirmationMarketRow {
+ pluginId?: string | null;
installed?: boolean;
namespace?: string | null;
scope?: 'public' | 'personal' | 'organization';
@@ -49,6 +50,7 @@ export function buildUnconfirmedConfirmationEvidence(input: {
currentOrganization: { organizationId: string; orgSlug: string | null } | null;
packageSha256: string | null;
forgeSelfTest: boolean;
+ legacyManifestVerified?: boolean;
}): InstanceConfirmationEvidence {
return {
marketRecords: input.rows === undefined
@@ -61,6 +63,7 @@ export function buildUnconfirmedConfirmationEvidence(input: {
currentOrganization: input.currentOrganization,
packageSha256: input.packageSha256,
forgeSelfTest: input.forgeSelfTest,
+ ...(input.legacyManifestVerified ? { legacyManifestVerified: true } : {}),
};
}
@@ -70,6 +73,7 @@ interface UnconfirmedConfirmationHost {
sync(): PluginInstanceRegistry;
ownerContextKey(): string;
readApproval(relId: string): GhostInstallReceiptReadResult;
+ orphanPendingNamespace?(record: PluginInstanceRecord, approval: GhostInstallReceiptReadResult): { namespace: string | null } | undefined;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
runExclusive<T>(body: () => Promise<T>): Promise<T>;
contentPath(relId: string): string;
@@ -78,19 +82,33 @@ interface UnconfirmedConfirmationHost {
}
/** Confirm unconfirmed rows only when the caller supplies positive evidence. */
-export async function confirmUnconfirmedInstances(host: UnconfirmedConfirmationHost): Promise<void> {
+export async function confirmUnconfirmedInstances(host: UnconfirmedConfirmationHost): Promise<{ unresolvedPending: number; mutationFailures: number }> {
const readEvidence = host.readEvidence;
- if (!readEvidence || host.isBlocked()) return;
+ if (host.isBlocked()) return { unresolvedPending: 0, mutationFailures: 0 };
const registry = host.sync();
- if (host.isBlocked()) return;
+ if (host.isBlocked()) return { unresolvedPending: 0, mutationFailures: 0 };
+ const orphans = new Set(Object.values(registry.instances).filter((record) =>
+ record.active && record.namespaceState === 'pending' && registry.census !== null &&
+ !registry.census.pendingRelIds.includes(record.contentRelId),
+ ).map((record) => record.instanceKey));
+ if (!readEvidence) return { unresolvedPending: orphans.size, mutationFailures: 0 };
+ let mutationFailures = 0;
const ownerContextKey = host.ownerContextKey();
for (const record of Object.values(registry.instances)) {
- if (host.ownerContextKey() !== ownerContextKey) return;
- if (!record.active || record.namespaceState !== 'unconfirmed') continue;
- const evidenceSnapshot = namespaceCommitReceiptSnapshot(host.readApproval(record.contentRelId));
+ if (host.ownerContextKey() !== ownerContextKey) return { unresolvedPending: 0, mutationFailures: 0 };
+ const orphan = orphans.has(record.instanceKey);
+ if (!record.active || (record.namespaceState !== 'unconfirmed' && !orphan)) continue;
+ const initialApproval = host.readApproval(record.contentRelId);
+ const evidenceSnapshot = namespaceCommitReceiptSnapshot(initialApproval);
+ const target = orphan ? host.orphanPendingNamespace?.(record, initialApproval) : record;
+ if (!target) continue;
+ // This is a candidate for evidence checking, not a persisted state change or
+ // an expansion of the frozen upgrade allowlist. Receipt fields alone never confirm it.
+ const candidate: PluginInstanceRecord = orphan
+ ? { ...record, namespace: target.namespace, namespaceState: 'unconfirmed' } : record;
let evidence: InstanceConfirmationEvidence | null | undefined;
try {
- evidence = readEvidence(record);
+ evidence = readEvidence(candidate);
} catch (error) {
host.log?.warn('unconfirmed instance evidence unavailable', {
instanceKey: record.instanceKey,
@@ -99,7 +117,9 @@ export async function confirmUnconfirmedInstances(host: UnconfirmedConfirmationH
continue;
}
if (!evidence) continue;
- const decision = confirmUnconfirmedInstance(record, evidence);
+ // Forge self-tests only restore an already-known namespace. An orphan has
+ // no such history and cannot acquire the census-only Forge exception.
+ const decision = confirmUnconfirmedInstance(candidate, orphan ? { ...evidence, forgeSelfTest: false } : evidence);
if (!decision) continue;
try {
await host.runExclusive(async () => {
@@ -109,12 +129,21 @@ export async function confirmUnconfirmedInstances(host: UnconfirmedConfirmationH
evidenceSnapshot, namespaceCommitReceiptSnapshot(approval),
)) return;
if (approval.state !== 'approved' || approval.receipt.id !== record.ghostId) return;
+ const currentRecord = host.sync().instances[record.instanceKey];
+ if (!currentRecord?.active || currentRecord.pluginId !== record.pluginId || currentRecord.namespaceState !== record.namespaceState ||
+ currentRecord.namespace !== record.namespace || currentRecord.receiptRevision !== record.receiptRevision ||
+ currentRecord.packageSha256 !== record.packageSha256) return;
+ const freshEvidence = readEvidence(candidate);
+ if (!freshEvidence || confirmUnconfirmedInstance(candidate,
+ orphan ? { ...freshEvidence, forgeSelfTest: false } : freshEvidence,
+ )?.namespace !== decision.namespace) return;
let revision = approval.receipt.revision;
let packageSha256 = approval.receipt.packageSha256 ?? record.packageSha256;
const stamped = hasDeliveryNamespace(approval.receipt) &&
(approval.receipt.namespace ?? null) === decision.namespace;
if (!stamped) {
await host.writeReceipt(record.contentRelId, { ...approval.receipt, namespace: decision.namespace });
+ if (host.ownerContextKey() !== ownerContextKey) return;
const written = host.readApproval(record.contentRelId);
if (written.state !== 'approved' || !hasDeliveryNamespace(written.receipt) ||
(written.receipt.namespace ?? null) !== decision.namespace) return;
@@ -123,17 +152,23 @@ export async function confirmUnconfirmedInstances(host: UnconfirmedConfirmationH
}
const current = host.sync();
if (host.isBlocked()) return;
+ const live = current.instances[record.instanceKey];
+ if (!live?.active || live.pluginId !== record.pluginId || live.namespaceState !== record.namespaceState || live.namespace !== record.namespace ||
+ live.receiptRevision !== revision || live.packageSha256 !== packageSha256) return;
const confirmed = confirmInstanceNamespace(current, record.instanceKey, decision.namespace, {
revision, packageSha256,
});
if (confirmed === current) return;
host.writeRegistry(confirmed);
+ orphans.delete(record.instanceKey);
});
} catch (error) {
+ mutationFailures += 1;
host.log?.warn('unconfirmed instance confirmation skipped', {
instanceKey: record.instanceKey,
error: error instanceof Error ? error.message : String(error),
});
}
}
+ return { unresolvedPending: orphans.size, mutationFailures };
}
diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
index f523a4caaf..c2b504dc15 100644
--- a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistry.ts
@@ -83,6 +83,8 @@ export interface InstanceConfirmationEvidence {
orgSlug: string | null;
} | null;
packageSha256?: string | null;
+ /** Main verified a migrated receipt against the installed and market manifest identities. */
+ legacyManifestVerified?: boolean;
/** Approved receipt is an agent-forge self-test for this install. */
forgeSelfTest?: boolean;
}
@@ -261,7 +263,9 @@ function marketEvidenceConfirms(
const market = installed[0]!;
if (market.namespace === undefined || market.namespace !== record.namespace) return false;
const observed = evidence.packageSha256 ?? record.packageSha256 ?? null;
- if (!market.packageSha256 || !observed || market.packageSha256 !== observed) return false;
+ if (!market.packageSha256 || (observed === null
+ ? evidence.legacyManifestVerified !== true
+ : market.packageSha256 !== observed)) return false;
if (!shaDoesNotConflict(evidence.packageSha256, record.packageSha256)) return false;
if (!shaDoesNotConflict(evidence.packageSha256, market.packageSha256)) return false;
if (!shaDoesNotConflict(record.packageSha256, market.packageSha256)) return false;
@@ -285,6 +289,7 @@ function marketEvidenceConfirms(
export function marketRowMatchesUnconfirmedInstance(
row: {
+ pluginId?: string | null;
installed?: boolean;
namespace?: string | null;
scope?: 'public' | 'personal' | 'organization';
@@ -293,6 +298,9 @@ export function marketRowMatchesUnconfirmedInstance(
record: PluginInstanceRecord,
currentOrganization: { organizationId: string; orgSlug: string | null } | null,
): boolean {
+ // Unlabeled legacy installs still use independent package/manifest evidence;
+ // an existing market binding must never be confirmed by a different plugin.
+ if (record.pluginId !== null && row.pluginId !== record.pluginId) return false;
const hasNamespace = hasDeliveryNamespace(row);
if (hasNamespace) return (row.namespace ?? null) === record.namespace;
if (record.namespace === null) return row.scope !== 'organization';
diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts
index 6a3aefe16b..7f1ce6e990 100644
--- a/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceRegistryService.ts
@@ -38,6 +38,7 @@ interface PluginInstanceRegistryServiceDeps {
ensureOwner(): void;
registryStore(): PluginInstanceRegistryStore;
listContentEntries(): Array<{ relId: string; dir: string }>;
+ isPresenceUnknown?(relId: string): boolean;
receiptFact(relId: string): PluginInstanceReceiptFact | null | undefined;
censusCandidates(): NamespaceCensusCandidate[];
readApproval(relId: string): CensusApproval;
@@ -50,6 +51,7 @@ interface PluginInstanceRegistryServiceDeps {
namespace: string | null;
packageSha256: string | null;
}): { pluginId: string } | null;
+ marketIdentityForScan?(): NonNullable<PluginInstanceRegistryServiceDeps['marketIdentityForInstance']>;
log?: PluginInstanceRegistryLogger;
}
@@ -61,17 +63,27 @@ export function pendingCensusMismatches(
registry: PluginInstanceRegistry,
mode: 'privileges' | 'strict' = 'privileges',
): string[] {
+ return pendingCensusMismatchFacts(registry, mode).map(([mismatch]) => mismatch);
+}
+
+/** Keep diagnostic identity with each mismatch so logging never rescans instances. */
+function pendingCensusMismatchFacts(
+ registry: PluginInstanceRegistry,
+ mode: 'privileges' | 'strict' = 'privileges',
+): Array<[string, PluginInstanceRecord['receiptRevision'], PluginInstanceRecord['packageSha256']]> {
if (!registry.census) return [];
const listed = new Set(registry.census.pendingRelIds);
- const mismatches: string[] = [];
+ const mismatches: Array<[string, PluginInstanceRecord['receiptRevision'], PluginInstanceRecord['packageSha256']]> = [];
for (const record of Object.values(registry.instances)) {
if (!record.active) continue;
const isListed = listed.has(record.contentRelId);
+ let suffix: string;
if (record.namespaceState === 'pending' && !isListed) {
- mismatches.push(record.contentRelId + ':pending-but-not-listed');
+ suffix = ':pending-but-not-listed';
} else if (mode === 'strict' && isListed && record.namespaceState !== 'pending') {
- mismatches.push(record.contentRelId + ':listed-but-' + record.namespaceState);
- }
+ suffix = ':listed-but-' + record.namespaceState;
+ } else continue;
+ mismatches.push([record.contentRelId + suffix, record.receiptRevision, record.packageSha256]);
}
return mismatches;
}
@@ -134,12 +146,18 @@ type OpenedRegistry =
export class PluginInstanceRegistryService {
private registry: PluginInstanceRegistry | null = null;
private blocked = false;
+ private mismatchFingerprint = '';
+ private mismatchLoggedAt = 0;
+ private repeatedMismatchChecks = 0;
constructor(private readonly deps: PluginInstanceRegistryServiceDeps) {}
clear(): void {
this.registry = null;
this.blocked = false;
+ this.mismatchFingerprint = '';
+ this.mismatchLoggedAt = 0;
+ this.repeatedMismatchChecks = 0;
}
isBlocked(): boolean {
@@ -195,7 +213,7 @@ export class PluginInstanceRegistryService {
return parsePluginInstallRelId(relId)?.ghostId === relId;
}
- sync(scan: Pick<PluginInstanceRegistryServiceDeps, 'listContentEntries' | 'receiptFact'> = this.deps): PluginInstanceRegistry {
+ sync(scan: Pick<PluginInstanceRegistryServiceDeps, 'listContentEntries' | 'receiptFact' | 'isPresenceUnknown'> = this.deps): PluginInstanceRegistry {
this.deps.ensureOwner();
const store = this.deps.registryStore();
const opened = this.open(store);
@@ -204,6 +222,7 @@ export class PluginInstanceRegistryService {
let registry = opened.registry;
let dirty = false;
const present = new Set<string>();
+ const marketIdentity = this.deps.marketIdentityForScan?.() ?? this.deps.marketIdentityForInstance;
for (const listed of scan.listContentEntries()) {
present.add(listed.relId);
const fact = scan.receiptFact(listed.relId);
@@ -217,7 +236,7 @@ export class PluginInstanceRegistryService {
ghostId,
receipt: fact,
pendingMigration: this.isPendingMigrationRel(listed.relId, registry),
- marketPluginId: this.deps.marketIdentityForInstance?.({
+ marketPluginId: marketIdentity?.({
ghostId,
contentRelId: listed.relId,
namespace: parsePluginInstallRelId(listed.relId)?.namespace ?? null,
@@ -230,7 +249,7 @@ export class PluginInstanceRegistryService {
continue;
}
let next = reconcileInstanceReceipt(existing, { directoryPresent: true, receipt: fact });
- const market = this.deps.marketIdentityForInstance?.({
+ const market = marketIdentity?.({
ghostId: next.ghostId,
contentRelId: next.contentRelId,
namespace: next.namespace,
@@ -245,14 +264,28 @@ export class PluginInstanceRegistryService {
}
}
for (const record of Object.values(registry.instances)) {
- if (record.active && !present.has(record.contentRelId)) {
+ if (record.active && !present.has(record.contentRelId) && !scan.isPresenceUnknown?.(record.contentRelId)) {
registry = upsertInstance(registry, { ...record, active: false });
dirty = true;
}
}
- const mismatches = pendingCensusMismatches(registry);
- if (mismatches.length > 0) {
- this.deps.log?.warn('plugin instance census diverged from namespaceState', { mismatches });
+ const mismatchFacts = pendingCensusMismatchFacts(registry);
+ if (mismatchFacts.length > 0) {
+ const mismatches = mismatchFacts.map(([mismatch]) => mismatch);
+ const fingerprint = JSON.stringify(mismatchFacts.sort());
+ const changed = fingerprint !== this.mismatchFingerprint;
+ this.repeatedMismatchChecks = changed ? 1 : this.repeatedMismatchChecks + 1;
+ if (changed || Date.now() - this.mismatchLoggedAt >= 300_000) {
+ this.deps.log?.warn('plugin instance census diverged from namespaceState', {
+ mismatches, repeatedChecks: this.repeatedMismatchChecks,
+ });
+ this.mismatchFingerprint = fingerprint;
+ this.mismatchLoggedAt = Date.now();
+ this.repeatedMismatchChecks = 0;
+ }
+ } else {
+ this.mismatchFingerprint = '';
+ this.repeatedMismatchChecks = 0;
}
if (dirty) {
try {
diff --git a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
index 0d10b33206..272c0c2f5b 100644
--- a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
@@ -6,7 +6,7 @@
import path from 'node:path';
import { GHOST_INSTALL_MANIFEST_MAX_BYTES } from '../../shared/ghost.js';
-import { installedGhostPhysicalRelId, installedGhostStoragePart } from '../../shared/pluginIdentity.js';
+import { installedGhostPhysicalRelId, installedGhostStoragePart, parsePluginInstallRelId } from '../../shared/pluginIdentity.js';
import type { GhostManifest, InstalledGhost } from '../../shared/ghost.js';
import { isResidentBrowserGhost } from './residentGhost.js';
import {
@@ -17,9 +17,10 @@ import {
type NamespaceClassification,
} from './pluginNamespaceMigration.js';
import { buildUnconfirmedConfirmationEvidence } from './pluginInstanceConfirmation.js';
-import type { InstanceConfirmationEvidence, PluginInstanceRecord } from './pluginInstanceRegistry.js';
+import { marketRowMatchesUnconfirmedInstance, type InstanceConfirmationEvidence, type PluginInstanceRecord } from './pluginInstanceRegistry.js';
import {
hasVerifiedDisconnectedOrganizationInstallation,
+ hasVerifiedLegacyMarketInstallation,
installedMarketManifestIdentity,
} from '../plugin-market/installedManifestIdentity.js';
import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';
@@ -295,26 +296,43 @@ export function createNamespaceMigrationHost(deps: NamespaceMigrationHostDeps):
},
readUnconfirmedConfirmationEvidence(record: PluginInstanceRecord): InstanceConfirmationEvidence {
const currentOrganization = currentOrganizationFacts();
- let packageSha256: string | null = null;
+ let approved: ReturnType<NamespaceMigrationManager['approvedInstallEvidence']> = null;
let forgeSelfTest = false;
try {
- packageSha256 = deps.getGhostManager().approvedInstallEvidence(record.contentRelId)?.packageSha256 ?? null;
+ approved = deps.getGhostManager().approvedInstallEvidence(record.contentRelId);
} catch {
- packageSha256 = null;
+ // Unreadable approval cannot supply recovery evidence.
}
try {
forgeSelfTest = deps.getGhostManager().readApprovedInstallOriginStrict(record.contentRelId) === 'agent-forge';
} catch {
forgeSelfTest = false;
}
- let rows: Parameters<typeof buildUnconfirmedConfirmationEvidence>[0]['rows'];
+ let rows: PluginMarketInstallationRecord[] | undefined;
try {
rows = namespaceMigrationMarketRecordsForGhost(record.ghostId);
} catch {
rows = undefined;
}
+ let legacyManifestVerified = false;
+ if (approved?.legacyMigrated && approved.packageSha256 === null && rows &&
+ parsePluginInstallRelId(record.contentRelId)) {
+ try {
+ const snapshot = deps.readInstalledGhostManifestSnapshot(
+ path.join(deps.brainRootDir(), ...record.contentRelId.split('/')), GHOST_INSTALL_MANIFEST_MAX_BYTES);
+ legacyManifestVerified = hasVerifiedLegacyMarketInstallation({
+ records: rows.filter((row) => row.installed &&
+ marketRowMatchesUnconfirmedInstance(row, record, currentOrganization)),
+ evidence: approved,
+ identity: snapshot.ok && snapshot.snapshot ? installedMarketManifestIdentity(snapshot.snapshot) : null,
+ });
+ } catch {
+ // Preserve the old installation until independent evidence is readable.
+ }
+ }
return buildUnconfirmedConfirmationEvidence({
- rows, record, currentOrganization, packageSha256, forgeSelfTest,
+ rows, record, currentOrganization, packageSha256: approved?.packageSha256 ?? null,
+ forgeSelfTest, legacyManifestVerified,
});
},
canReclaimLegacyBareInstance({ ghostId, namespace, pluginId }): boolean {
diff --git a/apps/desktop/src/main/plugin-market/__tests__/defaultMarketPluginSyncOutcome.test.ts b/apps/desktop/src/main/plugin-market/__tests__/defaultMarketPluginSyncOutcome.test.ts
index a0c3c0b64e..8b3c889370 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/defaultMarketPluginSyncOutcome.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/defaultMarketPluginSyncOutcome.test.ts
@@ -1,7 +1,32 @@
-import { describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { PluginMarketSnapshot } from '../../../shared/pluginMarket';
-import { defaultMarketPluginSyncOutcome } from '../registerIpc';
+import { defaultMarketPluginSyncOutcome, refreshForegroundMarketPlugins } from '../registerIpc';
+
+const foreground = vi.hoisted(() => ({
+ pending: false,
+ refresh: vi.fn<() => Promise<'completed' | 'failed'>>(),
+ snapshot: vi.fn(),
+ notify: vi.fn(),
+}));
+vi.mock('../service.js', () => ({ getPluginMarketService: () => ({
+ refreshCatalogForForeground: foreground.refresh,
+ hasPendingRemovalNotice: () => foreground.pending,
+ snapshot: foreground.snapshot,
+}) }));
+vi.mock('../../cindy-brain/index.js', () => ({
+ sendToTrustedAppWindows: foreground.notify,
+ createWindowGhostInstallConsentPrompt: vi.fn(),
+ getGhostManager: vi.fn(),
+ setGhostUninstallLedgerPreparer: vi.fn(),
+}));
+
+beforeEach(() => {
+ foreground.pending = false;
+ foreground.refresh.mockReset().mockResolvedValue('completed');
+ foreground.snapshot.mockReset();
+ foreground.notify.mockReset();
+});
function snapshot(unavailableReason: string | null): PluginMarketSnapshot {
return {
@@ -46,3 +71,29 @@ describe('defaultMarketPluginSyncOutcome', () => {
})).toBe('completed');
});
});
+
+// PR #6667: foreground removals used to bypass the trusted notification path.
+// Exercise the production entry with no additional snapshot or scan to signal a notice.
+describe('foreground removal notification', () => {
+ it.each(['completed', 'failed', 'rejected'] as const)('signals an existing removal notice after %s maintenance', async (outcome) => {
+ const error = new Error('maintenance failed after removal');
+ foreground.refresh.mockImplementationOnce(async () => {
+ foreground.pending = true;
+ if (outcome === 'rejected') throw error;
+ return outcome;
+ });
+ const refresh = refreshForegroundMarketPlugins();
+ if (outcome === 'rejected') await expect(refresh).rejects.toBe(error);
+ else await expect(refresh).resolves.toBe(outcome);
+ expect(foreground.notify).toHaveBeenCalledExactlyOnceWith('plugin-market:removal-notice-available', undefined);
+ expect(foreground.snapshot).not.toHaveBeenCalled();
+ expect(foreground.pending).toBe(true);
+ });
+
+ it('does not broadcast or start an extra snapshot when the catalog is unchanged', async () => {
+ await expect(refreshForegroundMarketPlugins()).resolves.toBe('completed');
+ expect(foreground.notify).not.toHaveBeenCalled();
+ expect(foreground.snapshot).not.toHaveBeenCalled();
+ expect(foreground.refresh).toHaveBeenCalledOnce();
+ });
+});
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 f1e80f86a1..6b37cb38cc 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -102,7 +102,7 @@ describe('Plugin Market IPC error boundary', () => {
it('runs plugin reconciliation on cold start, foreground, resume and stable owner changes', () => {
const syncStart = registerSource.indexOf(
- 'export async function syncDefaultMarketPlugins(): Promise<DefaultMarketPluginSyncOutcome>',
+ 'export async function syncDefaultMarketPlugins(',
);
const syncEnd = registerSource.indexOf('\n}\n\n/**\n * Preserve stable IPC errors', syncStart);
const syncBody = registerSource.slice(syncStart, syncEnd);
@@ -141,7 +141,8 @@ describe('Plugin Market IPC error boundary', () => {
expect(serviceSource).toContain('await this.applyAutomaticUpgrades(plugins, customDiscovery.entries, owner, ledger)');
expect(serviceSource).toContain('if (error instanceof SilentUpgradeBusyError) {');
- expect(registerSource).toContain('deferReconciliation: true');
+ // Capability boundary: catalog readers cannot initiate install/update/removal maintenance.
+ expect(registerSource).toContain('discoveryOnly: true');
expect(registerSource).toContain('plugin-market:update-consent-holds-changed');
expect(registerSource).toContain('onConsentHoldsChanged:');
expect(ghostPluginPageSource).toContain('const installedGhostMarketKey = useMemo(');
@@ -162,13 +163,13 @@ describe('Plugin Market IPC error boundary', () => {
"if (dataOwnerId === null) return needsRetry ? 'failed' : 'completed';",
);
expect(ownerTaskBody.indexOf('dataOwnerId === null')).toBeLessThan(
- ownerTaskBody.indexOf('syncDefaultMarketPlugins()'),
+ ownerTaskBody.indexOf("syncDefaultMarketPlugins('owner-ready')"),
);
expect(ownerTaskBody).not.toContain("builtinOutcome === 'failed') return builtinOutcome");
expect(ownerTaskBody).toContain("outcome === 'retry-pending' ? 'failed' : outcome");
expect(ownerTaskBody).toContain("builtinOutcome === 'failed'");
expect(ownerTaskBody).toContain('const marketOutcome = await marketPostCommitStep.run(');
- expect(ownerTaskBody).toContain('return syncDefaultMarketPlugins();');
+ expect(ownerTaskBody).toContain("return syncDefaultMarketPlugins('owner-ready');");
expect(ownerTaskBody).toContain("marketOutcome === 'failed'");
expect(ownerTaskBody).toContain("marketOutcome === 'deferred'");
expect(ownerTaskBody).toContain('await reconcileGhostOauthAccountsForActiveOwner()');
@@ -184,7 +185,7 @@ describe('Plugin Market IPC error boundary', () => {
expect(bootstrapSource).not.toContain('syncDefaultPluginsForActiveOwner');
const ownerSyncStart = bootstrapSource.indexOf(
- 'function syncPluginMarketForActiveOwner(minIntervalMs = 0): void',
+ 'function syncPluginMarketForActiveOwner(',
);
const ownerSyncEnd = bootstrapSource.indexOf('\n}\n\nfunction parseOptionalDeviceLinkDeviceId', ownerSyncStart);
const ownerSyncBody = bootstrapSource.slice(ownerSyncStart, ownerSyncEnd);
@@ -195,7 +196,7 @@ describe('Plugin Market IPC error boundary', () => {
expect(ownerSyncBody).toContain('void marketPostCommitStep.run(scope,');
expect(ownerSyncBody).toContain('pluginMarketSyncInFlightScope = null;');
expect(bootstrapSource).toContain('PLUGIN_MARKET_PERIODIC_SYNC_MS = 30 * 60 * 1000');
- expect(bootstrapSource).toContain('syncPluginMarketForActiveOwner(30_000);');
+ expect(bootstrapSource).toContain("syncPluginMarketForActiveOwner(30_000, 'resume');");
});
});
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 155086d03a..77ca4d4883 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
@@ -2,7 +2,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
NS_LEDGER_FILE,
@@ -59,6 +59,24 @@ function sameNameNamespaceHarness(rootInstalled = true) {
}
describe('PluginMarketLedger', () => {
+ // Unit/performance: one synchronous registry scan must not read three ledgers
+ // per installed plugin. The next scan must still observe a changed ledger.
+ it('shares migration ledger reads within a scan without retaining stale authority', () => {
+ const { filePath, ledger } = sameNameNamespaceHarness();
+ const read = vi.spyOn(fs, 'readFileSync');
+ try {
+ const lookup = ledger.createNamespaceMigrationLookup();
+ const count = read.mock.calls.length;
+ expect(lookup('helper')).toMatchObject({ kind: 'found' });
+ expect(lookup('unrelated')).toEqual({ kind: 'absent' });
+ expect(read.mock.calls.length).toBe(count);
+ const raw = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ raw.installations.helper.sha256 = 42;
+ fs.writeFileSync(filePath, JSON.stringify(raw));
+ expect(ledger.createNamespaceMigrationLookup()('helper')).toEqual({ kind: 'invalid' });
+ } finally { read.mockRestore(); }
+ });
+
it.each(['main', 'custom', 'namespaced'] as const)(
'keeps namespace migration invalid instead of absent for a malformed target in %s',
(source) => {
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 56e7237c0f..1362c698e0 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -16,6 +16,7 @@ import {
} from '../../../shared/ghost.js';
const runtime = vi.hoisted(() => ({
listScans: 0,
+ installationScanComplete: true,
onList: undefined as (() => void) | undefined,
confirmLegacyLibraryReattach: vi.fn<(plugin: unknown) => Promise<boolean>>(async () => false),
ghosts: [] as Array<{
@@ -109,6 +110,7 @@ vi.mock('../../cindy-brain/index.js', () => ({
refreshPluginUsageBindings: vi.fn(async () => undefined),
confirmLegacyLibraryReattach: (plugin: unknown) => runtime.confirmLegacyLibraryReattach(plugin),
getGhostManager: () => ({
+ isInstallationScanComplete: () => runtime.installationScanComplete,
resumePendingResidentsOffline: runtime.resumeOfflineResidents,
reconcilePendingRootNamespaces: runtime.reconcilePendingRootNamespaces,
list: () => {
@@ -259,6 +261,7 @@ function deferred(): { promise: Promise<void>; resolve: () => void } {
afterEach(() => {
runtime.listScans = 0;
+ runtime.installationScanComplete = true;
runtime.onList = undefined;
runtime.ghosts = [];
runtime.confirmLegacyLibraryReattach.mockReset();
@@ -1067,6 +1070,77 @@ describe('PluginMarketService migration and defaultInstall', () => {
}
});
+ // Unit regression: focus, icon renewal and mounted catalog consumers could
+ // independently fetch and scan the same owner. Joined callers share one round.
+ it('coalesces concurrent catalog projections and keeps later reads fresh', async () => {
+ const h = harness([]);
+ const results = await Promise.all(Array.from({ length: 3 }, () => h.service.snapshot({ discoveryOnly: true })));
+ expect(results.map((result) => result.items)).toEqual([[], [], []]);
+ expect(h.api.listAll).toHaveBeenCalledTimes(1);
+ expect(runtime.listScans).toBe(1);
+ await h.service.snapshot({ discoveryOnly: true });
+ expect(h.api.listAll).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not add a catalog fetch or installation scan when foreground overlaps full maintenance', async () => {
+ const h = harness([]);
+ const catalog = h.api.listAll.getMockImplementation()!;
+ const gate = deferred();
+ h.api.listAll.mockImplementationOnce(async () => { await gate.promise; return catalog(); });
+ const full = h.service.snapshot();
+ const foreground = h.service.refreshCatalogForForeground();
+ gate.resolve();
+ await Promise.all([full, foreground]);
+ expect(h.api.listAll).toHaveBeenCalledOnce();
+ const overlappingScans = runtime.listScans;
+ runtime.listScans = 0;
+ await h.service.snapshot();
+ // Compare with an explicit full pass, so independent scheduling cannot
+ // silently add disk work when both triggers see the same catalog.
+ expect(overlappingScans).toBe(runtime.listScans);
+ });
+
+ it('rejects a catalog request if its owner changes before asynchronous work begins', async () => {
+ const h = harness([]);
+ const request = h.service.snapshot({ discoveryOnly: true });
+ runtime.session = { ...runtime.session, dataOwnerId: 'user-2', generation: runtime.session.generation + 1 };
+ await expect(request).rejects.toThrow('active account changed');
+ expect(h.api.listAll).not.toHaveBeenCalled();
+ });
+
+ it('does not provision plugins from an incomplete installation scan', async () => {
+ const h = harness([summary({ defaultInstall: true })]);
+ runtime.installationScanComplete = false;
+ await expect(h.service.snapshot()).rejects.toThrow('installation scan is incomplete');
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(h.ledger.read().installations).toEqual({});
+ });
+
+ it('reports a failed namespace transaction instead of marking the round completed', async () => {
+ const h = harness([]);
+ runtime.reconcilePendingRootNamespaces.mockRejectedValueOnce(new Error('namespace receipt write failed'));
+ const outcome = vi.fn();
+ await h.service.snapshot({ onDefaultReconciliationOutcome: outcome });
+ expect(outcome).toHaveBeenCalledWith('failed');
+ });
+
+ it('does not rescan installations on foreground when reconciled catalog facts have not changed', async () => {
+ const items: VisiblePluginSummary[] = [summary()];
+ items[0]!.currentRelease.icon = {
+ url: 'https://icons.test.invalid/icon?signature=old', expiresAt: '2099-01-01T00:00:00.000Z',
+ mimeType: 'image/png', sizeBytes: 42, sha256: 'b'.repeat(64),
+ };
+ const h = harness(items);
+ await h.service.snapshot();
+ runtime.listScans = 0;
+ items[0]!.currentRelease.icon.url = 'https://icons.test.invalid/icon?signature=new';
+ await h.service.refreshCatalogForForeground();
+ expect(runtime.listScans).toBe(0);
+ items[0]!.currentRelease.version = '2.0.0';
+ await h.service.refreshCatalogForForeground();
+ expect(runtime.listScans).toBeGreaterThan(0);
+ });
+
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`);
@@ -2149,14 +2223,28 @@ describe('PluginMarketService migration and defaultInstall', () => {
return ghost;
});
+ const firstOutcome = vi.fn();
+ const secondOutcome = vi.fn();
+ const settled = deferred();
const snapshot = await h.service.snapshot({
deferReconciliation: true,
+ onDefaultReconciliationOutcome: firstOutcome,
+ onDeferredReconciliationSettled: () => settled.resolve(),
});
expect(snapshot.items[0]?.installState).toBe('not-installed');
await vi.waitFor(() => expect(h.api.download).toHaveBeenCalledOnce());
+ // A later query must join the still-running writer even after the first
+ // snapshot returned, and both callers must receive its final outcome.
+ expect(await h.service.snapshot({
+ deferReconciliation: true, onDefaultReconciliationOutcome: secondOutcome,
+ })).toBe(snapshot);
+ expect(h.api.listAll).toHaveBeenCalledOnce();
downloadGate.resolve();
- await vi.waitFor(() => expect(runtime.install).toHaveBeenCalledOnce());
+ await settled.promise;
+ expect(runtime.install).toHaveBeenCalledOnce();
+ expect(firstOutcome).toHaveBeenCalledWith('completed');
+ expect(secondOutcome).toHaveBeenCalledWith('completed');
});
it('auto-installs the verified package when its capabilities exceed stale catalog metadata', async () => {
@@ -6155,6 +6243,14 @@ describe('PluginMarketService install consent', () => {
expect(h.ledger.installationForGhost('cindy-test')).toMatchObject({ releaseId: 'release-1' });
});
+ it('keeps the Renderer consent listener when background maintenance has no listener', async () => {
+ const { h } = upgradeFixture({ nextCapabilities: ['notify', 'fs'] });
+ const onConsentHoldsChanged = vi.fn();
+ await h.service.snapshot({ discoveryOnly: true, onConsentHoldsChanged });
+ await h.service.snapshot();
+ expect(onConsentHoldsChanged).toHaveBeenCalledOnce();
+ });
+
it('notifies after deferred reconciliation records a new consent hold', async () => {
const { h } = upgradeFixture({ nextCapabilities: ['notify', 'fs'] });
const onConsentHoldsChanged = vi.fn();
diff --git a/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts b/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts
index ce3e65af08..8c4d405da4 100644
--- a/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts
+++ b/apps/desktop/src/main/plugin-market/installedManifestIdentity.ts
@@ -81,6 +81,21 @@ interface OrganizationInstallationEvidenceInput {
identity: InstalledMarketManifestIdentity | null;
}
+/** Old receipts may lack a package hash; require both stored market and approved manifest identities. */
+export function hasVerifiedLegacyMarketInstallation(
+ input: OrganizationInstallationEvidenceInput,
+): boolean {
+ const { evidence, identity } = input;
+ if (!evidence?.legacyMigrated || evidence.packageSha256 !== null || !identity ||
+ !installedIdentityMatchesManifest(identity, evidence.approvedManifest)) return false;
+ if (input.records.length !== 1) return false;
+ const record = input.records[0]!;
+ return record.installed && /^[a-f0-9]{64}$/.test(record.sha256) &&
+ (record.source === 'market' || record.source === 'legacy-adopted') &&
+ record.ghostId === identity.manifest.id && record.version === identity.manifest.version &&
+ verifyInstalledMarketManifest(record, identity);
+}
+
function matchesApprovedOrganizationInstallation(
record: PluginMarketInstallationRecord,
input: OrganizationInstallationEvidenceInput,
diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.ts
index 91731e20bf..7d7b46efb5 100644
--- a/apps/desktop/src/main/plugin-market/ledger.ts
+++ b/apps/desktop/src/main/plugin-market/ledger.ts
@@ -439,18 +439,40 @@ export class PluginMarketLedger {
}
lookupInstallationsForNamespaceMigration(ghostId: string): PluginMarketNamespaceMigrationLookup {
+ return this.createNamespaceMigrationLookup()(ghostId);
+ }
+
+ /** Facts for one synchronous scan; never retain this across an await or use it for authorization. */
+ createNamespaceMigrationLookup(): (ghostId: string) => PluginMarketNamespaceMigrationLookup {
const { main, custom, namespaced } = this.readFiles();
- for (const file of [main, custom, namespaced]) {
- if (file.kind === 'invalid') return { kind: 'invalid' };
- if (!rawMentionsGhost(file, ghostId)) continue;
- const raw = file.raw!.installations as Record<string, unknown>;
- if (Object.entries(raw).some(([key, record]) =>
- rawEntryMentionsGhost(key, record, ghostId) &&
- (!validRecord(record) || (key !== record.ghostId && key !== pluginLedgerRecordKey(record))),
- )) return { kind: 'invalid' };
+ const files = [main, custom, namespaced];
+ const invalidFile = files.some((file) => file.kind === 'invalid');
+ const invalidGhostIds = new Set<string>();
+ for (const file of files) {
+ const raw = file.raw?.installations;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;
+ for (const [key, record] of Object.entries(raw)) {
+ if (validRecord(record) && (key === record.ghostId || key === pluginLedgerRecordKey(record))) continue;
+ invalidGhostIds.add(key);
+ const keyedGhost = parsePluginStoragePart(key)?.ghostId;
+ if (keyedGhost) invalidGhostIds.add(keyedGhost);
+ if (record && typeof record === 'object' && !Array.isArray(record) &&
+ typeof (record as { ghostId?: unknown }).ghostId === 'string') {
+ invalidGhostIds.add((record as { ghostId: string }).ghostId);
+ }
+ }
+ }
+ const byGhost = new Map<string, PluginMarketInstallationRecord[]>();
+ for (const record of Object.values(this.mergeInstallations(main, custom, namespaced).installations)) {
+ const records = byGhost.get(record.ghostId) ?? [];
+ records.push(record);
+ byGhost.set(record.ghostId, records);
}
- const records = recordsForGhostId(this.mergeInstallations(main, custom, namespaced).installations, ghostId);
- return records.length > 0 ? { kind: 'found', records } : { kind: 'absent' };
+ return (ghostId) => {
+ if (invalidFile || invalidGhostIds.has(ghostId)) return { kind: 'invalid' };
+ const records = byGhost.get(ghostId) ?? [];
+ return records.length > 0 ? { kind: 'found', records } : { kind: 'absent' };
+ };
}
installationForPlugin(plugin: {
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 9840ba1d01..1ce89fcd70 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -60,7 +60,7 @@ async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOpti
/**
* Reuse the market snapshot reconciliation outside the Plugins page so
* default-install plugins are provisioned and stable-source updates are applied
- * as soon as an app owner is ready. The Plugins page remains a later retry path.
+ * as soon as an app owner is ready. Resume and periodic maintenance retry it.
*/
export type DefaultMarketPluginSyncOutcome = 'completed' | 'deferred' | 'failed';
@@ -89,10 +89,13 @@ export function defaultMarketPluginSyncOutcome(
return 'failed';
}
-export async function syncDefaultMarketPlugins(): Promise<DefaultMarketPluginSyncOutcome> {
+export async function syncDefaultMarketPlugins(
+ trigger: PluginMarketSnapshotOptions['trigger'] = 'background',
+): Promise<DefaultMarketPluginSyncOutcome> {
try {
let reconciliationOutcome: 'completed' | 'failed' | null = null;
const snapshot = await snapshotAndSignalRemovalNotice({
+ trigger,
onDefaultReconciliationOutcome: (outcome) => {
reconciliationOutcome = outcome;
},
@@ -116,6 +119,16 @@ export async function syncDefaultMarketPlugins(): Promise<DefaultMarketPluginSyn
}
}
+/** Signal foreground removals without requesting another snapshot or disk scan. */
+export async function refreshForegroundMarketPlugins(): Promise<'completed' | 'failed'> {
+ try {
+ return await service().refreshCatalogForForeground();
+ } finally {
+ // A removal can succeed before a later maintenance step fails.
+ signalRemovalNoticeAvailable();
+ }
+}
+
/**
* Preserve stable IPC errors and hide internal/network messages from the
* renderer. Detailed failures stay in main logs; the renderer localizes by
@@ -147,7 +160,7 @@ export function registerPluginMarketIpc(): void {
assertTrustedAppRendererEvent(event);
return invokePluginMarket(() =>
snapshotAndSignalRemovalNotice({
- deferReconciliation: true,
+ discoveryOnly: true,
onConsentHoldsChanged: signalUpdateConsentHoldsChanged,
}),
);
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index a9982cd4b5..534a0aa841 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -250,7 +250,7 @@ async function yieldMarketReconciliation(owner: ActiveAppSession): Promise<void>
function installedGhostMatchingMarketPlugin(
plugin: { ghostId: string; namespace?: string | null },
- ghosts: readonly InstalledGhost[] = getGhostManager().list(),
+ ghosts: readonly InstalledGhost[] = listMarketInstallations(),
): InstalledGhost | undefined {
if (!isValidGhostId(plugin.ghostId)) {
return ghosts.find((ghost) => ghost.manifest.id === plugin.ghostId);
@@ -551,9 +551,11 @@ interface CustomMarketDiscoveryProgress {
}
export interface PluginMarketSnapshotOptions {
+ /** Main-only diagnostic source, never supplied by Renderer payloads. */
+ trigger?: 'owner-ready' | 'foreground' | 'resume' | 'periodic' | 'background' | 'catalog-query';
/** Agent discovery must never install, update, remove or repair plugins. */
discoveryOnly?: boolean;
- /** Renderer 目录请求先返回;默认安装和稳定来源升级在同一 owner 上后台补做。 */
+ /** 目录请求先返回;默认安装和稳定来源升级在同一 owner 上后台补做。 */
deferReconciliation?: boolean;
/** 延后对账完成(成功或失败)后通知 IPC 层刷新一次性提示。 */
onDeferredReconciliationSettled?: () => void;
@@ -794,7 +796,47 @@ function sameDisconnectedMarketInstallation(
);
}
-/** Stable local facts reused while projecting one market catalog response. */
+type MarketCatalog = Awaited<ReturnType<PluginMarketApi['listAll']>>;
+interface MarketSnapshotFlight {
+ promise: Promise<PluginMarketSnapshot>;
+ listeners: Set<PluginMarketSnapshotOptions>;
+ outcome: 'completed' | 'failed' | null;
+ deferredSettled: boolean;
+ deferredStarted: boolean;
+}
+
+function marketOwnerKey(owner: ActiveAppSession): string {
+ return JSON.stringify([owner.mode, owner.dataOwnerId, owner.generation, getClientEndpoint('pluginApiBaseUrl')]);
+}
+
+function listMarketInstallations(): InstalledGhost[] {
+ const manager = getGhostManager();
+ let installed: InstalledGhost[];
+ try {
+ installed = manager.list();
+ } catch {
+ throwIpcError('PRECONDITION_FAILED', 'Plugin installation scan is unavailable');
+ }
+ if (manager.isInstallationScanComplete?.() === false) {
+ throwIpcError('PRECONDITION_FAILED', 'Plugin installation scan is incomplete');
+ }
+ return installed;
+}
+
+/** Signed icon URLs rotate independently of installation/update facts. */
+function catalogReconciliationFingerprint(catalog: MarketCatalog): string {
+ return crypto.createHash('sha256').update(JSON.stringify({
+ plugins: catalog.plugins.map((plugin) => ({
+ id: plugin.id, ghostId: plugin.ghostId, namespace: plugin.namespace,
+ scope: plugin.scope, organizationId: plugin.organizationId,
+ defaultInstall: plugin.defaultInstall, release: { ...plugin.currentRelease, icon: undefined },
+ })).sort((a, b) => a.id.localeCompare(b.id)),
+ removals: [...catalog.removals].sort((a, b) => a.pluginId.localeCompare(b.pluginId)),
+ organization: catalog.currentOrganization,
+ organizationAccessError: catalog.organizationAccessError,
+ })).digest('hex');
+}
+
interface LocalInstallSnapshot {
/** Installed Ghost runtime facts for one market operation. */
ghosts: readonly InstalledGhost[];
@@ -839,6 +881,9 @@ function removalNoticeKey(owner: ActiveAppSession): string {
* 通过 protocol parser、下载大小/SHA 校验、Ghost runtime validator 和原子换目录。
*/
export class PluginMarketService {
+ private readonly snapshotFlights = new Map<string, MarketSnapshotFlight>();
+ private readonly catalogFlights = new Map<string, Promise<MarketCatalog>>();
+ private lastMaintenanceCatalog: { owner: string; fingerprint: string } | null = null;
private readonly mutations = new Map<string, Promise<unknown>>();
private ledgerMutation: Promise<void> = Promise.resolve();
private readonly pendingRemovalNotices = new Map<string, PluginRemovalUserNotice>();
@@ -978,7 +1023,96 @@ export class PluginMarketService {
});
}
- async snapshot(options: PluginMarketSnapshotOptions = {}): Promise<PluginMarketSnapshot> {
+ snapshot(options: PluginMarketSnapshotOptions = {}): Promise<PluginMarketSnapshot> {
+ return this.requestSnapshot(options);
+ }
+
+ private loadCatalog(owner: ActiveAppSession): Promise<MarketCatalog> {
+ const key = marketOwnerKey(owner);
+ const existing = this.catalogFlights.get(key);
+ if (existing) return existing;
+ const request = Promise.resolve().then(() => {
+ requireSameMarketOwner(owner);
+ return this.api.listAll();
+ });
+ this.catalogFlights.set(key, request);
+ const clear = () => { if (this.catalogFlights.get(key) === request) this.catalogFlights.delete(key); };
+ void request.then(clear, clear);
+ return request;
+ }
+
+ /** Focus checks remote changes without scanning installations when unchanged.
+ * Startup, resume and periodic full passes still independently recheck disk. */
+ async refreshCatalogForForeground(): Promise<'completed' | 'failed'> {
+ const owner = captureMarketOwner();
+ if (!getClientEndpoint('pluginApiBaseUrl')) return 'completed';
+ const key = marketOwnerKey(owner);
+ const catalog = await this.loadCatalog(owner);
+ requireSameMarketOwner(owner);
+ if (marketOwnerKey(owner) !== key) throwIpcError('PRECONDITION_FAILED', 'Plugin market endpoint changed');
+ const fingerprint = catalogReconciliationFingerprint(catalog);
+ const inFlight = this.snapshotFlights.get(JSON.stringify([key, false, false]));
+ if (inFlight) {
+ await inFlight.promise;
+ requireSameMarketOwner(owner);
+ if (marketOwnerKey(owner) !== key) throwIpcError('PRECONDITION_FAILED', 'Plugin market endpoint changed');
+ }
+ if (this.lastMaintenanceCatalog?.owner === key && this.lastMaintenanceCatalog.fingerprint === fingerprint) return 'completed';
+ let outcome: 'completed' | 'failed' = 'completed';
+ await this.requestSnapshot({ trigger: 'foreground', onDefaultReconciliationOutcome: (value) => { outcome = value; } }, catalog);
+ return outcome;
+ }
+
+ private requestSnapshot(options: PluginMarketSnapshotOptions, catalog?: MarketCatalog): Promise<PluginMarketSnapshot> {
+ // Only an actual subscriber replaces the long-lived notification sink.
+ // Background callers and in-flight aggregation must not erase Renderer notifications.
+ if (options.onConsentHoldsChanged) this.consentHoldsChangedListener = options.onConsentHoldsChanged;
+ const owner = getActiveAppSession();
+ const ownerKey = marketOwnerKey(owner);
+ const key = JSON.stringify([ownerKey, !!options.discoveryOnly, !!options.deferReconciliation]);
+ const existing = this.snapshotFlights.get(key);
+ if (existing) {
+ existing.listeners.add(options);
+ if (existing.outcome) options.onDefaultReconciliationOutcome?.(existing.outcome);
+ return existing.promise;
+ }
+ let flight!: MarketSnapshotFlight;
+ const clear = () => { if (this.snapshotFlights.get(key) === flight) this.snapshotFlights.delete(key); };
+ const runId = crypto.randomBytes(6).toString('hex');
+ const startedAt = Date.now();
+ const promise = Promise.resolve().then(() => {
+ requireSameMarketOwner(owner, { allowPendingBoundary: true });
+ if (marketOwnerKey(owner) !== ownerKey) throwIpcError('PRECONDITION_FAILED', 'Plugin market endpoint changed');
+ return this.buildSnapshot({
+ ...options,
+ onDefaultReconciliationOutcome: (outcome) => {
+ flight.outcome = outcome;
+ for (const listener of flight.listeners) listener.onDefaultReconciliationOutcome?.(outcome);
+ },
+ onDeferredReconciliationSettled: () => {
+ flight.deferredSettled = true;
+ for (const listener of flight.listeners) listener.onDeferredReconciliationSettled?.();
+ clear();
+ },
+ }, catalog, () => { flight.deferredStarted = true; });
+ }).then((snapshot) => {
+ log.info('plugin market refresh completed', {
+ runId, trigger: options.trigger ?? (options.discoveryOnly ? 'catalog-query' : 'background'),
+ mode: options.discoveryOnly ? 'discovery' : 'reconciliation',
+ elapsedMs: Date.now() - startedAt, items: snapshot.items.length, outcome: flight.outcome,
+ requests: flight.listeners.size,
+ });
+ return snapshot;
+ }).finally(() => {
+ if (!flight.deferredStarted || flight.deferredSettled) clear();
+ });
+ flight = { promise, listeners: new Set([options]), outcome: null, deferredStarted: false, deferredSettled: false };
+ this.snapshotFlights.set(key, flight);
+ void flight.promise.catch(clear);
+ return flight.promise;
+ }
+
+ private async buildSnapshot(options: PluginMarketSnapshotOptions, prefetchedCatalog?: MarketCatalog, onDeferredStarted?: () => void): Promise<PluginMarketSnapshot> {
// 自定义市场项完全来自本地数据,不依赖服务端与登录态;服务端不可用时
// 仍然返回,unavailableReason 只表达服务端部分的不可用。
//
@@ -1009,9 +1143,6 @@ export class PluginMarketService {
}
return this.snapshotPublicCatalogWithoutOwner();
}
- if (options.onConsentHoldsChanged) {
- this.consentHoldsChangedListener = options.onConsentHoldsChanged;
- }
const iconProjectionGeneration = this.nextCustomIconProjectionGeneration();
const customSourceNames = this.customSourceNamesSafe(owner);
const customDiscoveryPromise = this.discoverCustomEntriesBounded(
@@ -1056,6 +1187,7 @@ export class PluginMarketService {
unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,
};
if (!options.discoveryOnly && options.deferReconciliation) {
+ onDeferredStarted?.();
void Promise.resolve()
.then(reconcileCustomUpdates)
.catch((error) => {
@@ -1079,10 +1211,13 @@ export class PluginMarketService {
let currentOrganization: PluginCurrentOrganization | null | undefined;
let organizationAccessError: string | null = null;
let customDiscovery: CustomMarketDiscovery;
+ let catalogFingerprint: string | null = null;
+ const catalogOwnerKey = marketOwnerKey(owner);
const catalogServerRoot = getClientEndpoint('pluginApiBaseUrl').replace(/\/+$/, '');
try {
// 官方目录与自定义发现并行;单个本地/网络盘来源卡顿不会串行拖住官方请求。
- const [catalog, discovered] = await Promise.all([this.api.listAll(), customDiscoveryPromise]);
+ const [catalog, discovered] = await Promise.all([prefetchedCatalog ?? this.loadCatalog(owner), customDiscoveryPromise]);
+ catalogFingerprint = catalogReconciliationFingerprint(catalog);
plugins = visiblePluginsForOwner(owner, catalog.plugins);
removals = catalog.removals;
currentOrganization = catalog.currentOrganization;
@@ -1102,8 +1237,13 @@ export class PluginMarketService {
}
requireSameMarketOwner(owner);
+ if (marketOwnerKey(owner) !== catalogOwnerKey) throwIpcError('PRECONDITION_FAILED', 'Plugin market endpoint changed');
const ledger = this.ledgerForOwner(owner);
+ let namespaceReconciliationFailed = false;
if (!options.discoveryOnly) {
+ // Local failures are retried by startup/recovery and periodic maintenance,
+ // not on every subsequent focus of an unchanged remote catalog.
+ this.lastMaintenanceCatalog = { owner: catalogOwnerKey, fingerprint: catalogFingerprint! };
this.rememberCurrentOrganization(currentOrganization);
await this.backfillInstalledManifestIdentities(ledger, owner);
await yieldMarketReconciliation(owner);
@@ -1115,6 +1255,7 @@ export class PluginMarketService {
try {
await getGhostManager().reconcilePendingRootNamespaces?.(true);
} catch (error) {
+ namespaceReconciliationFailed = true;
log.warn('namespace migration market reconcile failed', {
error: error instanceof Error ? error.message : String(error),
});
@@ -1158,7 +1299,7 @@ export class PluginMarketService {
const reconcileMarketInstallations = async (): Promise<'completed' | 'failed'> => {
// 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。
// 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。
- let completed = true;
+ let completed = !namespaceReconciliationFailed;
await yieldMarketReconciliation(owner);
try {
if (!(await this.applyDefaultInstalls(plugins, currentOrganization, owner, ledger))) {
@@ -1207,6 +1348,7 @@ export class PluginMarketService {
organizationAccessError,
};
if (!options.discoveryOnly && options.deferReconciliation) {
+ onDeferredStarted?.();
// 目录展示不等待默认插件下载;对账仍复用原有串行锁和 owner 校验。
void Promise.resolve()
.then(reconcileMarketInstallations)
@@ -1620,7 +1762,7 @@ export class PluginMarketService {
}
const ledger = this.ledgerForOwner(owner);
const ghost = typeof target === 'string'
- ? findInstalledGhostByInstanceId(getGhostManager().list(), target)
+ ? findInstalledGhostByInstanceId(listMarketInstallations(), target)
: target;
if (!ghost) return null;
const record = ledger.installationForLocalUninstall({
@@ -2678,7 +2820,7 @@ export class PluginMarketService {
(record) => record.installed && record.rawManifestSha256 === undefined,
);
if (candidates.length === 0) return;
- const ghosts = getGhostManager().list();
+ const ghosts = listMarketInstallations();
for (const candidate of candidates) {
await yieldMarketReconciliation(owner);
// Reject unchanged, ineligible records using one scan for the whole pass.
@@ -2743,7 +2885,7 @@ export class PluginMarketService {
): Promise<void> {
const counts = ghostIdCounts(plugins);
const installations = ledger.read().installations;
- for (const ghost of getGhostManager().list()) {
+ for (const ghost of listMarketInstallations()) {
if (installations[pluginLedgerRecordKey({
ghostId: ghost.manifest.id,
...deliveryNamespaceFields(ghost),
@@ -2850,7 +2992,7 @@ export class PluginMarketService {
if (installed) return installed;
const lookup = ledger.lookupInstallationsForNamespaceMigration(record.ghostId);
if (lookup.kind !== 'found' || lookup.records.length !== 1) return undefined;
- const candidates = getGhostManager().list().filter((ghost) =>
+ const candidates = listMarketInstallations().filter((ghost) =>
ghost.manifest.id === record.ghostId && !hasDeliveryNamespace(ghost) &&
installedGhostPhysicalRelId(ghost) === record.ghostId,
);
@@ -2976,8 +3118,7 @@ export class PluginMarketService {
): Promise<void> {
const record = ledger.installationForPlugin({ namespace: null, ghostId: 'cindy-github' });
requireSameMarketOwner(owner);
- const installed = getGhostManager()
- .list()
+ const installed = listMarketInstallations()
.find((ghost) => ghost.manifest.id === 'cindy-github' && ghost.namespace == null &&
ghost.namespaceState !== 'pending');
if (!record || !installed || !canBackfillOfficialCindyGithubTrust(record, installed)) return;
@@ -3002,8 +3143,7 @@ export class PluginMarketService {
await withGhostInstallLock('cindy-github', async () => {
requireSameMarketOwner(owner);
const currentRecord = ledger.installationForPlugin({ namespace: null, ghostId: 'cindy-github' });
- const currentInstalled = getGhostManager()
- .list()
+ const currentInstalled = listMarketInstallations()
.find((ghost) => ghost.manifest.id === 'cindy-github' && ghost.namespace == null &&
ghost.namespaceState !== 'pending');
if (
@@ -3111,7 +3251,7 @@ export class PluginMarketService {
const reason = ledgerGateReason(record, removal);
if (reason) return skip(removal, reason);
- removalGhosts ??= getGhostManager().list();
+ removalGhosts ??= listMarketInstallations();
const installed = snapshotGhost({
...EMPTY_LOCAL_INSTALL_SNAPSHOT,
ghosts: removalGhosts,
@@ -3553,7 +3693,7 @@ export class PluginMarketService {
installations = ledger.read().installations,
ghostId?: string,
): LocalInstallSnapshot {
- const ghosts = getGhostManager().list();
+ const ghosts = listMarketInstallations();
const records = Object.values(installations).filter((record) => record.installed);
return {
ghosts,
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 8191871d4b..b14448563b 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -659,6 +659,36 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
- 当前组织的前缀对不上这个 ghostId 时保持待迁移,插件按旧规则继续运行,不报错。作者以后登录前缀匹配的组织,再完成迁移。
- 归属一旦写入注册表并确认,再切换组织也不会改这条记录。
+### 5.3 市场刷新与实例核对
+
+- Renderer 的市场目录请求只做 discovery,不顺带安装、更新、移除或修复。Main 在数据所有者
+ 稳定后、系统恢复和 30 分钟周期运行完整维护;切回应用仍受 30 秒节流,但先比较远端目录
+ 中影响安装的事实。目录未变时不扫描本机插件;签名图标 URL 的变化不触发完整维护。
+ 本地改动和暂时失败由启动恢复与周期维护重查,不靠每次焦点切换重复全盘扫描。
+ 前台检查与完整维护各有独立的节流时刻和有界在途槽位:持续切回应用不能推迟周期维护,
+ 在途前台请求也不能吞掉系统恢复检查。两类入口重叠时仍由市场服务合并目录请求与完整维护。
+ 前台入口完成或失败时,仅从当前 owner 的内存提示队列检查并广播待处理的移除提示,
+ 不为发送提示额外请求目录或扫描插件。
+- 同一 owner、会话 generation、市场端点及执行策略的并发请求合并为一轮;延后维护的槽位
+ 保留到实际维护结束。不同账号或端点不复用在途结果。一次同步扫描只读一组市场账本,
+ 这组事实不跨 `await` 保存,也不作为运行时授权缓存。
+- `pending-but-not-listed` 是注册表中的旧实例脱离普查清单,不能只记日志后永远跳过。
+ 修复不得扩大冻结的普查名单,也不能用 receipt 的 namespace 字段直接确认身份。必须核对
+ 唯一的已安装市场记录、包指纹、namespace 和当前组织;实例已有 pluginId 时,市场记录必须
+ 与它一致,确认提交前也复核该绑定未变。尚未绑定的旧实例仍按完整证据链核验。缺少包指纹的已迁移旧 receipt,
+ 还必须同时匹配批准清单、当前安装清单和账本原先保存的清单身份。孤立记录不能走只对普查
+ 存量开放的 Forge 前缀或手动安装推断。证据不足保留既有可用状态并记录等待证据,
+ 由下一次独立完整维护重查,不触发启动协调器整批自动重试;实际的扫描、落盘等错误仍报告维护失败。
+- 内容根读取失败不能当空目录;子树读取失败表示该子树的存在性未知,不能将其记录置为
+ 未安装,也不能据此自动补装。其他可读插件仍可投影;界面可以保留当前 owner 最近一次完整
+ 列表,运行时授权仍读取当前批准事实。
+- 相同实例、receipt 修订和包指纹的核对告警首次记录,之后每 5 分钟汇总重复次数;恢复正常、
+ 事实改变或 owner 切换后重新记录。告警事实在核对时同一遍收集,不能为每条异常重新遍历
+ 全部实例,也不为日志额外读取磁盘。刷新日志记录轮次、触发来源、耗时和合并请求数,用于
+ 区分“一处异常被多次检查”和“多个插件异常”,不记录凭证或用户内容。
+
+这部分不改变 manifest、包格式、安装布局、批准权限、凭证或用户偏好,不涉及作者契约变更。
+
## 6. 作者契约与编写手册同步
内置 `cindy-plugin-creator` Skill 是 Agent 替用户编写插件的**唯一教材**,正本位于