Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): bound package negative cache reuse
lizzjinab5b6ac39d00
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.tsindex 761306c2a1..815c6ab038 100644--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts@@ -1578,36 +1578,50 @@ describe('Pi package executable-code boundary', () => {{ enabled: false, warning: 'inspection-limit' },],});- const state = JSON.parse(await fs.readFile(+ const stateFile = await fs.readFile(path.join(runtime.userData, 'pi-package-home', 'cindy-package-state.json'),'utf8',- )) as {- disabledSources: string[];- snapshotUnavailablePackages: Array<{- source: string;- installedRoot: string;- installationIdentity: string;- snapshotRoot: string;- warning: string;- }>;- };- expect(state.disabledSources).toEqual([]);- expect(state.snapshotUnavailablePackages).toEqual([- expect.objectContaining({- source: sources[1],- installedRoot: await fs.realpath(packageRoots[1]!),- installationIdentity: expect.stringMatching(/^[a-f0-9]{64}$/),- snapshotRoot: await fs.realpath(packageRoots[1]!),- warning: 'inspection-limit',- }),- expect.objectContaining({- source: sources[2],- installedRoot: await fs.realpath(packageRoots[2]!),- installationIdentity: expect.stringMatching(/^[a-f0-9]{64}$/),- snapshotRoot: await fs.realpath(packageRoots[2]!),- warning: 'inspection-limit',- }),- ]);+ ).catch((error: NodeJS.ErrnoException) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (stateFile) {+ const state = JSON.parse(stateFile) as {+ disabledSources: string[];+ snapshotUnavailablePackages: unknown[];+ };+ expect(state.disabledSources).toEqual([]);+ expect(state.snapshotUnavailablePackages).toEqual([]);+ }++ vi.resetModules();+ const nextStore = await import('../pi-package-store.js');+ const recoveredRoot = path.join(runtime.userData, 'aggregate-package-recovered');+ await expect(nextStore.resolveManagedPiPackageResources({+ snapshotRoot: recoveredRoot,+ snapshotLimits: {+ maxEntries: 100,+ maxBytes: 1024 * 1024,+ maxDurationMs: 10_000,+ },+ })).resolves.toMatchObject({+ skills: [+ expect.objectContaining({+ path: path.join(recoveredRoot, '0', 'skills', 'skill-0', 'SKILL.md'),+ }),+ expect.objectContaining({+ path: path.join(recoveredRoot, '1', 'skills', 'skill-1', 'SKILL.md'),+ }),+ expect.objectContaining({+ path: path.join(recoveredRoot, '2', 'skills', 'skill-2', 'SKILL.md'),+ }),+ ],+ packageRoots: [+ path.join(recoveredRoot, '0'),+ path.join(recoveredRoot, '1'),+ path.join(recoveredRoot, '2'),+ ],+ });});it('reuses a persisted inspection-limit without walking the package tree for every session', async () => {@@ -1699,6 +1713,46 @@ describe('Pi package executable-code boundary', () => {});});+ it('retries a legacy v4 inspection-limit without retry metadata once', async () => {+ const { source } = await createSkillOnlyPackage('npm:legacy-v4-snapshot-limit');+ const store = await import('../pi-package-store.js');+ await expect(store.resolveManagedPiPackageResources({+ snapshotRoot: path.join(runtime.userData, 'legacy-v4-limited-snapshot'),+ snapshotLimits: {+ maxEntries: 1,+ maxBytes: 1024 * 1024,+ maxDurationMs: 10_000,+ },+ })).resolves.toMatchObject({ packageRoots: [] });++ const statePath = path.join(+ runtime.userData,+ 'pi-package-home',+ 'cindy-package-state.json',+ );+ const state = JSON.parse(await fs.readFile(statePath, 'utf8')) as {+ snapshotUnavailablePackages: Array<{ retryAfterEpochMs?: number }>;+ };+ expect(state.snapshotUnavailablePackages).toHaveLength(1);+ delete state.snapshotUnavailablePackages[0]!.retryAfterEpochMs;+ await fs.writeFile(statePath, JSON.stringify(state));++ vi.resetModules();+ const nextStore = await import('../pi-package-store.js');+ const recoveredRoot = path.join(runtime.userData, 'legacy-v4-recovered-snapshot');+ await expect(nextStore.resolveManagedPiPackageResources({+ snapshotRoot: recoveredRoot,+ })).resolves.toMatchObject({+ skills: [expect.objectContaining({+ path: path.join(recoveredRoot, '0', 'skills', 'managed-skill', 'SKILL.md'),+ })],+ packageRoots: [path.join(recoveredRoot, '0')],+ });+ await expect(nextStore.listPiPackages()).resolves.toMatchObject({+ packages: [expect.objectContaining({ source, enabled: true })],+ });+ });+it('persists a deterministic inspection-stage limit before the next session walks metadata', async () => {const { root, source } = await createPackage({ oversizedManifest: true });const store = await import('../pi-package-store.js');@@ -1725,6 +1779,7 @@ describe('Pi package executable-code boundary', () => {vi.resetModules();const manifestPath = path.join(root, 'package.json');+ const canonicalManifestPath = path.resolve(await fs.realpath(manifestPath));const openSpy = vi.spyOn(fs, 'open');const opendirSpy = vi.spyOn(fs, 'opendir');try {@@ -1735,9 +1790,10 @@ describe('Pi package executable-code boundary', () => {// The durable negative identity includes one bounded package.json digest// so in-place upgrades invalidate it. Reuse must still avoid walking,// fingerprinting, or copying the package tree.- expect(openSpy.mock.calls.filter(([candidate]) => (- path.resolve(String(candidate)) === path.resolve(manifestPath)- ))).toHaveLength(1);+ const openedPaths = await Promise.all(openSpy.mock.calls.map(async ([candidate]) => (+ path.resolve(await fs.realpath(String(candidate)))+ )));+ expect(openedPaths.filter((candidate) => candidate === canonicalManifestPath)).toHaveLength(1);expect(opendirSpy).not.toHaveBeenCalled();} finally {openSpy.mockRestore();@@ -1801,14 +1857,16 @@ describe('Pi package executable-code boundary', () => {const { root, source } = await createSkillOnlyPackage('npm:inspection-duration-retry');const store = await import('../pi-package-store.js');const originalReaddir = fs.readdir.bind(fs);+ const canonicalSkillsRoot = path.resolve(await fs.realpath(path.join(root, 'skills')));let now = Date.now();let delayedInspection = false;const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);const readdirSpy = vi.spyOn(fs, 'readdir').mockImplementation(async (...args) => {const result = await originalReaddir(...args as Parameters<typeof fs.readdir>);+ const canonicalCandidate = path.resolve(await fs.realpath(String(args[0])));if (!delayedInspection- && path.resolve(String(args[0])) === path.resolve(root, 'skills')+ && canonicalCandidate === canonicalSkillsRoot) {delayedInspection = true;now += 2_001;@@ -1902,59 +1960,67 @@ describe('Pi package executable-code boundary', () => {});});- it('does not reuse a persisted inspection-limit after package content changes under a stable root identity', async () => {+ it('retries a persisted inspection-limit after deep package content shrinks under a stable root identity', async () => {const { root, source } = await createSkillOnlyPackage('npm:mutated-installation');- const store = await import('../pi-package-store.js');- await expect(- store.resolveManagedPiPackageResources({- snapshotRoot: path.join(runtime.userData, 'mutated-installation-limited-snapshot'),- snapshotLimits: {- maxEntries: 1,- maxBytes: 1024 * 1024,- maxDurationMs: 10_000,- },- }),- ).resolves.toMatchObject({ packageRoots: [] });-- const canonicalRoot = await fs.realpath(root);- const stableRootStat = await fs.stat(canonicalRoot);- await fs.writeFile(- path.join(root, 'package.json'),- JSON.stringify({- name: source.slice(4),- version: '2.0.0',- pi: { skills: ['./skills'] },- }),- );- await fs.writeFile(- path.join(root, 'skills', 'managed-skill', 'SKILL.md'),- '# Mutated installation\n',- );-- // Root directory metadata is not a content identity. Pin it to the value- // captured for the failed installation so this regression stays- // deterministic on filesystems that happen to touch directory timestamps.+ const deepPayload = path.join(root, 'skills', 'managed-skill', 'payload.bin');+ await fs.writeFile(deepPayload, Buffer.alloc(4_096));+ let now = Date.now();+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);const originalLstat = fs.lstat.bind(fs);const originalStat = fs.stat.bind(fs);- const lstatSpy = vi.spyOn(fs, 'lstat').mockImplementation(async (target, options) => (- path.resolve(String(target)) === canonicalRoot- ? stableRootStat- : originalLstat(target, options as never)- ));- const statSpy = vi.spyOn(fs, 'stat').mockImplementation(async (target, options) => (- path.resolve(String(target)) === canonicalRoot- ? stableRootStat- : originalStat(target, options as never)- ));+ let lstatSpy: { mockRestore(): void } | undefined;+ let statSpy: { mockRestore(): void } | undefined;try {+ const store = await import('../pi-package-store.js');+ await expect(+ store.resolveManagedPiPackageResources({+ snapshotRoot: path.join(runtime.userData, 'mutated-installation-limited-snapshot'),+ snapshotLimits: {+ maxEntries: 100,+ maxBytes: 1_024,+ maxDurationMs: 10_000,+ },+ }),+ ).resolves.toMatchObject({ packageRoots: [] });++ const canonicalRoot = await fs.realpath(root);+ const stableRootStat = await fs.stat(canonicalRoot);+ await fs.writeFile(deepPayload, Buffer.from('.'));+ now += 24 * 60 * 60 * 1_000;++ // Root directory metadata is not a content identity. Pin it to the value+ // captured for the failed installation so this regression stays+ // deterministic on filesystems that happen to touch directory timestamps.+ lstatSpy = vi.spyOn(fs, 'lstat').mockImplementation(async (target, options) => (+ path.resolve(String(target)) === canonicalRoot+ ? stableRootStat+ : originalLstat(target, options as never)+ ));+ statSpy = vi.spyOn(fs, 'stat').mockImplementation(async (target, options) => (+ path.resolve(String(target)) === canonicalRoot+ ? stableRootStat+ : originalStat(target, options as never)+ ));vi.resetModules();const replacementStore = await import('../pi-package-store.js');- await expect(replacementStore.listPiPackages()).resolves.toMatchObject({- packages: [expect.objectContaining({ source, version: '2.0.0', enabled: true })],+ const recoveredRoot = path.join(runtime.userData, 'mutated-installation-recovered-snapshot');+ await expect(replacementStore.resolveManagedPiPackageResources({+ snapshotRoot: recoveredRoot,+ snapshotLimits: {+ maxEntries: 100,+ maxBytes: 1_024,+ maxDurationMs: 10_000,+ },+ })).resolves.toMatchObject({+ skills: [expect.objectContaining({+ path: path.join(recoveredRoot, '0', 'skills', 'managed-skill', 'SKILL.md'),+ })],+ packageRoots: [path.join(recoveredRoot, '0')],});} finally {- lstatSpy.mockRestore();- statSpy.mockRestore();+ lstatSpy?.mockRestore();+ statSpy?.mockRestore();+ nowSpy.mockRestore();}});diff --git a/apps/desktop/src/main/maker-host/pi-package-store.ts b/apps/desktop/src/main/maker-host/pi-package-store.tsindex a21ee26916..800c01341e 100644--- a/apps/desktop/src/main/maker-host/pi-package-store.ts+++ b/apps/desktop/src/main/maker-host/pi-package-store.ts@@ -73,6 +73,7 @@ const MAX_INSPECTED_PACKAGES = 128;const MAX_ALL_INSPECTION_MS = 10_000;const MAX_EXTENSION_FILES = 128;const INSPECTION_CACHE_MS = 1_000;+const SNAPSHOT_UNAVAILABLE_RETRY_MS = 6 * 60 * 60 * 1_000;const SNAPSHOT_COPY_CHUNK_BYTES = 256 * 1024;const DEFAULT_SNAPSHOT_LIMITS: PiPackageSnapshotLimits = {maxEntries: 10_000,@@ -187,11 +188,18 @@ interface SnapshotUnavailablePackageIdentity {interface SnapshotUnavailablePackageProjection extends SnapshotUnavailablePackageIdentity {warning: SnapshotUnavailableWarning;+ retryAfterEpochMs?: number;}/** Durable deterministic failure bound to one exact package installation. */interface PersistedSnapshotUnavailablePackage extends SnapshotUnavailablePackageIdentity {warning: 'inspection-limit';+ retryAfterEpochMs: number;+}++interface SnapshotUnavailableRootProjection {+ warning: SnapshotUnavailableWarning;+ durable: boolean;}interface PiPackageState {@@ -509,15 +517,39 @@ function parseSnapshotUnavailablePackages(&& typeof entry.installationIdentity === 'string'&& /^[a-f0-9]{64}$/.test(entry.installationIdentity)&& entry.warning === 'inspection-limit'+ && (+ entry.retryAfterEpochMs === undefined+ || (+ typeof entry.retryAfterEpochMs === 'number'+ && Number.isSafeInteger(entry.retryAfterEpochMs)+ && entry.retryAfterEpochMs >= 0+ )+ )))) return undefined;- return (entries as PersistedSnapshotUnavailablePackage[]).toSorted((left, right) => (+ return sortSnapshotUnavailablePackages(entries.map((entry) => ({+ ...entry,+ // v4 states written before this additive field retry once after upgrade.+ retryAfterEpochMs: entry.retryAfterEpochMs ?? 0,+ })) as PersistedSnapshotUnavailablePackage[]);+}++function sortSnapshotUnavailablePackages(+ entries: PersistedSnapshotUnavailablePackage[],+): PersistedSnapshotUnavailablePackage[] {+ return entries.toSorted((left, right) => (left.source.localeCompare(right.source)|| left.installedRoot.localeCompare(right.installedRoot)|| left.snapshotRoot.localeCompare(right.snapshotRoot)));}+function isSnapshotUnavailableRetryDue(+ entry: SnapshotUnavailablePackageProjection,+): boolean {+ return entry.retryAfterEpochMs !== undefined && Date.now() >= entry.retryAfterEpochMs;+}+function snapshotUnavailablePackageKey(entry: SnapshotUnavailablePackageIdentity,): string {@@ -534,6 +566,7 @@ function applySharedSnapshotUnavailablePackages(): void {snapshotUnavailablePackages.clear();for (const pkg of packages) {+ if (isSnapshotUnavailableRetryDue(pkg)) continue;snapshotUnavailablePackages.set(snapshotUnavailablePackageKey(pkg), pkg);}}@@ -1586,6 +1619,7 @@ async function inspectPackage(installationIdentity,snapshotRoot,warning: 'inspection-limit' as const,+ retryAfterEpochMs: Date.now() + SNAPSHOT_UNAVAILABLE_RETRY_MS,}: undefined;return {@@ -1633,7 +1667,7 @@ async function persistedSnapshotLimitProjection(path.resolve(entry.snapshotRoot) === path.resolve(snapshotRoot) &&entry.installationIdentity === installationIdentity,);- if (!persisted) return undefined;+ if (!persisted || isSnapshotUnavailableRetryDue(persisted)) return undefined;return {rawSource: pkg.source,view: {@@ -1883,13 +1917,13 @@ export async function capturePiPackageEnableIdentity(source: string): Promise<Pi}async function persistSnapshotUnavailableProjection(- unavailableRoots: Iterable<readonly [string, SnapshotUnavailableWarning]>,+ unavailableRoots: Iterable<readonly [string, SnapshotUnavailableRootProjection]>,inspected: readonly InspectedPackage[] = [],): Promise<boolean> {const state = await requireState();- const warningsByRoot = new Map<string, SnapshotUnavailableWarning>();- for (const [root, warning] of unavailableRoots) {- warningsByRoot.set(path.resolve(root), warning);+ const projectionsByRoot = new Map<string, SnapshotUnavailableRootProjection>();+ for (const [root, projection] of unavailableRoots) {+ projectionsByRoot.set(path.resolve(root), projection);}const projectionByIdentity = new Map<string, SnapshotUnavailablePackageProjection>();const durableByIdentity = new Map<string, PersistedSnapshotUnavailablePackage>();@@ -1905,8 +1939,8 @@ async function persistSnapshotUnavailableProjection(}if (!pkg.installedRoot || !pkg.installationIdentity) continue;for (const snapshotRoot of pkg.launch.packageRoots) {- const warning = warningsByRoot.get(path.resolve(snapshotRoot));- if (!warning) continue;+ const rootProjection = projectionsByRoot.get(path.resolve(snapshotRoot));+ if (!rootProjection) continue;try {const { canonicalPath, stat } = await resolveStablePackagePath(pkg.installedRoot,@@ -1920,14 +1954,15 @@ async function persistSnapshotUnavailableProjection(installedRoot: canonicalPath,installationIdentity: currentInstallationIdentity,snapshotRoot: path.resolve(snapshotRoot),- warning,+ warning: rootProjection.warning,};const key = snapshotUnavailablePackageKey(projection);projectionByIdentity.set(key, projection);- if (warning === 'inspection-limit') {+ if (rootProjection.warning === 'inspection-limit' && rootProjection.durable) {durableByIdentity.set(key, {...projection,warning: 'inspection-limit',+ retryAfterEpochMs: Date.now() + SNAPSHOT_UNAVAILABLE_RETRY_MS,});}} catch {@@ -1935,11 +1970,7 @@ async function persistSnapshotUnavailableProjection(}}}- const nextPackages = [...durableByIdentity.values()].toSorted((left, right) => (- left.source.localeCompare(right.source)- || left.installedRoot.localeCompare(right.installedRoot)- || left.snapshotRoot.localeCompare(right.snapshotRoot)- ));+ const nextPackages = sortSnapshotUnavailablePackages([...durableByIdentity.values()]);const changed = JSON.stringify(nextPackages) !== JSON.stringify(state.snapshotUnavailablePackages);if (changed) {await writeState({@@ -2031,6 +2062,7 @@ export async function resolveManagedPiPackageResources(const verificationBudget = createSnapshotBudgetCounters(snapshotLimits);const unavailableVerificationRoots = new Map<string, SnapshotUnavailableWarning>();const transientUnavailableVerificationRoots = new Set<string>();+ const durableUnavailableVerificationRoots = new Set<string>();const failedVerificationIndexes = new Set<number>();let aggregateVerificationLimitReached = false;let aggregateVerificationLimitReason: PiPackageSnapshotLimitReason | undefined;@@ -2063,6 +2095,9 @@ export async function resolveManagedPiPackageResources(if (error.reason === 'duration') {transientUnavailableVerificationRoots.add(sourceRoot);}+ if (error.scope === 'package' && error.reason !== 'duration') {+ durableUnavailableVerificationRoots.add(sourceRoot);+ }failedVerificationIndexes.add(index);if (error.scope === 'aggregate') {aggregateVerificationLimitReached = true;@@ -2118,25 +2153,37 @@ export async function resolveManagedPiPackageResources(...(stageMetadata?.transientSkippedPackageRoots ?? []),...transientUnavailableVerificationRoots,];+ const nextDurableSkippedRoots = [+ ...(stageMetadata?.durableSkippedPackageRoots ?? []),+ ...durableUnavailableVerificationRoots,+ ];snapshotStageMetadata.set(filtered, {sourcePackageRoots: copiedSourceRoots.filter((_, index) => (!failedVerificationIndexes.has(index))),skippedPackageRoots: [...new Set(nextSkippedRoots)],transientSkippedPackageRoots: [...new Set(nextTransientSkippedRoots)],+ durableSkippedPackageRoots: [...new Set(nextDurableSkippedRoots)],});staged = filtered;}- const unavailableRoots = new Map<string, SnapshotUnavailableWarning>();+ const unavailableRoots = new Map<string, SnapshotUnavailableRootProjection>();const transientSkippedRoots = new Set(stageMetadata?.transientSkippedPackageRoots ?? []);+ const durableSkippedRoots = new Set(stageMetadata?.durableSkippedPackageRoots ?? []);for (const root of stageMetadata?.skippedPackageRoots ?? []) {if (transientSkippedRoots.has(root)) continue;- unavailableRoots.set(root, 'inspection-limit');+ unavailableRoots.set(root, {+ warning: 'inspection-limit',+ durable: durableSkippedRoots.has(root),+ });}for (const [root, warning] of unavailableVerificationRoots) {if (transientUnavailableVerificationRoots.has(root)) continue;- unavailableRoots.set(root, warning);+ unavailableRoots.set(root, {+ warning,+ durable: durableUnavailableVerificationRoots.has(root),+ });}if (startupTiming) {const skippedThisStart = new Set([@@ -2162,10 +2209,14 @@ export async function resolveManagedPiPackageResources(const warning = error instanceof PiPackageSnapshotLimitError? 'inspection-limit': 'inspection-failed';- const persistableRoots = error instanceof PiPackageSnapshotLimitError- && error.reason === 'duration'- ? []- : resources.packageRoots.map((root) => [root, warning] as const);+ const persistableRoots: Array<readonly [string, SnapshotUnavailableRootProjection]> =+ error instanceof PiPackageSnapshotLimitError && error.reason === 'duration'+ ? []+ : resources.packageRoots.map((root) => [root, {+ warning,+ durable: error instanceof PiPackageSnapshotLimitError+ && error.scope === 'package',+ }] as const);if (await persistSnapshotUnavailableProjection(persistableRoots, inspected)) {await publishPiPackagesChanged({ invalidateCache: false });}@@ -2686,6 +2737,8 @@ interface SnapshotStageMetadata {skippedPackageRoots: string[];/** Load-dependent duration failures that must remain retryable. */transientSkippedPackageRoots: string[];+ /** Package-scoped deterministic limits that may be cached across sessions. */+ durableSkippedPackageRoots: string[];}const snapshotStageMetadata = new WeakMap<PiManagedPackageResources, SnapshotStageMetadata>();@@ -2700,6 +2753,7 @@ export async function stageManagedPackageSnapshot(const mappings: Array<{ source: string; target: string; directory: boolean }> = [];const skippedPackageRoots: string[] = [];const transientSkippedPackageRoots: string[] = [];+ const durableSkippedPackageRoots: string[] = [];const aggregateBudget = createSnapshotBudgetCounters(limits);let aggregateLimitReached = false;let aggregateLimitReason: PiPackageSnapshotLimitReason | undefined;@@ -2741,6 +2795,9 @@ export async function stageManagedPackageSnapshot(const skippedRoot = source ?? path.resolve(rawRoot);skippedPackageRoots.push(skippedRoot);if (error.reason === 'duration') transientSkippedPackageRoots.push(skippedRoot);+ if (error.scope === 'package' && error.reason !== 'duration') {+ durableSkippedPackageRoots.push(skippedRoot);+ }await fs.rm(path.join(temporaryRoot, String(index)), {recursive: true,force: true,@@ -2781,6 +2838,7 @@ export async function stageManagedPackageSnapshot(sourcePackageRoots: mappings.map((mapping) => mapping.source),skippedPackageRoots,transientSkippedPackageRoots,+ durableSkippedPackageRoots,});return mappedResources;} catch (error) {