Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(plugins): reuse asynchronous installation scans within market refreshes
DavidShenfb57f1142d3d
diff --git a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts b/apps/desktop/src/main/__tests__/installedGhostManifest.test.tsindex 9a42895e30..1ed95e22c5 100644--- a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts+++ b/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts@@ -3,15 +3,17 @@ 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 {parseInstalledGhostManifest,readInstalledGhostManifest,readInstalledGhostManifestDigestFormats,readInstalledGhostManifestSnapshot,+ readInstalledGhostManifestSnapshotAsync,} from '../installedGhostManifest.js';import { ghostManifestDigest } from '../plugin-market/ledger.js';+import { GhostInstallReceiptStore } from '../cindy-brain/ghostInstallReceipt.js';const roots: string[] = [];@@ -135,13 +137,15 @@ describe('installed ghost manifest compatibility', () => {expect(parsed.manifest).not.toHaveProperty('manual');});- it('hashes the exact bytes read instead of a normalized serialization', () => {+ // Background discovery must retain the exact-byte update identity contract;+ // run the existing minimal fixture through both production readers (unit).+ it.each([readInstalledGhostManifestSnapshot, readInstalledGhostManifestSnapshotAsync])('hashes the exact bytes read instead of a normalized serialization (%#)', async (read) => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-manifest-sha-'));roots.push(root);const bytes = Buffer.from(`${JSON.stringify(manifest(), null, 2)}\n`);fs.writeFileSync(path.join(root, 'ghost.json'), bytes);- const result = readInstalledGhostManifestSnapshot(root, 64 * 1024);+ const result = await read(root, 64 * 1024);expect(result.ok).toBe(true);if (!result.ok) return;@@ -153,6 +157,49 @@ describe('installed ghost manifest compatibility', () => {);});+ // Review regression: background receipt/manifest readers lost the sync path's+ // non-blocking open, so an unwritten POSIX FIFO stalled market refresh forever.+ // Unit: model that open at the fs boundary (also on Windows); existing regular+ // file tests cannot expose it. Both public readers must finish and reject it.+ it.each(['manifest', 'receipt'] as const)('rejects a FIFO %s without waiting for a writer', async (kind) => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-fifo-'));+ roots.push(root);+ const nativeFlag = fs.constants.O_NONBLOCK;+ const nonBlockingFlag = nativeFlag ?? 0x800;+ if (nativeFlag === undefined) {+ Object.defineProperty(fs.constants, 'O_NONBLOCK', { value: nonBlockingFlag, configurable: true });+ }+ const handle = {+ stat: async () => ({ isFile: () => false, size: 0n }),+ close: async () => {},+ } as unknown as fs.promises.FileHandle;+ let release!: (value: fs.promises.FileHandle) => void;+ const writer = new Promise<fs.promises.FileHandle>((resolve) => { release = resolve; });+ let entered!: () => void;+ const opening = new Promise<void>((resolve) => { entered = resolve; });+ const open = vi.spyOn(fs.promises, 'open').mockImplementation(async (_file, flags) => {+ entered();+ return Number(flags) & nonBlockingFlag ? handle : writer;+ });+ let reading: Promise<unknown> | undefined;+ try {+ reading = kind === 'manifest'+ ? readInstalledGhostManifestSnapshotAsync(root, 64 * 1024)+ : new GhostInstallReceiptStore(() => root).readAsync('hello');+ await opening;+ const result = await Promise.race([+ reading,+ new Promise<'waiting for writer'>((resolve) => setImmediate(() => resolve('waiting for writer'))),+ ]);+ expect(result).toMatchObject(kind === 'manifest' ? { ok: false } : { state: 'invalid' });+ } finally {+ release(handle);+ await reading;+ open.mockRestore();+ if (nativeFlag === undefined) Reflect.deleteProperty(fs.constants, 'O_NONBLOCK');+ }+ });+it('keeps semantic equality separate from raw-byte identity', () => {const rootsForFormats = [fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-format-a-')),diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 81618d92bf..cdf5e5fba9 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -88,6 +88,12 @@ import {type NamespaceMigrationBasis,} from './pluginNamespaceMigration.js';import { confirmUnconfirmedInstances } from './pluginInstanceConfirmation.js';+import {+ createGhostBackgroundRefresh,+ type GhostBackgroundRefresh,+ type GhostBackgroundScan,+ type GhostScanState,+} from './ghostBackgroundRefresh.js';import {commitPendingNamespaceMigration,reconcilePendingNamespaceMigrations,@@ -1078,7 +1084,7 @@ export class GhostManager {return { kind: 'proceed' };}- async reconcilePendingRootNamespaces(marketSyncCompleted: boolean): Promise<void> {+ async reconcilePendingRootNamespaces(marketSyncCompleted: boolean, refresh?: GhostBackgroundRefresh): Promise<void> {await reconcilePendingNamespaceMigrations({ensureCensus: () => this.ensureNamespaceMigrationCensus(),ownerContextKey: () => this.currentOwnerContextKey(),@@ -1089,17 +1095,18 @@ export class GhostManager {classify: this.options.classifyPendingNamespace,commit: (ghostId, namespace, basis, expectedReceipt) =>this.commitPendingNamespace(ghostId, namespace, basis, expectedReceipt),- confirmUnconfirmed: () => this.confirmUnconfirmedInstances(),+ confirmUnconfirmed: () => this.confirmUnconfirmedInstances(refresh),log: this.options.log,}, marketSyncCompleted);}- private async confirmUnconfirmedInstances(): Promise<void> {+ private async confirmUnconfirmedInstances(refresh?: GhostBackgroundRefresh): Promise<void> {const result = await confirmUnconfirmedInstances({readEvidence: this.options.readUnconfirmedConfirmationEvidence,isBlocked: () => this.instanceRegistryService.isBlocked(),sync: () => this.syncInstanceRegistry(),+ prepare: refresh ? () => refresh.registry() : undefined,ownerContextKey: () => this.currentOwnerContextKey(),readApproval: (relId) => this.readApproval(relId),orphanPendingNamespace: (record, approval) => {@@ -1139,18 +1146,20 @@ export class GhostManager {}}- resumePendingResidentsOffline(): void {+ resumePendingResidentsOffline(installed?: readonly InstalledGhost[]): void {const ledger = this.ensureNamespaceMigrationCensus();if (!ledger || !this.options.canResumePendingResidentOffline ||!this.options.onResumePendingResidentOffline) return;- const ghosts = this.list();+ const ghosts = installed ?? this.list();for (const ghost of ghosts) {const ghostId = ghost.manifest.id;if (ghost.dir !== this.contentPath(ghostId) ||ghost.namespaceState !== 'pending' || !ghost.enabled ||ghost.approval.state !== 'approved' || this.hasPendingMutationJournal(ghostId)) continue;const approval = this.readApproval(ghostId);- if (approval.state !== 'approved' || hasDeliveryNamespace(approval.receipt)) continue;+ if (approval.state !== 'approved' || hasDeliveryNamespace(approval.receipt) ||+ approval.receipt.revision !== ghost.approval.revision ||+ !this.effectiveEnabled(ghost.dir, approval.receipt.enabled)) continue;if (this.options.canResumePendingResidentOffline(ghostId)) {this.options.onResumePendingResidentOffline(ghost);}@@ -2660,6 +2669,151 @@ export class GhostManager {return this.scanInstalled().ghosts;}+ /**+ * Background discovery only. Fresh receipt IO runs off the main thread, with+ * at most four reads in flight. Projection yields between plugins; it shares+ * the sync list's approval/isolation rules, never a completed approval cache.+ * Do not call from inside runExclusiveMutation: discovery waits for that lane.+ */+ async listAsync(): Promise<InstalledGhost[]> {+ return (await this.scanInstalledAsync()).ghosts;+ }++ /** Only the caller's current market refresh retains this read-only view. */+ createBackgroundRefresh(): GhostBackgroundRefresh {+ return createGhostBackgroundRefresh({+ state: () => this.backgroundScanState(),+ scan: () => this.scanInstalledAsync(),+ });+ }++ private backgroundScanState(): GhostScanState {+ return {+ owner: this.currentOwnerContextKey(),+ mutation: this.mutationTail,+ // Registry/census changes can happen without a content transaction. Use+ // their value, not parsed-object identity, so unchanged reloads still share.+ identity: JSON.stringify([+ this.options.getLocale?.(),+ this.instanceRegistryService.current(),+ this.instanceRegistryService.isBlocked(),+ [...this.untrustedApprovals],+ [...this.recoveryBlockedApprovalNamespaces],+ [...this.unavailableContentRoots],+ ]),+ };+ }++ private async scanInstalledAsync(): Promise<GhostBackgroundScan> {+ const owner = this.currentOwnerContextKey();+ const ownerKey = this.options.getOwnerContextKey?.();+ const contentRoot = this.options.getRootDir();+ const stateRootOption = this.options.getStateDir?.();+ const assertOwner = (checkPhysicalRoots = false) => {+ // Per-turn checks are cheap. Re-resolve filesystem identities at commit+ // and return, rather than synchronously stat-ing both roots per plugin.+ if (this.options.getOwnerContextKey?.() !== ownerKey ||+ this.options.getRootDir() !== contentRoot ||+ this.options.getStateDir?.() !== stateRootOption ||+ (checkPhysicalRoots && this.currentOwnerContextKey() !== owner)) {+ throw new Error('ghost owner context changed during background scan');+ }+ };+ for (let attempt = 0; attempt < 3; attempt++) {+ const mutations = this.mutationTail;+ await mutations;+ assertOwner(true);+ if (mutations !== this.mutationTail) continue;+ this.ensureCurrentOwnerContextSync();+ const locale = this.options.getLocale?.();+ const root = this.contentRootDir();+ const stateRoot = this.stateRootDir();+ const receipts = new GhostInstallReceiptStore(() => stateRoot);+ const entries = await this.listContentEntriesAsync(root);+ assertOwner();+ if (mutations !== this.mutationTail) continue;+ const approved = new Map<string, GhostInstallReceiptReadResult>();+ const disabled = new Map<string, boolean>();+ let next = 0;+ await Promise.all(Array.from({ length: Math.min(4, entries.length) }, async () => {+ while (next < entries.length) {+ const { relId, dir } = entries[next++];+ approved.set(relId, await receipts.readAsync(relId));+ try {+ await classifyGhostDirEntry(path.join(dir, DISABLED_MARKER_FILE));+ disabled.set(dir, true);+ } catch (error) {+ disabled.set(dir, (error as NodeJS.ErrnoException).code !== 'ENOENT');+ }+ await new Promise<void>((resolve) => setImmediate(resolve));+ }+ }));+ assertOwner(true);+ if (mutations !== this.mutationTail) continue;+ // This short commit has no await: an intervening Host install, disable or+ // removal invalidates the entire preparation before registry publication.+ this.unavailableContentRoots.clear();+ const readReceipt = (relId: string) => approved.get(relId)!;+ const registry = this.instanceRegistryService.sync({+ listContentEntries: () => entries,+ receiptFact: (relId) => this.receiptFact(relId, readReceipt(relId)),+ isPresenceUnknown: () => false,+ });+ const result: InstalledGhost[] = [];+ for (const entry of entries) {+ result.push(...this.projectListedEntries([entry], readReceipt, disabled));+ await new Promise<void>((resolve) => setImmediate(resolve));+ assertOwner();+ if (mutations !== this.mutationTail) break;+ }+ if (mutations !== this.mutationTail) continue;+ assertOwner(true);+ if (locale !== this.options.getLocale?.() ||+ (registry !== this.instanceRegistryService.current() &&+ JSON.stringify(registry) !== JSON.stringify(this.instanceRegistryService.current()))) continue;+ return {+ ghosts: result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id)),+ registry,+ state: this.backgroundScanState(),+ };+ }+ throw new Error('ghost installations changed repeatedly during background scan');+ }++ private async listContentEntriesAsync(root: string): Promise<Array<{ relId: string; dir: string }>> {+ const listed: Array<{ relId: string; dir: string }> = [];+ const scan = async (parent: string): Promise<string[]> => {+ const dir = path.join(root, ...parent.split('/'));+ try {+ if (await classifyGhostDirEntry(dir) !== 'directory') return [];+ return await fs.promises.readdir(dir);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];+ throw error;+ }+ };+ const add = async (parent: string, names: string[]) => {+ for (const name of names) {+ const relId = parent ? parent + '/' + name : name;+ if (!parsePluginInstallRelId(relId)) continue;+ const dir = path.join(root, ...relId.split('/'));+ try {+ if (await classifyGhostDirEntry(dir) === 'directory') listed.push({ relId, dir });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+ };+ const names = await scan('');+ for (const namespace of await scan(PLUGIN_NS_INSTALL_ROOT)) {+ if (namespace !== PLUGIN_ROOT_INSTALL_DIR && !isValidPluginNamespace(namespace)) continue;+ const parent = PLUGIN_NS_INSTALL_ROOT + '/' + namespace;+ await add(parent, await scan(parent));+ }+ await add('', names.filter((name) => !name.startsWith('.') && name !== PLUGIN_NS_INSTALL_ROOT));+ return listed;+ }+private scanInstalled(): { ghosts: InstalledGhost[]; registry: PluginInstanceRegistry } {this.ensureCurrentOwnerContextSync();const entries = this.listContentEntries();@@ -2708,6 +2862,7 @@ export class GhostManager {private projectListedEntries(listedDirs: Array<{ relId: string; dir: string }>,readReceipt?: (relId: string) => GhostInstallReceiptReadResult,+ disabledMarkers?: ReadonlyMap<string, boolean>,): InstalledGhost[] {const result: InstalledGhost[] = [];for (const listed of listedDirs) {@@ -2717,6 +2872,9 @@ export class GhostManager {const approvalResult = this.readApproval(relId, readReceipt);if (approvalResult.state === 'approved') {const receipt = approvalResult.receipt;+ const enabled = disabledMarkers+ ? receipt.enabled && disabledMarkers.get(dir) === false+ : this.effectiveEnabled(dir, receipt.enabled);const localizedManifest = this.localizeApprovedManifest(receipt);const retired = findFeatureRetirement(receipt.manifest);let retirement: InstalledGhost['retirement'];@@ -2725,7 +2883,7 @@ export class GhostManager {retirement = this.retirements.observe(retired.id,pluginInstallStoragePart(relId),- this.effectiveEnabled(dir, receipt.enabled),+ enabled,);} catch (error) {// Do not consume the observation on failed IO. The original receipt@@ -2736,7 +2894,7 @@ export class GhostManager {});retirement = {id: retired.id,- eligible: this.effectiveEnabled(dir, receipt.enabled),+ eligible: enabled,unread: false,};}@@ -2745,7 +2903,7 @@ export class GhostManager {manifest: localizedManifest,dir,...this.instanceProjection(relId, identity.ghostId),- enabled: !retired && this.effectiveEnabled(dir, receipt.enabled),+ enabled: !retired && enabled,...(retirement ? { retirement } : {}),approval: { state: 'approved', revision: receipt.revision },...(receipt.taskCapabilityApproved === true ? { taskCapabilityApproved: true as const } : {}),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex af1fc41072..c21acc5b4c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -3865,6 +3865,138 @@ describe('GhostManager · uninstall', () => {});describe('GhostManager · list', () => {+ // Compatibility §5 / #6667: an IO failure must not persist active:false or+ // trigger a default reinstall. Existing sync-list coverage misses async IO.+ // Unit; one approved install and one unreadable directory, then IO recovery.+ it.each(['root', 'namespaces', 'namespace', 'install'] as const)('async scan refuses an incomplete %s view without changing the registry', async (scope) => {+ await manager.install(await makeCindy('unreadable-async.cindy', goodManifest()));+ 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') : scope === 'namespace'+ ? path.join(rootDir, '_ns', '_root') : path.join(rootDir, '_ns', '_root', 'hello');+ const refresh = manager.createBackgroundRefresh();+ const fail = () => { throw Object.assign(new Error('scan unavailable'), { code: 'EACCES' }); };+ const readdir = fs.promises.readdir;+ const lstat = fs.promises.lstat;+ const read = scope === 'install'+ ? vi.spyOn(fs.promises, 'lstat').mockImplementation(((file: never, options: never) => {+ if (String(file) === target) fail();+ return lstat(file, options);+ }) as never)+ : vi.spyOn(fs.promises, 'readdir').mockImplementation(((dir: never, options: never) => {+ if (String(dir) === target) fail();+ return readdir(dir, options);+ }) as never);+ try {+ await expect(refresh.list()).rejects.toThrow('scan unavailable');+ expect(fs.readFileSync(registryPath, 'utf8')).toBe(before);+ } finally {+ read.mockRestore();+ }+ expect((await refresh.list())[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ });++ // One market refresh must read installations once, while later refreshes and+ // Host mutations observe fresh approval. Existing listAsync tests only cover+ // independent scans, not this request lifetime (unit; one installed plugin).+ it('reuses one scan inside a refresh and reads current approval in the next refresh', async () => {+ await manager.install(await makeCindy('refresh.cindy', goodManifest()));+ const read = vi.spyOn(GhostInstallReceiptStore.prototype, 'readAsync');+ try {+ const refresh = manager.createBackgroundRefresh();+ const lists = await Promise.all([refresh.list(), refresh.list()]);+ for (let i = 0; i < 4; i++) expect((await refresh.list())[0].enabled).toBe(true);+ expect(lists[0]).toEqual(lists[1]);+ expect(read).toHaveBeenCalledTimes(1);+ const receiptPath = path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json');+ await fs.promises.writeFile(receiptPath, '{invalid');+ expect((await manager.createBackgroundRefresh().list())[0]).toMatchObject({ enabled: false, approval: { state: 'invalid' } });+ expect(read).toHaveBeenCalledTimes(2);+ } finally {+ read.mockRestore();+ }+ });++ it.each(['disable', 'install', 'uninstall'] as const)('invalidates a refresh after a queued %s', async (change) => {+ await manager.install(await makeCindy('refresh.cindy', goodManifest()));+ const refresh = manager.createBackgroundRefresh();+ expect((await refresh.list())[0].enabled).toBe(true);+ const mutation = change === 'disable' ? manager.setEnabled('hello', false)+ : change === 'uninstall' ? manager.uninstall('hello')+ : manager.install(await makeCindy('new.cindy', goodManifest('other')));+ const listing = refresh.list();+ await mutation;+ const current = await listing;+ if (change === 'disable') expect(current[0].enabled).toBe(false);+ if (change === 'uninstall') expect(current).toEqual([]);+ if (change === 'install') expect(current.map((ghost) => ghost.manifest.id)).toEqual(['hello', 'other']);+ });++ it('rejects a cached refresh after the owner generation changes', async () => {+ let owner = '1';+ manager = new GhostManager({ getRootDir: () => rootDir, getOwnerContextKey: () => owner });+ await manager.install(await makeCindy('refresh.cindy', goodManifest()));+ const refresh = manager.createBackgroundRefresh();+ await refresh.list();+ owner = '2';+ await expect(refresh.list()).rejects.toThrow(/owner context changed/);+ });++ // Background scanning must yield during receipt IO, reject an obsolete owner,+ // and retry after a Host removal. Sync list coverage cannot exercise these+ // await windows (plugin-security-and-authoring §5; unit, one installed plugin).+ it('async scan reads fresh receipts without using the synchronous receipt reader', async () => {+ await manager.install(await makeCindy('async.cindy', goodManifest()));+ const syncRead = vi.spyOn(GhostInstallReceiptStore.prototype, 'readForRecovery');+ try {+ const first = await manager.listAsync();+ expect(first[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ expect(syncRead).not.toHaveBeenCalled();+ const receiptPath = path.join(workDir, 'ghosts-install-state', '_ns', '_root', 'hello.json');+ await fs.promises.writeFile(receiptPath, '{invalid');+ expect((await manager.listAsync())[0]).toMatchObject({ enabled: false, approval: { state: 'invalid' } });+ } finally {+ syncRead.mockRestore();+ }+ });++ it.each(['owner', 'uninstall'] as const)('async scan does not publish stale approval after %s changes during IO', async (change) => {+ let ownerGeneration = 1;+ manager = new GhostManager({ getRootDir: () => rootDir, getOwnerContextKey: () => String(ownerGeneration) });+ await manager.install(await makeCindy('race.cindy', goodManifest()));+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ let entered!: () => void;+ const reading = new Promise<void>((resolve) => { entered = resolve; });+ const original = GhostInstallReceiptStore.prototype.readAsync;+ let paused = false;+ const read = vi.spyOn(GhostInstallReceiptStore.prototype, 'readAsync').mockImplementation(async function (this: GhostInstallReceiptStore, id: string) {+ const receipt = await original.call(this, id);+ if (!paused && id.endsWith('/hello')) {+ paused = true;+ entered();+ await gate;+ }+ return receipt;+ });+ try {+ const listing = manager.listAsync();+ const observed = change === 'owner' ? expect(listing).rejects.toThrow(/owner context changed/) : null;+ await reading;+ if (change === 'owner') ownerGeneration++;+ else await manager.uninstall('hello');+ release();+ if (observed) await observed;+ else {+ expect(await listing).toEqual([]);+ }+ } finally {+ release();+ read.mockRestore();+ }+ });+it('根目录不存在 → 空清单(不报错)', () => {expect(manager.list()).toEqual([]);});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex f711e2991f..7cea67263a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -119,6 +119,18 @@ describe('GhostInstallReceiptStore cleanup', () => {});}+ // Async discovery adds an await window: preserve the sync reader's no-follow+ // parent gate. A linked namespace must never become an approved installation.+ // Unit; one valid receipt behind a directory link (junction on Windows).+ it('async reading rejects a linked namespace parent', async () => {+ const outside = path.join(workDir, 'outside');+ await fs.promises.mkdir(outside);+ await fs.promises.writeFile(path.join(outside, 'hello.json'), JSON.stringify(createSetupReceipt()));+ await fs.promises.mkdir(path.join(stateRoot, '_ns'));+ await fs.promises.symlink(outside, path.join(stateRoot, '_ns', 'acme'), process.platform === 'win32' ? 'junction' : 'dir');+ expect(await store.readAsync('_ns/acme/hello')).toMatchObject({ state: 'invalid' });+ });+// Unit regression: repeated store.read() must reuse only icon format validation.// Existing receipt tests do not cover unchanged revision/path with replaced icon// bytes. A same-length invalid replacement must fail, and enabled stays fresh.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.tsindex 7e3b03d040..d3ee476cb8 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@@ -825,6 +825,40 @@ describe('GhostManager namespace migration census', () => {expect(resumed.mock.results[0]?.value).toBe('pending');});+ // A background list may precede the resume callback by several awaits. A+ // cached enabled projection must not restart a resident disabled meanwhile.+ // Unit: one pending legacy resident; existing tests use only fresh sync lists.+ it('rechecks enabled state before resuming from a prepared background list', async () => {+ await plantLegacyInstall('hello');+ const resumed = vi.fn();+ manager = createManager({+ canResumePendingResidentOffline: () => true,+ onResumePendingResidentOffline: resumed,+ });+ manager.ensureNamespaceMigrationCensus();+ const installed = await manager.listAsync();+ expect(installed[0]).toMatchObject({ enabled: true, namespaceState: 'pending' });+ await manager.setEnabled('hello', false);+ manager.resumePendingResidentsOffline(installed);+ expect(resumed).not.toHaveBeenCalled();+ });++ // Census publication changes namespace eligibility without a content+ // transaction. A per-refresh view must observe that new registry (unit).+ it('invalidates a background refresh when the census changes without an install mutation', async () => {+ await plantLegacyInstall('hello');+ const read = vi.spyOn(GhostInstallReceiptStore.prototype, 'readAsync');+ try {+ const refresh = manager.createBackgroundRefresh();+ expect((await refresh.registry()).census).toBeNull();+ expect(manager.ensureNamespaceMigrationCensus()).not.toBeNull();+ expect((await refresh.registry()).census).not.toBeNull();+ expect(read).toHaveBeenCalledTimes(2);+ } finally {+ read.mockRestore();+ }+ });+it('does not assign an organization namespace to a plugin planted after the census', async () => {await fs.promises.mkdir(rootDir, { recursive: true });expect(manager.ensureNamespaceMigrationCensus()?.pendingRelIds).toEqual([]);diff --git a/apps/desktop/src/main/cindy-brain/ghostBackgroundRefresh.ts b/apps/desktop/src/main/cindy-brain/ghostBackgroundRefresh.tsnew file mode 100644index 0000000000..28cb54045d--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostBackgroundRefresh.ts@@ -0,0 +1,58 @@+import type { InstalledGhost } from '../../shared/ghost.js';+import type { PluginInstanceRegistry } from './pluginInstanceRegistry.js';++export interface GhostScanState {+ owner: string;+ mutation: object;+ identity: string;+}++export interface GhostBackgroundScan {+ ghosts: InstalledGhost[];+ registry: PluginInstanceRegistry;+ state: GhostScanState;+}++export interface GhostBackgroundRefresh {+ list(): Promise<InstalledGhost[]>;+ registry(): Promise<PluginInstanceRegistry>;+}++/** A single market refresh owns this view; no snapshot survives into the next refresh. */+export function createGhostBackgroundRefresh(deps: {+ state(): GhostScanState;+ scan(): Promise<GhostBackgroundScan>;+}): GhostBackgroundRefresh {+ const owner = deps.state().owner;+ let cached: GhostBackgroundScan | null = null;+ let flight: Promise<GhostBackgroundScan> | null = null;+ const current = () => {+ const state = deps.state();+ if (state.owner !== owner)+ throw new Error('ghost owner context changed during background refresh');+ return state;+ };+ const same = (a: GhostScanState, b: GhostScanState) =>+ a.owner === b.owner && a.mutation === b.mutation && a.identity === b.identity;+ const read = async <T>(project: (scan: GhostBackgroundScan) => T): Promise<T> => {+ for (let attempt = 0; attempt < 3; attempt++) {+ const state = current();+ if (cached && same(cached.state, state)) return project(cached);+ const pending = (flight ??= deps.scan());+ let scanned: GhostBackgroundScan;+ try {+ scanned = await pending;+ } finally {+ if (flight === pending) flight = null;+ }+ if (!same(scanned.state, current())) continue;+ cached = scanned;+ return project(scanned);+ }+ throw new Error('ghost installations changed repeatedly during background refresh');+ };+ return {+ list: () => read((scan) => scan.ghosts),+ registry: () => read((scan) => scan.registry),+ };+}diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 9e2f835e07..9e9ac8f52c 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -1,7 +1,7 @@import crypto from 'node:crypto';import fs from 'node:fs';import path from 'node:path';-import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';+import { readBoundedFileNoFollow, readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';import { isValidPluginNamespace } from '@cindy/plugin-protocol';import {@@ -306,6 +306,31 @@ export class GhostInstallReceiptStore {return { state: 'invalid', reason: result.reason };}+ /** Bind the owner root before yielding; use the same validation as the sync reader. */+ async readAsync(id: string): Promise<GhostInstallReceiptReadResult> {+ const root = this.rootDir();+ const receiptPath = this.receiptPath(id, root);+ let bytes: Buffer | null;+ try {+ let parent = root;+ for (const segment of id.split('/').slice(0, -1)) {+ parent = path.join(parent, segment);+ if (await classifyGhostDirEntry(parent) !== 'directory') {+ throw new Error('managed plugin parent is not a real directory');+ }+ }+ bytes = await readBoundedFileNoFollow(receiptPath, MAX_RECEIPT_BYTES, {+ nonBlocking: true,+ containWithin: await fs.promises.realpath(root),+ });+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === 'ENOENT'+ ? { state: 'legacy-unapproved' }+ : { state: 'invalid', reason: error instanceof Error ? error.message : String(error) };+ }+ return this.parseReceiptBytes(id, bytes);+ }+captureLegacyFirstPartyEligibilitySync(id: string, expectedRevision: string): void {const identity = parsePluginInstallRelId(id);const read = this.readForRecovery(id);@@ -356,6 +381,10 @@ export class GhostInstallReceiptStore {reason: error instanceof Error ? error.message : String(error),};}+ return this.parseReceiptBytes(id, bytes);+ }++ private parseReceiptBytes(id: string, bytes: Buffer | null): Extract<GhostInstallReceiptReadResult, { state: 'approved' | 'invalid' }> {if (!bytes) {return { state: 'invalid', reason: 'receipt 不是普通文件或超过大小上限' };}diff --git a/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts b/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.tsindex a39f02115a..5e1562f4e0 100644--- a/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts+++ b/apps/desktop/src/main/cindy-brain/pluginInstanceConfirmation.ts@@ -71,6 +71,7 @@ interface UnconfirmedConfirmationHost {readEvidence?(record: PluginInstanceRecord): InstanceConfirmationEvidence | null | undefined;isBlocked(): boolean;sync(): PluginInstanceRegistry;+ prepare?(): Promise<PluginInstanceRegistry>;ownerContextKey(): string;readApproval(relId: string): GhostInstallReceiptReadResult;orphanPendingNamespace?(record: PluginInstanceRecord, approval: GhostInstallReceiptReadResult): { namespace: string | null } | undefined;@@ -85,15 +86,17 @@ interface UnconfirmedConfirmationHost {export async function confirmUnconfirmedInstances(host: UnconfirmedConfirmationHost): Promise<{ unresolvedPending: number; mutationFailures: number }> {const readEvidence = host.readEvidence;if (host.isBlocked()) return { unresolvedPending: 0, mutationFailures: 0 };- const registry = host.sync();- if (host.isBlocked()) return { unresolvedPending: 0, mutationFailures: 0 };+ const ownerContextKey = host.ownerContextKey();+ const registry = host.prepare ? await host.prepare() : host.sync();+ if (host.isBlocked() || host.ownerContextKey() !== ownerContextKey) {+ 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 { unresolvedPending: 0, mutationFailures: 0 };const orphan = orphans.has(record.instanceKey);diff --git a/apps/desktop/src/main/installedGhostManifest.ts b/apps/desktop/src/main/installedGhostManifest.tsindex c9fb9bc156..60a09717fa 100644--- a/apps/desktop/src/main/installedGhostManifest.ts+++ b/apps/desktop/src/main/installedGhostManifest.ts@@ -6,7 +6,7 @@ import {validateInstalledGhostManifest,type GhostManifest,} from '../shared/ghost.js';-import { readBoundedFileNoFollowSync } from './utils/readBoundedFile.js';+import { readBoundedFileNoFollow, readBoundedFileNoFollowSync } from './utils/readBoundedFile.js';export type InstalledGhostManifestParse =| { ok: true; manifest: GhostManifest; legacyManualIgnored: boolean }@@ -24,8 +24,7 @@ export interface InstalledGhostManifestSnapshot {}export type InstalledGhostManifestSnapshotRead =- | { ok: true; snapshot: InstalledGhostManifestSnapshot }- | { ok: false; reason: string };+ { ok: true; snapshot: InstalledGhostManifestSnapshot } | { ok: false; reason: string };function isPlainObject(value: unknown): value is Record<string, unknown> {if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;@@ -77,33 +76,50 @@ export function readInstalledGhostManifestSnapshot(): InstalledGhostManifestSnapshotRead {try {const bytes = readBoundedFileNoFollowSync(path.join(dir, 'ghost.json'), maxBytes);- if (bytes === null) return { ok: false, reason: 'manifest is not a bounded regular file' };- const raw = JSON.parse(bytes.toString('utf8')) as unknown;- const parsed = parseInstalledGhostManifest(raw);- if (!parsed.ok) return parsed;- const current = parsed.manifest;- const legacy = ghostManifestToLegacyV2DigestFormat(current, raw);- return {- ok: true,- snapshot: {- manifest: current,- legacyManualIgnored: parsed.legacyManualIgnored,- rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),- releasedLegacyDigestFormat: legacy,- legacyDigestFormats:- JSON.stringify(current) === JSON.stringify(legacy) ? [current] : [current, legacy],- },- };+ return parseInstalledGhostManifestSnapshot(bytes);} catch {return { ok: false, reason: 'manifest could not be read' };}}-/** 当前投影与升级前 v2 slots 投影;调用方可兼容核对既有持久摘要。 */-export function readInstalledGhostManifestDigestFormats(+/** Background equivalent: same bounded handle and exact-byte identity rules. */+export async function readInstalledGhostManifestSnapshotAsync(dir: string,maxBytes: number,-): unknown[] {+): Promise<InstalledGhostManifestSnapshotRead> {+ try {+ return parseInstalledGhostManifestSnapshot(+ await readBoundedFileNoFollow(path.join(dir, 'ghost.json'), maxBytes, { nonBlocking: true }),+ );+ } catch {+ return { ok: false, reason: 'manifest could not be read' };+ }+}++function parseInstalledGhostManifestSnapshot(+ bytes: Buffer | null,+): InstalledGhostManifestSnapshotRead {+ if (bytes === null) return { ok: false, reason: 'manifest is not a bounded regular file' };+ const raw = JSON.parse(bytes.toString('utf8')) as unknown;+ const parsed = parseInstalledGhostManifest(raw);+ if (!parsed.ok) return parsed;+ const current = parsed.manifest;+ const legacy = ghostManifestToLegacyV2DigestFormat(current, raw);+ return {+ ok: true,+ snapshot: {+ manifest: current,+ legacyManualIgnored: parsed.legacyManualIgnored,+ rawManifestSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ releasedLegacyDigestFormat: legacy,+ legacyDigestFormats:+ JSON.stringify(current) === JSON.stringify(legacy) ? [current] : [current, legacy],+ },+ };+}++/** 当前投影与升级前 v2 slots 投影;调用方可兼容核对既有持久摘要。 */+export function readInstalledGhostManifestDigestFormats(dir: string, maxBytes: number): unknown[] {const result = readInstalledGhostManifestSnapshot(dir, maxBytes);return result.ok ? [...result.snapshot.legacyDigestFormats] : [];}diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex 64be003f09..a87ca5987e 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -3,6 +3,9 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { createGhostBackgroundRefresh } from '../../cindy-brain/ghostBackgroundRefresh.js';+import { emptyPluginInstanceRegistry } from '../../cindy-brain/pluginInstanceRegistry.js';+import type { InstalledGhost } from '../../../shared/ghost.js';import { afterEach, describe, expect, it, vi } from 'vitest';import JSZip from 'jszip';@@ -77,6 +80,11 @@ vi.mock('../../cindy-brain/index.js', () => ({refreshPluginUsageBindings: vi.fn(async () => undefined),confirmLegacyLibraryReattach: async () => false,getGhostManager: () => ({+ createBackgroundRefresh() {+ const state = () => ({ owner: JSON.stringify(runtime.session), mutation: runtime, identity: JSON.stringify(runtime.ghosts) });+ return createGhostBackgroundRefresh({ state, scan: async () => ({ ghosts: this.list() as unknown as InstalledGhost[], registry: emptyPluginInstanceRegistry(), state: state() }) });+ },+ async listAsync() { return this.list(); },list: () =>(runtime.listSequence ? runtime.listSequence() : runtime.ghosts).map((ghost) => ({...ghost,diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 1362c698e0..1e78d7144b 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -2,6 +2,8 @@ import crypto from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';+import { createGhostBackgroundRefresh } from '../../cindy-brain/ghostBackgroundRefresh.js';+import { emptyPluginInstanceRegistry } from '../../cindy-brain/pluginInstanceRegistry.js';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -111,6 +113,11 @@ vi.mock('../../cindy-brain/index.js', () => ({confirmLegacyLibraryReattach: (plugin: unknown) => runtime.confirmLegacyLibraryReattach(plugin),getGhostManager: () => ({isInstallationScanComplete: () => runtime.installationScanComplete,+ createBackgroundRefresh() {+ const state = () => ({ owner: JSON.stringify(runtime.session), mutation: runtime, identity: JSON.stringify(runtime.ghosts) });+ return createGhostBackgroundRefresh({ state, scan: async () => ({ ghosts: this.list() as unknown as InstalledGhost[], registry: emptyPluginInstanceRegistry(), state: state() }) });+ },+ async listAsync() { return this.list(); },resumePendingResidentsOffline: runtime.resumeOfflineResidents,reconcilePendingRootNamespaces: runtime.reconcilePendingRootNamespaces,list: () => {@@ -1051,20 +1058,38 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.listScans).toBe(singleScans);});- // A microtask-only refresh starved main's native message pump. This unit- // checks an event-loop turn between scans without timing assertions or sleep.- it('lets a queued event run between market reconciliation scans', async () => {+ // One installed plugin is projected in several snapshot phases. The unit+ // contract is one async manifest read, while returning the installed state;+ // existing scan-count tests do not detect repeated identity-file reads.+ it('shares manifest identities across phases of an unchanged market snapshot', async () => {+ const item = summary();+ const h = harness([item]);+ runtime.ghosts = [ghostEntry(item.ghostId)];+ h.ledger.upsertInstallation(recordForTest(item));+ const open = vi.spyOn(fs.promises, 'open');+ try {+ const snapshot = await h.service.snapshot();+ expect(snapshot.items[0]?.installState).toBe('installed');+ expect(runtime.listScans).toBe(1);+ expect(open.mock.calls.filter(([file]) => path.basename(String(file)) === 'ghost.json')).toHaveLength(1);+ } finally {+ open.mockRestore();+ }+ });++ // Even a reused installation view must let the native message pump run+ // between reconciliation phases; one unchanged refresh scans only once.+ it('lets a queued event run while sharing one market reconciliation scan', async () => {const h = harness([]);let eventRan = false;- let eventBeforeNextScan = false;let queued: ReturnType<typeof setImmediate> | undefined;runtime.onList = () => {if (runtime.listScans === 1) queued = setImmediate(() => { eventRan = true; });- if (runtime.listScans === 2) eventBeforeNextScan = eventRan;};try {expect((await h.service.snapshot()).items).toEqual([]);- expect(eventBeforeNextScan).toBe(true);+ expect(eventRan).toBe(true);+ expect(runtime.listScans).toBe(1);} finally {if (queued) clearImmediate(queued);}diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 534a0aa841..42aad9ad34 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -79,7 +79,9 @@ import {} from '../utils/readBoundedFile.js';import {readInstalledGhostManifestSnapshot,+ readInstalledGhostManifestSnapshotAsync,} from '../installedGhostManifest.js';+import type { GhostBackgroundRefresh } from '../cindy-brain/ghostBackgroundRefresh.js';import {withGhostInstallLock,withPluginDeliveryInstallLock,@@ -823,6 +825,27 @@ function listMarketInstallations(): InstalledGhost[] {return installed;}+/** Async discovery must retain the same incomplete-scan gate as mutation preflights. */+function createMarketBackgroundRefresh(): GhostBackgroundRefresh {+ const manager = getGhostManager();+ const refresh = manager.createBackgroundRefresh();+ return {+ registry: () => refresh.registry(),+ async list() {+ let ghosts: InstalledGhost[];+ try {+ ghosts = await refresh.list();+ } catch {+ throwIpcError('PRECONDITION_FAILED', 'Plugin installation scan is unavailable');+ }+ if (manager.isInstallationScanComplete?.() === false) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin installation scan is incomplete');+ }+ return ghosts;+ },+ };+}+/** Signed icon URLs rotate independently of installation/update facts. */function catalogReconciliationFingerprint(catalog: MarketCatalog): string {return crypto.createHash('sha256').update(JSON.stringify({@@ -848,6 +871,14 @@ interface LocalInstallSnapshot {manifestIdentityByStoragePart: ReadonlyMap<string, InstalledMarketManifestIdentity | null>;}+interface PluginMarketRefreshContext {+ installed: GhostBackgroundRefresh;+ identities?: {+ ghosts: readonly InstalledGhost[];+ values: LocalInstallSnapshot['manifestIdentityByStoragePart'];+ };+}+/** 未登录浏览公开目录时不读本机账本 / 已装列表,避免带出上一账号的安装态。 */const EMPTY_LOCAL_INSTALL_SNAPSHOT: LocalInstallSnapshot = {ghosts: [],@@ -1143,6 +1174,9 @@ export class PluginMarketService {}return this.snapshotPublicCatalogWithoutOwner();}+ const refresh: PluginMarketRefreshContext = {+ installed: createMarketBackgroundRefresh(),+ };const iconProjectionGeneration = this.nextCustomIconProjectionGeneration();const customSourceNames = this.customSourceNamesSafe(owner);const customDiscoveryPromise = this.discoverCustomEntriesBounded(@@ -1157,13 +1191,14 @@ export class PluginMarketService {requireSameMarketOwner(owner);const ledger = this.ledgerForOwner(owner);await this.ledgerMutation;- if (!options.discoveryOnly) await this.backfillInstalledManifestIdentities(ledger, owner);+ if (!options.discoveryOnly) await this.backfillInstalledManifestIdentities(ledger, owner, refresh);const reconcileCustomUpdates = async (): Promise<'completed' | 'failed'> => {const completed = await this.applyAutomaticUpgrades([],customDiscovery.entries,owner,ledger,+ refresh,);const outcome = completed ? 'completed' : 'failed';options.onDefaultReconciliationOutcome?.(outcome);@@ -1173,13 +1208,14 @@ export class PluginMarketService {await reconcileCustomUpdates();await yieldMarketReconciliation(owner);}+ const local = await this.localInstallSnapshotAsync(owner, ledger, refresh);requireSameMarketOwner(owner);if (!options.discoveryOnly) {- getGhostManager().resumePendingResidentsOffline?.();+ getGhostManager().resumePendingResidentsOffline?.(local.ghosts);}const snapshot: PluginMarketSnapshot = {items: this.withUpdateConsentHolds(- this.projectCustomItems(customDiscovery.entries, this.localInstallSnapshot(ledger)),+ this.projectCustomItems(customDiscovery.entries, local),owner,),unavailableReason,@@ -1245,15 +1281,15 @@ export class PluginMarketService {// 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 this.backfillInstalledManifestIdentities(ledger, owner, refresh);await yieldMarketReconciliation(owner);- await this.adoptLegacyInstallations(plugins, ledger, owner);+ await this.adoptLegacyInstallations(plugins, ledger, owner, refresh);await yieldMarketReconciliation(owner);- await this.recoverDisconnectedMarketInstallations(plugins, ledger, owner);+ await this.recoverDisconnectedMarketInstallations(plugins, ledger, owner, refresh);await yieldMarketReconciliation(owner);ledger.backfillMissingNamespacesFromCatalog(plugins);try {- await getGhostManager().reconcilePendingRootNamespaces?.(true);+ await getGhostManager().reconcilePendingRootNamespaces?.(true, refresh.installed);} catch (error) {namespaceReconciliationFailed = true;log.warn('namespace migration market reconcile failed', {@@ -1285,7 +1321,7 @@ export class PluginMarketService {if (rebound) await refreshPluginUsageBindings();}await yieldMarketReconciliation(owner);- await this.backfillOfficialCindyGithubTrust(ledger, owner);+ await this.backfillOfficialCindyGithubTrust(ledger, owner, refresh);await yieldMarketReconciliation(owner);// A snapshot is passive discovery: an empty runtime list can be caused by// startup, an owner transition, or a transient filesystem view. Only an@@ -1302,7 +1338,7 @@ export class PluginMarketService {let completed = !namespaceReconciliationFailed;await yieldMarketReconciliation(owner);try {- if (!(await this.applyDefaultInstalls(plugins, currentOrganization, owner, ledger))) {+ if (!(await this.applyDefaultInstalls(plugins, currentOrganization, owner, ledger, refresh))) {completed = false;}} catch (error) {@@ -1313,7 +1349,7 @@ export class PluginMarketService {}await yieldMarketReconciliation(owner);try {- if (!(await this.applyAutomaticUpgrades(plugins, customDiscovery.entries, owner, ledger))) {+ if (!(await this.applyAutomaticUpgrades(plugins, customDiscovery.entries, owner, ledger, refresh))) {completed = false;}} catch (error) {@@ -1331,7 +1367,8 @@ export class PluginMarketService {await yieldMarketReconciliation(owner);}requireSameMarketOwner(owner);- const local = this.localInstallSnapshot(ledger);+ const local = await this.localInstallSnapshotAsync(owner, ledger, refresh);+ requireSameMarketOwner(owner);const serverItems = plugins.map((plugin) => this.toItem(plugin, local));const items = this.withUpdateConsentHolds([...serverItems, ...this.projectCustomItems(customDiscovery.entries, local)],@@ -2815,12 +2852,14 @@ export class PluginMarketService {private async backfillInstalledManifestIdentities(ledger: PluginMarketLedger,owner: ActiveAppSession,+ refresh: PluginMarketRefreshContext,): Promise<void> {const candidates = Object.values(ledger.read().installations).filter((record) => record.installed && record.rawManifestSha256 === undefined,);if (candidates.length === 0) return;- const ghosts = listMarketInstallations();+ const ghosts = await refresh.installed.list();+ requireSameMarketOwner(owner);for (const candidate of candidates) {await yieldMarketReconciliation(owner);// Reject unchanged, ineligible records using one scan for the whole pass.@@ -2882,10 +2921,13 @@ export class PluginMarketService {plugins: readonly VisiblePluginSummary[],ledger: PluginMarketLedger,owner: ActiveAppSession,+ refresh: PluginMarketRefreshContext,): Promise<void> {const counts = ghostIdCounts(plugins);const installations = ledger.read().installations;- for (const ghost of listMarketInstallations()) {+ const ghosts = await refresh.installed.list();+ requireSameMarketOwner(owner);+ for (const ghost of ghosts) {if (installations[pluginLedgerRecordKey({ghostId: ghost.manifest.id,...deliveryNamespaceFields(ghost),@@ -2952,6 +2994,7 @@ export class PluginMarketService {plugins: readonly VisiblePluginSummary[],ledger: PluginMarketLedger,owner: ActiveAppSession,+ refresh: PluginMarketRefreshContext,): Promise<void> {const pluginIdCounts = new Map<string, number>();const ghostCounts = ghostIdCounts(plugins);@@ -2987,18 +3030,20 @@ export class PluginMarketService {continue;}- const findRecoveryCandidate = (): InstalledGhost | undefined => {- const installed = installedGhostMatchingMarketPlugin(record);+ const findRecoveryCandidate = (ghosts?: readonly InstalledGhost[]): InstalledGhost | undefined => {+ const installed = installedGhostMatchingMarketPlugin(record, ghosts);if (installed) return installed;const lookup = ledger.lookupInstallationsForNamespaceMigration(record.ghostId);if (lookup.kind !== 'found' || lookup.records.length !== 1) return undefined;- const candidates = listMarketInstallations().filter((ghost) =>+ const candidates = (ghosts ?? listMarketInstallations()).filter((ghost) =>ghost.manifest.id === record.ghostId && !hasDeliveryNamespace(ghost) &&installedGhostPhysicalRelId(ghost) === record.ghostId,);return candidates.length === 1 ? candidates[0] : undefined;};- const installed = findRecoveryCandidate();+ const ghosts = await refresh.installed.list();+ requireSameMarketOwner(owner);+ const installed = findRecoveryCandidate(ghosts);if (!installed || installed.approval.state !== 'approved') continue;try {@@ -3115,11 +3160,13 @@ export class PluginMarketService {private async backfillOfficialCindyGithubTrust(ledger: PluginMarketLedger,owner: ActiveAppSession,+ refresh: PluginMarketRefreshContext,): Promise<void> {const record = ledger.installationForPlugin({ namespace: null, ghostId: 'cindy-github' });requireSameMarketOwner(owner);- const installed = listMarketInstallations()- .find((ghost) => ghost.manifest.id === 'cindy-github' && ghost.namespace == null &&+ const ghosts = await refresh.installed.list();+ requireSameMarketOwner(owner);+ const installed = ghosts.find((ghost) => ghost.manifest.id === 'cindy-github' && ghost.namespace == null &&ghost.namespaceState !== 'pending');if (!record || !installed || !canBackfillOfficialCindyGithubTrust(record, installed)) return;const tempPath = path.join(@@ -3314,6 +3361,7 @@ export class PluginMarketService {currentOrganization: PluginCurrentOrganization | null | undefined,owner: ActiveAppSession,ledger: PluginMarketLedger,+ refresh: PluginMarketRefreshContext,): Promise<boolean> {let completed = true;const installSubject = defaultInstallSubject(owner);@@ -3327,7 +3375,8 @@ export class PluginMarketService {identityCounts.set(key, (identityCounts.get(key) ?? 0) + 1);}const ledgerData = ledger.read();- const local = this.localInstallSnapshot(ledger, ledgerData.installations);+ const local = await this.localInstallSnapshotAsync(owner, ledger, refresh, ledgerData.installations);+ requireSameMarketOwner(owner);for (const summary of plugins) {const uniqueIdentity = uniqueGhostIds.has(summary.ghostId) ||(hasDeliveryNamespace(summary) && identityCounts.get(pluginLedgerRecordKey(summary)) === 1);@@ -3531,9 +3580,11 @@ export class PluginMarketService {customEntries: readonly CustomMarketEntry[],owner: ActiveAppSession,ledger: PluginMarketLedger,+ refresh: PluginMarketRefreshContext,): Promise<boolean> {let reconciled = true;- let local = this.localInstallSnapshot(ledger);+ let local = await this.localInstallSnapshotAsync(owner, ledger, refresh);+ requireSameMarketOwner(owner);for (const summary of plugins) {const { target, record, installState } = this.serverMarketBinding(summary, local);const retryKey = this.automaticUpgradeRetryKey(owner, 'server', summary.id);@@ -3601,7 +3652,8 @@ export class PluginMarketService {ledger,);});- local = this.localInstallSnapshot(ledger);+ local = await this.localInstallSnapshotAsync(owner, ledger, refresh);+ requireSameMarketOwner(owner);this.clearAutomaticUpgradeFailure(retryKey, releaseKey);} catch (error) {if (isGhostInstallConsentRequiredError(error)) {@@ -3657,7 +3709,8 @@ export class PluginMarketService {{ mode: 'automatic' },owner,);- local = this.localInstallSnapshot(ledger);+ local = await this.localInstallSnapshotAsync(owner, ledger, refresh);+ requireSameMarketOwner(owner);this.clearAutomaticUpgradeFailure(retryKey, releaseKey);} catch (error) {if (isGhostInstallConsentRequiredError(error)) {@@ -3694,18 +3747,54 @@ export class PluginMarketService {ghostId?: string,): LocalInstallSnapshot {const ghosts = listMarketInstallations();+ return this.projectLocalInstallSnapshot(ghosts, installations, new Map(+ ghosts.filter((ghost) => ghostId === undefined || ghost.manifest.id === ghostId).map((ghost) => [+ installedGhostStoragePart(ghost),+ readInstalledMarketManifestIdentity(ghost.dir),+ ]),+ ));+ }++ private async localInstallSnapshotAsync(+ owner: ActiveAppSession,+ ledger: PluginMarketLedger,+ refresh: PluginMarketRefreshContext,+ installations?: LocalInstallSnapshot['installations'],+ ): Promise<LocalInstallSnapshot> {+ for (let attempt = 0; attempt < 3; attempt++) {+ requireSameMarketOwner(owner);+ const ghosts = await refresh.installed.list();+ requireSameMarketOwner(owner);+ if (refresh.identities?.ghosts !== ghosts) {+ const identities = new Map<string, InstalledMarketManifestIdentity | null>();+ for (const ghost of ghosts) {+ const result = await readInstalledGhostManifestSnapshotAsync(ghost.dir, GHOST_MANIFEST_MAX_BYTES);+ requireSameMarketOwner(owner);+ identities.set(installedGhostStoragePart(ghost), result.ok ? installedMarketManifestIdentity(result.snapshot) : null);+ }+ if (await refresh.installed.list() !== ghosts) continue;+ requireSameMarketOwner(owner);+ refresh.identities = { ghosts, values: identities };+ }+ // Ledger routing stays fresh; mutation preflights re-read approval under+ // their locks. Only this refresh's read-only installation view is shared.+ return this.projectLocalInstallSnapshot(ghosts, installations ?? ledger.read().installations, refresh.identities.values);+ }+ throw new Error('Plugin installations changed repeatedly while reading market identities');+ }++ private projectLocalInstallSnapshot(+ ghosts: InstalledGhost[],+ installations: LocalInstallSnapshot['installations'],+ manifestIdentityByStoragePart: LocalInstallSnapshot['manifestIdentityByStoragePart'],+ ): LocalInstallSnapshot {const records = Object.values(installations).filter((record) => record.installed);return {ghosts,ghostsById: indexByGhostId(ghosts, (ghost) => ghost.manifest.id),installations,installedRecordsByGhostId: indexByGhostId(records, (record) => record.ghostId),- manifestIdentityByStoragePart: new Map(- ghosts.filter((ghost) => ghostId === undefined || ghost.manifest.id === ghostId).map((ghost) => [- installedGhostStoragePart(ghost),- readInstalledMarketManifestIdentity(ghost.dir),- ]),- ),+ manifestIdentityByStoragePart,};}