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(pi): reconcile startup analysis and runtime cleanup with main

zqchris4e61077384bf
diff --cc apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
index d607bfafd5,8e27abb176..0b53ee77aa
--- 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
@@@ -618,32 -612,6 +618,69 @@@ describe('Pi package executable-code bo
await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([]);
});
+ it('collects startup metadata without copying native packages into a session snapshot', async () => {
+ const { root, source } = await createSkillOnlyPackage('npm:native-startup-metadata');
+ const aliasParent = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-pi-package-security-alias-'));
+ roots.push(aliasParent);
+ const aliasRoot = path.join(aliasParent, 'package-link');
+ await fs.symlink(root, aliasRoot, process.platform === 'win32' ? 'junction' : 'dir');
+ runtime.listOutput = `User packages:\n ${source}\n ${aliasRoot}\n`;
+ const canonicalRoot = await fs.realpath(aliasRoot);
+ const store = await import('../pi-package-store.js');
+ const copySpy = vi.spyOn(fs, 'copyFile');
+ try {
+ await expect(store.resolveManagedPiPackageResources({
+ startupTraceId: '0123456789abcdef',
+ })).resolves.toMatchObject({
+ skills: [expect.objectContaining({
+ path: path.join(canonicalRoot, 'skills', 'managed-skill', 'SKILL.md'),
+ })],
+ packageRoots: [canonicalRoot],
+ });
+ expect(copySpy).not.toHaveBeenCalled();
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([aliasRoot]);
+ } finally {
+ copySpy.mockRestore();
+ }
+ });
+
++ it('coalesces startup diagnostics and honors the existing short inspection cache', async () => {
++ const { root } = await createSkillOnlyPackage('npm:concurrent-startup-metadata');
++ const store = await import('../pi-package-store.js');
++ const results = await Promise.all([
++ store.resolveManagedPiPackageResources({ startupTraceId: '0123456789abcdef' }),
++ store.resolveManagedPiPackageResources({ startupTraceId: 'fedcba9876543210' }),
++ ]);
++ expect(results[0].packageRoots).toEqual([await fs.realpath(root)]);
++ expect(results[1]).toEqual(results[0]);
++ expect(runtime.spawns.filter(({ args }) => args.includes('list'))).toHaveLength(1);
++ await store.resolveManagedPiPackageResources({ startupTraceId: '1111111111111111' });
++ expect(runtime.spawns.filter(({ args }) => args.includes('list'))).toHaveLength(1);
++ });
++
++ it.each([null, [null], [{ warning: 'bad-cache' }]])(
++ 'keeps native loading and disable preferences when advisory cache is malformed: %j',
++ async (snapshotUnavailablePackages) => {
++ const { root, source } = await createSkillOnlyPackage('npm:cache-corruption');
++ const stateDir = path.join(runtime.userData, 'pi-package-home');
++ await fs.mkdir(stateDir, { recursive: true });
++ await fs.writeFile(path.join(stateDir, 'cindy-package-state.json'), JSON.stringify({
++ version: 3,
++ disabledSources: [],
++ approvedExtensionSources: [],
++ approvedExtensionFingerprints: {},
++ snapshotUnavailablePackages,
++ }));
++ const store = await import('../pi-package-store.js');
++ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([root]);
++ await store.mutatePiPackage({ action: 'set-enabled', source, enabled: false });
++ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([]);
++ const saved = JSON.parse(await fs.readFile(path.join(stateDir, 'cindy-package-state.json'), 'utf8'));
++ expect(saved.version).toBe(3);
++ expect(saved.disabledSources).toEqual([source]);
++ },
++ );
++
it('fails explicitly instead of widening a filtered package when settings are invalid', async () => {
const { root, source } = await createPackage({ source: 'npm:filtered-invalid' });
runtime.listOutput = `User packages:\n ${source} (filtered)\n ${root}\n`;
@@@ -1935,280 -1895,6 +1972,281 @@@
{ enabled: true, warning: 'inspection-limit' },
],
});
+ const stateFile = await fs.readFile(
+ path.join(runtime.userData, 'pi-package-home', 'cindy-package-state.json'),
+ 'utf8',
+ ).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 () => {
+ const { root, source } = await createSkillOnlyPackage('npm:oversized-skill');
+ const store = await import('../pi-package-store.js');
+ const snapshotLimits = {
+ maxEntries: 1,
+ maxBytes: 1024 * 1024,
+ maxDurationMs: 10_000,
+ };
+
+ await expect(
+ store.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, 'first-oversized-skill-snapshot'),
+ snapshotLimits,
+ }),
+ ).resolves.toEqual({
+ extensions: [],
+ skills: [],
+ promptTemplates: [],
+ packageRoots: [],
+ });
+ await expect(store.listPiPackages()).resolves.toMatchObject({
+ packages: [{ source, enabled: true, warning: 'inspection-limit' }],
+ });
+
+ const canonicalRoot = await fs.realpath(root);
+ const opendirSpy = vi.spyOn(fs, 'opendir');
+ try {
+ await expect(
+ store.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, 'second-oversized-skill-snapshot'),
+ snapshotLimits,
+ }),
+ ).resolves.toEqual({
+ extensions: [],
+ skills: [],
+ promptTemplates: [],
+ packageRoots: [],
+ });
+ const repeatedPackageWalks = opendirSpy.mock.calls.filter(([candidate]) => {
+ const resolved = path.resolve(String(candidate));
+ return resolved === canonicalRoot || resolved.startsWith(`${canonicalRoot}${path.sep}`);
+ });
+ expect(repeatedPackageWalks).toEqual([]);
+ } finally {
+ opendirSpy.mockRestore();
+ }
+ });
+
+ it('does not reuse a persisted inspection-limit for a different source at the same root', async () => {
+ const { root } = await createSkillOnlyPackage('npm:oversized-source-a');
+ const store = await import('../pi-package-store.js');
+ await expect(
+ store.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, 'source-a-limited-snapshot'),
+ snapshotLimits: {
+ maxEntries: 1,
+ maxBytes: 1024 * 1024,
+ maxDurationMs: 10_000,
+ },
+ }),
+ ).resolves.toMatchObject({ packageRoots: [] });
+
+ const replacementSource = 'npm:replacement-source-b';
+ runtime.listOutput = `User packages:\n ${replacementSource}\n ${root}\n`;
+ vi.resetModules();
+ const replacementStore = await import('../pi-package-store.js');
+ await expect(replacementStore.listPiPackages()).resolves.toMatchObject({
+ packages: [
+ expect.objectContaining({
+ source: replacementSource,
+ enabled: true,
+ }),
+ ],
+ });
+ const recoveredRoot = path.join(runtime.userData, 'source-b-recovered-snapshot');
+ await expect(
+ replacementStore.resolveManagedPiPackageResources({
+ snapshotRoot: recoveredRoot,
+ }),
+ ).resolves.toMatchObject({
+ skills: [
+ expect.objectContaining({
+ path: path.join(recoveredRoot, '0', 'skills', 'managed-skill', 'SKILL.md'),
+ }),
+ ],
+ packageRoots: [path.join(recoveredRoot, '0')],
+ });
+ });
+
+ 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);
++ Object.assign(state, { version: 4 }); // Earlier PR builds wrote this version.
+ 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.each(['snapshot', 'metadata'] as const)('persists a deterministic inspection-stage limit for %s requests', async (mode) => {
+ const { root, source } = await createPackage({ oversizedManifest: true });
+ const store = await import('../pi-package-store.js');
+ await expect(store.resolveManagedPiPackageResources({
+ ...(mode === 'snapshot'
+ ? { snapshotRoot: path.join(runtime.userData, 'inspection-limit-first-snapshot') }
+ : { startupTraceId: '0123456789abcdef' }),
+ })).resolves.toEqual({
+ extensions: [],
+ skills: [],
+ promptTemplates: [],
+ packageRoots: [],
+ });
+
+ const statePath = path.join(
+ runtime.userData,
+ 'pi-package-home',
+ 'cindy-package-state.json',
+ );
+ await expect(fs.readFile(statePath, 'utf8')).resolves.toSatisfy((raw) => {
+ const state = JSON.parse(raw) as {
+ snapshotUnavailablePackages: Array<{ source: string }>;
+ };
+ return state.snapshotUnavailablePackages.some((entry) => entry.source === source);
+ });
+
+ 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 {
+ const nextStore = await import('../pi-package-store.js');
+ await nextStore.resolveManagedPiPackageResources({
+ ...(mode === 'snapshot'
+ ? { snapshotRoot: path.join(runtime.userData, 'inspection-limit-second-snapshot') }
+ : { startupTraceId: 'fedcba9876543210' }),
+ });
+ // 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.
+ 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();
+ await expect(nextStore.resolveManagedPiNativePackagePaths()).resolves.toEqual([root]);
+ await expect(nextStore.listPiPackages()).resolves.toMatchObject({
+ packages: [{ source, enabled: true, warning: 'inspection-limit' }],
+ });
+ } finally {
+ openSpy.mockRestore();
+ opendirSpy.mockRestore();
+ }
+ });
+
+ it('does not spread an inspection-stage failure to a healthy npm sibling on the shared root', async () => {
+ const npmRoot = path.join(runtime.userData, 'pi-package-home', 'npm');
+ const oversizedRoot = path.join(npmRoot, 'node_modules', 'inspection-oversized');
+ const healthyRoot = path.join(npmRoot, 'node_modules', 'inspection-healthy');
+ await fs.mkdir(path.join(healthyRoot, 'skills', 'healthy'), { recursive: true });
+ await fs.mkdir(oversizedRoot, { recursive: true });
+ const oversizedSource = 'npm:inspection-oversized';
+ const healthySource = 'npm:inspection-healthy';
+ await fs.writeFile(path.join(oversizedRoot, 'package.json'), JSON.stringify({
+ name: 'inspection-oversized',
+ version: '1.0.0',
+ pi: {
+ prompts: Array.from({ length: 257 }, (_, index) => `prompts/${index}.md`),
+ },
+ }));
+ await fs.writeFile(path.join(healthyRoot, 'package.json'), JSON.stringify({
+ name: 'inspection-healthy',
+ version: '1.0.0',
+ pi: { skills: ['./skills'] },
+ }));
+ await fs.writeFile(
+ path.join(healthyRoot, 'skills', 'healthy', 'SKILL.md'),
+ '# Healthy\n',
+ );
+ runtime.listOutput = [
+ 'User packages:',
+ ` ${oversizedSource}`,
+ ` ${oversizedRoot}`,
+ ` ${healthySource}`,
+ ` ${healthyRoot}`,
+ '',
+ ].join('\n');
+
+ const store = await import('../pi-package-store.js');
+ await store.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, 'inspection-shared-root-snapshot'),
+ });
+ await expect(store.listPiPackages()).resolves.toMatchObject({
+ packages: [
+ { source: oversizedSource, enabled: true, warning: 'inspection-limit' },
+ { source: healthySource, enabled: true },
+ ],
+ });
const state = JSON.parse(await fs.readFile(
path.join(runtime.userData, 'pi-package-home', 'cindy-package-state.json'),
'utf8',
@@@ -2777,10 -2229,10 +2815,10 @@@
disabledSources: string[];
approvedExtensionSources: string[];
approvedExtensionFingerprints: Record<string, string>;
- snapshotUnavailableRoots: Record<string, string>;
+ snapshotUnavailablePackages: unknown[];
};
expect(migrated).toEqual({
- version: 4,
+ version: 3,
disabledSources: ['npm:keep-disabled'],
approvedExtensionSources: [source],
approvedExtensionFingerprints: {
@@@ -2796,38 -2248,6 +2834,38 @@@
expect(installSpawn?.args).toContain('--no-approve');
});
+ it('drops the v3 root-only snapshot failure while migrating durable package state', async () => {
+ const { root, source } = await createSkillOnlyPackage('npm:v3-snapshot-migration');
+ const stateDir = path.join(runtime.userData, 'pi-package-home');
+ await fs.mkdir(stateDir, { recursive: true });
+ await fs.writeFile(
+ path.join(stateDir, 'cindy-package-state.json'),
+ JSON.stringify({
+ version: 3,
+ disabledSources: [],
+ approvedExtensionSources: [],
+ approvedExtensionFingerprints: {},
+ snapshotUnavailableRoots: {
+ [await fs.realpath(root)]: 'inspection-limit',
+ },
+ }),
+ );
+
+ const store = await import('../pi-package-store.js');
+ await store.mutatePiPackage({ action: 'set-enabled', source, enabled: false });
+
+ const migrated = JSON.parse(
+ await fs.readFile(path.join(stateDir, 'cindy-package-state.json'), 'utf8'),
+ ) as {
+ version: number;
+ disabledSources: string[];
+ snapshotUnavailablePackages: unknown[];
+ };
- expect(migrated.version).toBe(4);
++ expect(migrated.version).toBe(3);
+ expect(migrated.disabledSources).toEqual([source]);
+ expect(migrated.snapshotUnavailablePackages).toEqual([]);
+ });
+
it('clears a relative disable alias when the same local package is reinstalled by absolute path', async () => {
const relativeSource = './same-directory/relative-package';
const sibling = './same-directory/sibling-package';
diff --cc apps/desktop/src/main/maker-host/pi-package-store.ts
index 1f92270eae,58365ae2ca..1f96d4645f
--- a/apps/desktop/src/main/maker-host/pi-package-store.ts
+++ b/apps/desktop/src/main/maker-host/pi-package-store.ts
@@@ -84,7 -83,7 +84,8 @@@ const DEFAULT_SNAPSHOT_LIMITS: PiPackag
maxBytes: 128 * 1024 * 1024,
maxDurationMs: 15_000,
};
- const STATE_VERSION = 4;
++// Analysis metadata is additive: older Cindy instances must still read user preferences.
+ const STATE_VERSION = 3;
const CHANGE_TOKEN_POLL_MS = 250;
export type PiPackagesChangeOrigin = 'local' | 'external' | 'external-runtime';
const changeListeners = new Set<(origin: PiPackagesChangeOrigin) => void>();
@@@ -722,78 -582,31 +723,80 @@@ function parseApprovedExtensionFingerpr
return Object.fromEntries(entries) as Record<string, string>;
}
-function parseSnapshotUnavailableRoots(
+function parseSnapshotUnavailablePackages(
value: unknown,
-): Record<string, SnapshotUnavailableWarning> | undefined {
- if (value === undefined) return {};
- if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
- const entries = Object.entries(value);
+): PersistedSnapshotUnavailablePackage[] | undefined {
+ if (value === undefined) return [];
+ if (!Array.isArray(value)) return undefined;
+ const entries = value as Array<Partial<PersistedSnapshotUnavailablePackage>>;
if (
entries.length > MAX_INSPECTED_PACKAGES
- || !entries.every(([root, warning]) => (
- root.length > 0
- && root.length <= MAX_SOURCE_LENGTH
- && (warning === 'inspection-failed' || warning === 'inspection-limit')
+ || !entries.every((entry) => (
- typeof entry.source === 'string'
++ entry !== null
++ && typeof entry === 'object'
++ && typeof entry.source === 'string'
+ && entry.source.length > 0
+ && entry.source.length <= MAX_SOURCE_LENGTH
+ && typeof entry.installedRoot === 'string'
+ && entry.installedRoot.length > 0
+ && entry.installedRoot.length <= MAX_SOURCE_LENGTH
+ && typeof entry.snapshotRoot === 'string'
+ && entry.snapshotRoot.length > 0
+ && entry.snapshotRoot.length <= MAX_SOURCE_LENGTH
+ && 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 Object.fromEntries(
- entries.sort(([left], [right]) => left.localeCompare(right)),
- ) as Record<string, SnapshotUnavailableWarning>;
+ 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 applySharedSnapshotUnavailableRoots(
- roots: Readonly<Record<string, SnapshotUnavailableWarning>>,
+function isSnapshotUnavailableRetryDue(
+ entry: SnapshotUnavailablePackageProjection,
+): boolean {
+ return entry.retryAfterEpochMs !== undefined && Date.now() >= entry.retryAfterEpochMs;
+}
+
+function snapshotUnavailablePackageKey(
+ entry: SnapshotUnavailablePackageIdentity,
+): string {
+ return JSON.stringify([
+ entry.source,
+ path.resolve(entry.installedRoot),
+ entry.installationIdentity,
+ path.resolve(entry.snapshotRoot),
+ ]);
+}
+
+function applySharedSnapshotUnavailablePackages(
+ packages: readonly SnapshotUnavailablePackageProjection[],
): void {
- snapshotUnavailableRoots.clear();
- for (const [root, warning] of Object.entries(roots)) {
- snapshotUnavailableRoots.set(path.resolve(root), warning);
+ snapshotUnavailablePackages.clear();
+ for (const pkg of packages) {
+ if (isSnapshotUnavailableRetryDue(pkg)) continue;
+ snapshotUnavailablePackages.set(snapshotUnavailablePackageKey(pkg), pkg);
}
}
@@@ -813,15 -626,15 +816,15 @@@ async function readState(): Promise<PiP
const fingerprints = parseApprovedExtensionFingerprints(
parsed.approvedExtensionFingerprints,
);
- const unavailablePackages = parseSnapshotUnavailablePackages(parsed.snapshotUnavailablePackages);
- const unavailableRoots = parseSnapshotUnavailableRoots(parsed.snapshotUnavailableRoots);
++ // A damaged advisory cache must not make the disable ledger unreadable.
++ const unavailablePackages = parseSnapshotUnavailablePackages(parsed.snapshotUnavailablePackages) ?? [];
if (
-- parsed.version === STATE_VERSION
++ (parsed.version === STATE_VERSION || parsed.version === 4)
&& Array.isArray(parsed.disabledSources)
&& parsed.disabledSources.every((source) => typeof source === 'string')
&& Array.isArray(parsed.approvedExtensionSources)
&& parsed.approvedExtensionSources.every((source) => typeof source === 'string')
&& fingerprints
- && unavailablePackages
- && unavailableRoots
) {
const approvedExtensionSources = [...new Set(parsed.approvedExtensionSources)]
.filter((source) => Object.hasOwn(fingerprints, source));
@@@ -843,33 -656,17 +846,10 @@@
&& Array.isArray(parsed.disabledSources)
&& parsed.disabledSources.every((source) => typeof source === 'string')
) {
- const legacyFingerprints =
- parsed.version === 3
- ? parseApprovedExtensionFingerprints(parsed.approvedExtensionFingerprints)
- : undefined;
- const legacyApprovedSources =
- parsed.version === 3 &&
- Array.isArray(parsed.approvedExtensionSources) &&
- parsed.approvedExtensionSources.every((source) => typeof source === 'string') &&
- legacyFingerprints
- ? [...new Set(parsed.approvedExtensionSources)].filter((source) =>
- Object.hasOwn(legacyFingerprints, source),
- )
- : [];
- // v3 approvals already carry byte identity and remain valid. Its root-only
- // negative cache cannot prove source/install identity, so migration drops it.
- // v1/v2 approvals had no byte identity and stay fail closed as before.
- // Preserve explicit disables. Older approvals had no byte identity, so
- // they cannot authorize executable code under the v3 content boundary.
++ // Pre-v3 approvals lacked byte identity; preserve explicit disable preferences.
return {
ok: true,
-- state: {
-- version: STATE_VERSION,
-- disabledSources: [...new Set(parsed.disabledSources)],
- approvedExtensionSources: legacyApprovedSources,
- approvedExtensionFingerprints: Object.fromEntries(
- legacyApprovedSources.map((source) => [source, legacyFingerprints![source]!]),
- ),
- snapshotUnavailablePackages: [],
- approvedExtensionSources: [],
- approvedExtensionFingerprints: {},
- snapshotUnavailableRoots: {},
-- },
++ state: { ...emptyState(), disabledSources: [...new Set(parsed.disabledSources)] },
};
}
throw new Error('Pi extension state has an invalid structure');
@@@ -2056,27 -1757,20 +2036,26 @@@ async function persistedSnapshotLimitPr
}
}
-async function inspectAllPackagesUncached(): Promise<InspectedPackage[]> {
+async function inspectAllPackagesUncached(
+ options: {
- ignorePersistedSnapshotUnavailable?: boolean;
+ startupTiming?: PiPackageStartupTiming;
+ } = {},
+): Promise<InspectedPackage[]> {
const [listed, stateResult] = await Promise.all([
- runPiPackageListCommand(),
+ measurePiPackageStartupStage(
+ options.startupTiming,
+ 'package-list',
+ () => runPiPackageListCommand(),
+ ),
readState(),
]);
- // Snapshot failures are shared package-store state, not a property of one
- // Main process. Every fresh inspection replaces the local projection with
- // the atomically persisted view so packaged/dev peers agree after the
- // existing change-token invalidation.
const state = stateResult.ok ? stateResult.state : emptyState();
if (stateResult.ok) {
- applySharedSnapshotUnavailableRoots(state.snapshotUnavailableRoots);
+ applySharedSnapshotUnavailablePackages(state.snapshotUnavailablePackages);
}
+ if (options.startupTiming) options.startupTiming.packageCount = listed.length;
const startedAt = Date.now();
+ const inspectionStartedAt = Date.now();
const inspected: InspectedPackage[] = [];
const fingerprintCache = new Map<string, Promise<string>>();
const aggregateFingerprintBudget = createSnapshotBudgetCounters(DEFAULT_SNAPSHOT_LIMITS);
@@@ -2100,23 -1794,12 +2079,23 @@@
});
continue;
}
- const inspectedPackage = await inspectPackage(
- pkg,
- state,
- fingerprintCache,
- aggregateFingerprintBudget,
- );
+ const inspectedPackage =
- stateResult.ok && options.ignorePersistedSnapshotUnavailable !== true
++ stateResult.ok
+ ? ((await persistedSnapshotLimitProjection(pkg, state)) ??
+ (await inspectPackage(
+ pkg,
+ state,
+ fingerprintCache,
+ aggregateFingerprintBudget,
+ options.startupTiming,
+ )))
+ : await inspectPackage(
+ pkg,
+ state,
+ fingerprintCache,
+ aggregateFingerprintBudget,
+ options.startupTiming,
+ );
if (stateResult.ok) {
inspected.push(inspectedPackage);
} else {
@@@ -2158,11 -1834,11 +2137,11 @@@ function invalidateInspectionCache(): v
inspectionPromise = undefined;
}
--async function inspectAllPackages(): Promise<InspectedPackage[]> {
++async function inspectAllPackages(startupTiming?: PiPackageStartupTiming): Promise<InspectedPackage[]> {
if (inspectionCache && inspectionCache.expiresAt > Date.now()) return inspectionCache.value;
if (inspectionPromise) return inspectionPromise;
const generation = inspectionGeneration;
-- const pending = inspectAllPackagesUncached().then((value) => {
++ const pending = inspectAllPackagesUncached({ startupTiming }).then((value) => {
if (generation === inspectionGeneration) {
inspectionCache = { expiresAt: Date.now() + INSPECTION_CACHE_MS, value };
}
@@@ -2174,12 -1850,7 +2153,11 @@@
return pending;
}
-async function inspectAllPackagesFreshUnderMutationLock(): Promise<InspectedPackage[]> {
+async function inspectAllPackagesFreshUnderMutationLock(
+ options: {
- ignorePersistedSnapshotUnavailable?: boolean;
+ startupTiming?: PiPackageStartupTiming;
+ } = {},
+): Promise<InspectedPackage[]> {
// A local inspection that began before another process changed the shared
// package store must finish before its generation is retired. Starting the
// replacement under the cross-process mutation lock then re-reads both the
@@@ -2187,9 -1858,7 +2165,7 @@@
const staleInspection = inspectionPromise;
if (staleInspection) await staleInspection.catch(() => undefined);
invalidateInspectionCache();
- return options.ignorePersistedSnapshotUnavailable || options.startupTiming
- ? inspectAllPackagesUncached(options)
- : inspectAllPackages();
- return inspectAllPackages();
++ return inspectAllPackages(options.startupTiming);
}
async function projectNativePackageViews(
@@@ -2406,9 -2027,9 +2382,9 @@@ export async function resolveManagedPiP
try {
const resolveResources = async (forceFresh = false): Promise<PiManagedPackageResources> => {
const inspected = forceFresh
- ? await inspectAllPackagesFreshUnderMutationLock()
- : await inspectAllPackages();
- if (options) {
+ ? await inspectAllPackagesFreshUnderMutationLock({ startupTiming })
- : await inspectAllPackages();
++ : await inspectAllPackages(startupTiming);
+ if (snapshotRoot) {
const staleApprovals = inspected
.filter((pkg) => pkg.staleApproval)
.map((pkg) => pkg.rawSource);
@@@ -2423,25 -2044,7 +2399,26 @@@
promptTemplates: [...new Set(inspected.flatMap((pkg) => pkg.launch.promptTemplates))],
packageRoots: [...new Set(inspected.flatMap((pkg) => pkg.launch.packageRoots))],
};
- if (!options) return resources;
+ if (startupTiming) {
++ startupTiming.packageCount = inspected.length;
+ startupTiming.resourceCount = resources.extensions.length
+ + resources.skills.length
+ + resources.promptTemplates.length;
+ startupTiming.skippedPackageCount = inspected.filter((pkg) => (
+ pkg.view.warning === 'inspection-failed'
+ || pkg.view.warning === 'inspection-limit'
+ || Boolean(pkg.snapshotUnavailable)
+ )).length;
+ startupTiming.degraded = startupTiming.skippedPackageCount > 0;
+ }
+ if (!snapshotRoot) {
+ // Native Pi owns loading. Cache only advisory inspection limits here;
+ // startup timing must not reintroduce per-session package copies.
+ if (startupTiming && await persistSnapshotUnavailableProjection([], inspected)) {
+ await publishPiPackagesChanged({ invalidateCache: false });
+ }
+ return resources;
+ }
const approvalsByRoot = new Map<string, Array<{ source: string; fingerprint: string }>>();
for (const pkg of inspected) {
@@@ -2625,11 -2167,9 +2602,15 @@@
await publishPiPackagesChanged({ invalidateCache: false });
}
throw error;
+ } finally {
+ recordPiPackageStartupDuration(startupTiming, 'package-snapshot', snapshotStartedAt);
}
};
- if (snapshotRoot || startupTiming) return await enqueueMutation(() => resolveResources(true));
- if (options) return await enqueueMutation(() => resolveResources(true));
++ if (snapshotRoot || startupTiming) {
++ // Only an explicitly requested snapshot needs fresh byte verification.
++ // Startup diagnostics share the existing short cache and in-flight inspection.
++ return await enqueueMutation(() => resolveResources(Boolean(snapshotRoot)));
++ }
await mutationTail;
return await resolveResources();
} catch (error) {
diff --cc packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index 3f60fd124f,472da415c5..19a6521cb4
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@@ -5413,66 -5428,6 +5443,68 @@@ describe("Pi provider-aware model routi
await handle.close();
});
+ it("preserves the stable remote config home across a transport disconnect and reattach", async () => {
+ const remoteStub: import("../transport.js").PiTransport = {
+ writeLine: async () => {},
+ onLine: () => () => {},
+ onStderr: () => () => {},
+ onClose: () => () => {},
+ close: async () => {},
+ pid: 4321,
+ isClosed: () => false,
+ remoteBinaryPath: "/remote/pi",
+ killRemoteSession: async () => {},
+ };
+ const remoteRm = vi.fn(async () => {});
+ const capturedRemoteEnvs: Array<Record<string, string | undefined>> = [];
+ const base = byomDeps(async () => ({ providers: [], env: {} }));
+ const deps: AgentDeps = {
+ ...base,
+ runtimeConfig: {
+ ...base.runtimeConfig,
+ remoteEndpoint: "https://gateway.example.test",
+ },
+ resolveRemotePiBinaryPath: async () => "/remote/pi",
+ getRemotePiTransport: async (_hostId, opts) => {
+ capturedRemoteEnvs.push({ ...(opts.env ?? {}) });
+ return remoteStub;
+ },
+ getRemotePiFileOps: () => ({
+ mkdirp: async () => {},
+ writeFile: async () => {},
+ stat: async () => ({ isFile: true }),
+ rm: remoteRm,
+ listDir: async () => [],
++ readFile: async () => { throw new Error("Unexpected remote file read in empty directory fixture"); },
++ sha256File: async () => { throw new Error("Unexpected remote file hash in empty directory fixture"); },
+ }),
+ };
+
+ await new PiAgent(deps).startSession({
+ sessionId: "remote-disconnect-reattach",
+ workingDir: cwd,
+ model: "local-model",
+ remoteHostId: "remote-host",
+ });
+ const firstEnv = capturedRemoteEnvs[0]!;
+ const configHome = firstEnv.PI_CODING_AGENT_DIR!;
+
+ captured.onExit?.({ code: null, signal: null });
+ await Promise.resolve();
+ expect(remoteRm).not.toHaveBeenCalledWith(configHome, { recursive: true });
+
+ const reattached = await new PiAgent(deps).startSession({
+ sessionId: "remote-disconnect-reattach",
+ workingDir: cwd,
+ model: "local-model",
+ remoteHostId: "remote-host",
+ });
+ expect(capturedRemoteEnvs[1]).toEqual(firstEnv);
+ expect(capturedRemoteEnvs[1]?.PI_CODING_AGENT_DIR).toBe(configHome);
+ await reattached.close();
+ expect(remoteRm).not.toHaveBeenCalledWith(configHome, { recursive: true });
+ });
+
it("hashes the remote permission snapshot into spawn env so a later Full-access attach restarts", async () => {
const remoteStub: import("../transport.js").PiTransport = {
writeLine: async () => {},
diff --cc packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index a19a1c2f61,d208deefa3..2b0f31f33c
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@@ -2181,8 -2350,11 +2351,39 @@@ describe('PiAgent.startSession failure
// codex review P2:并发普通会话不得共写 agentHome/models.json —— 第二次写入会在首次写完
// 到 spawn 之间截断/覆盖 provider 快照。每 startSession 用隔离的 configHome
// (PI_CODING_AGENT_DIR = agentHome/run-tmp/<hex>)承载 models.json,close/退出时清理。
++ it('keeps staged ripgrep bytes private and removes them on close', async () => {
++ const managedRg = path.join(agentHome, 'managed-rg');
++ writeFileSync(managedRg, 'managed ripgrep fixture');
++ const agent = new PiAgent(buildDeps({
++ runtimeConfig: {
++ endpoint: 'http://127.0.0.1:9',
++ managedExecutablePaths: { ripgrep: managedRg },
++ },
++ }));
++ const handles = await Promise.all(['rg-one', 'rg-two'].map((sessionId) =>
++ agent.startSession({ sessionId, workingDir: cwd, model: 'm' })));
++ const copies = knobs.spawnedEnvs.map((env) => path.join(
++ env.PI_CODING_AGENT_DIR!, 'bin', process.platform === 'win32' ? 'rg.exe' : 'rg',
++ ));
++ try {
++ expect(copies).toHaveLength(2);
++ expect(copies[0]).not.toBe(copies[1]);
++ expect(readFileSync(copies[0], 'utf8')).toBe('managed ripgrep fixture');
++ writeFileSync(copies[0], 'runtime replacement');
++ expect(readFileSync(managedRg, 'utf8')).toBe('managed ripgrep fixture');
++ expect(readFileSync(copies[1], 'utf8')).toBe('managed ripgrep fixture');
++ } finally {
++ await Promise.all(handles.map((handle) => handle.close()));
++ }
++ expect(copies.some((copy) => existsSync(copy))).toBe(false);
++ expect(existsSync(managedRg)).toBe(true);
++ });
++
it('isolates each session config home under run-tmp and keeps concurrent sessions independent', async () => {
const { existsSync } = await import('node:fs');
+ const nativeHome = path.join(agentHome, 'native-user-home');
+ mkdirSync(nativeHome);
+ writeFileSync(path.join(nativeHome, 'AGENTS.md'), 'global rules v1');
const skillOne = path.join(cwd, '.pi', 'skills', 'one');
const skillTwo = path.join(cwd, '.agents', 'skills', 'two');
for (const skillPath of [skillOne, skillTwo]) {
@@@ -2383,383 -2564,9 +2595,430 @@@
// 上层随后仍可能调用 close() —— cleanup 幂等,不抛。
await handle.close();
});
+
+ it("registers ownership before package setup and cleans the config home when setup fails", async () => {
+ const { promises: fs } = await import("node:fs");
+ const originalWriteFile = fs.writeFile.bind(fs);
+ let configHome = "";
+ let ownerWasPresent = false;
+ const writeSpy = vi
+ .spyOn(fs, "writeFile")
+ .mockImplementation(async (target, ...args) => {
+ if (path.basename(String(target)) === "models.json") {
+ configHome = path.dirname(String(target));
+ ownerWasPresent = existsSync(
+ path.join(configHome, ".cindy-owner.json"),
+ );
+ throw new Error("models setup failed (mock)");
+ }
+ return originalWriteFile(
+ target,
+ ...(args as Parameters<typeof fs.writeFile> extends [
+ unknown,
+ ...infer Rest,
+ ]
+ ? Rest
+ : never),
+ );
+ });
+ try {
+ const agent = new PiAgent(buildDeps());
+ await expect(
+ agent.startSession({
+ sessionId: "setup-failure",
+ workingDir: cwd,
+ model: "m",
+ }),
+ ).rejects.toThrow("models setup failed (mock)");
+ expect(ownerWasPresent).toBe(true);
+ expect(configHome).not.toBe("");
+ await waitFor(() => !existsSync(configHome));
+ } finally {
+ writeSpy.mockRestore();
+ }
+ });
+
++ it('preserves a starting home while its published owner write is still completing', async () => {
++ const { promises: fs } = await import('node:fs');
++ const originalWriteFile = fs.writeFile.bind(fs);
++ const originalOpendir = fs.opendir.bind(fs);
++ let releaseWrite!: () => void;
++ const writeReleased = new Promise<void>((resolve) => { releaseWrite = resolve; });
++ let publishedHome = '';
++ let completedSweeps = 0;
++ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
++ await originalWriteFile(...args);
++ if (path.basename(String(args[0])) === '.cindy-owner.json' && !publishedHome) {
++ publishedHome = path.dirname(String(args[0]));
++ await writeReleased;
++ }
++ });
++ vi.spyOn(fs, 'opendir').mockImplementation(async (...args) => {
++ const directory = await originalOpendir(...args);
++ const iterate = directory[Symbol.asyncIterator].bind(directory);
++ directory[Symbol.asyncIterator] = async function* () {
++ try { yield* iterate(); } finally { completedSweeps += 1; }
++ return undefined;
++ };
++ return directory;
++ });
++ // Ensure the first scheduled sweep can open run-tmp before either startup.
++ mkdirSync(path.join(agentHome, 'run-tmp'), { recursive: true });
++ const agent = new PiAgent(buildDeps());
++ const starting = agent.startSession({ sessionId: 'publishing-owner', workingDir: cwd, model: 'm' });
++ let second: Awaited<typeof starting> | undefined;
++ try {
++ await waitFor(() => publishedHome !== '' && completedSweeps >= 1);
++ second = await agent.startSession({ sessionId: 'sweeping-owner', workingDir: cwd, model: 'm' });
++ await waitFor(() => completedSweeps >= 2);
++ expect(existsSync(path.join(publishedHome, '.cindy-owner.json'))).toBe(true);
++ } finally {
++ releaseWrite();
++ await (await starting).close();
++ await second?.close();
++ }
++ });
++
+ it('records process incarnation plus redacted session/runtime identity in the local owner marker', async () => {
+ const sessionId = 'owner-marker-session';
+ const handle = await new PiAgent(buildDeps()).startSession({
+ sessionId,
+ workingDir: cwd,
+ model: 'm',
+ });
+ const configHome = knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!;
+ try {
+ const owner = JSON.parse(
+ readFileSync(path.join(configHome, '.cindy-owner.json'), 'utf8'),
+ ) as Record<string, unknown>;
+ expect(owner).toMatchObject({
+ version: 2,
+ ownerPid: process.pid,
+ directoryName: path.basename(configHome),
+ runtimeId: path.basename(configHome),
+ sessionIdHash: createHash('sha256').update(sessionId).digest('hex'),
+ });
+ expect(owner.ownerStartTimeSec).toEqual(expect.any(Number));
+ expect(owner).not.toHaveProperty('sessionId');
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('correlates redacted MCP, spawn, RPC-ready, and first-model-request timings', async () => {
+ const info = vi.fn();
+ const timingLogger: Logger = {
+ ...noopLogger,
+ info,
+ child: () => timingLogger,
+ };
- const resolvePiManagedPackageResources = vi.fn(async () => ({
++ const resolvePiManagedPackageResources = vi.fn<NonNullable<AgentDeps['resolvePiManagedPackageResources']>>(async () => ({
+ extensions: [], skills: [], promptTemplates: [], packageRoots: [],
+ }));
+ const handle = await new PiAgent(buildDeps({
+ logger: timingLogger,
+ resolvePiManagedPackageResources,
+ })).startSession({
+ sessionId: 'timing-session-secret',
+ workingDir: cwd,
+ model: 'm',
+ });
+ try {
+ await handle.send({ type: 'user', content: 'timing-prompt-secret' });
+ const resolverOptions = resolvePiManagedPackageResources.mock.calls[0]?.[0] as
+ | { startupTraceId?: string }
+ | undefined;
+ expect(resolverOptions?.startupTraceId).toMatch(/^[a-f0-9]{16}$/);
+
+ const events = info.mock.calls
+ .filter(([message]) => message === 'pi startup stage')
+ .map(([, fields]) => fields as Record<string, unknown>);
+ expect(events.map((event) => event.stage)).toEqual([
+ 'mcp-ready',
+ 'pi-spawn',
+ 'rpc-ready',
+ 'first-model-request',
+ ]);
+ for (const event of events) {
+ expect(event).toMatchObject({
+ startupTraceId: resolverOptions?.startupTraceId,
+ stage: expect.any(String),
+ durationMs: expect.any(Number),
+ status: 'ok',
+ });
+ }
+ const serialized = JSON.stringify(events);
+ expect(serialized).not.toContain('timing-session-secret');
+ expect(serialized).not.toContain('timing-prompt-secret');
+ expect(serialized).not.toContain(cwd);
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('starts a new session while stale config-home cleanup is blocked and finishes the backlog later', async () => {
+ const { promises: fs } = await import('node:fs');
+ const originalRm = fs.rm.bind(fs);
+ const staleHomes = Array.from({ length: 10 }, (_, index) => {
+ const staleHome = path.join(agentHome, 'run-tmp', `stale-budget-${index}`);
+ mkdirSync(staleHome, { recursive: true });
+ writeFileSync(
+ path.join(staleHome, '.cindy-owner.json'),
+ `${JSON.stringify({
+ version: 1,
+ ownerPid: 2_147_483_647,
+ createdAt: 1,
+ directoryName: path.basename(staleHome),
+ })}\n`,
+ );
+ return staleHome;
+ });
+ const staleHomeKeys = new Set(staleHomes.map((home) => path.resolve(home)));
+ let announceRemovalStarted!: () => void;
+ const removalStarted = new Promise<void>((resolve) => { announceRemovalStarted = resolve; });
+ let releaseRemoval!: () => void;
+ const removalGate = new Promise<void>((resolve) => { releaseRemoval = resolve; });
+ let removalReleased = false;
+ let staleRemovalCount = 0;
+ let firstSweepYieldObservedAt: number | undefined;
+ const unblockRemoval = (): void => {
+ if (removalReleased) return;
+ removalReleased = true;
+ releaseRemoval();
+ };
+ const rmSpy = vi.spyOn(fs, 'rm').mockImplementation(async (target, options) => {
+ if (staleHomeKeys.has(path.resolve(String(target)))) {
+ staleRemovalCount += 1;
+ if (staleRemovalCount === 1) {
+ // Observe live progress when timers next get a turn. The sweep budget is
+ // over inspected entries, not removals: an active/markerless home may
+ // make this value lower than 8, but it must never exceed the budget.
+ setTimeout(() => { firstSweepYieldObservedAt = staleRemovalCount; }, 0);
+ }
+ announceRemovalStarted();
+ await removalGate;
+ rmSync(String(target), { recursive: true, force: true });
+ return;
+ }
+ return originalRm(target, options);
+ });
+ const startPromise = new PiAgent(buildDeps()).startSession({
+ sessionId: 'bounded-stale-sweep',
+ workingDir: cwd,
+ model: 'm',
+ });
+ let handle: Awaited<typeof startPromise> | undefined;
+ try {
+ await removalStarted;
+ await vi.waitFor(
+ () => expect(knobs.spawnedEnvs.some(
+ (env) => env.CINDY_PI_SESSION_ID === 'bounded-stale-sweep',
+ )).toBe(true),
+ { timeout: 500 },
+ );
+ unblockRemoval();
+ handle = await startPromise;
+ await waitFor(() => staleHomes.every((home) => !existsSync(home)));
+ await vi.waitFor(() => expect(firstSweepYieldObservedAt).toBeDefined());
+ expect(firstSweepYieldObservedAt).toBeGreaterThanOrEqual(1);
+ expect(firstSweepYieldObservedAt).toBeLessThanOrEqual(8);
+ } finally {
+ unblockRemoval();
+ handle ??= await startPromise;
+ rmSpy.mockRestore();
+ await handle.close();
+ await Promise.all(staleHomes.map((home) => originalRm(home, { recursive: true, force: true })));
+ }
+ });
+
+ it('reclaims a v2 local config home whose owner pid was recycled', async () => {
+ const runtimeId = 'a'.repeat(32);
+ const recycledHome = path.join(agentHome, 'run-tmp', runtimeId);
+ mkdirSync(recycledHome, { recursive: true });
+ writeFileSync(
+ path.join(recycledHome, '.cindy-owner.json'),
+ `${JSON.stringify({
+ version: 2,
+ ownerPid: process.pid,
+ ownerStartTimeSec: 1,
+ createdAt: 1,
+ directoryName: path.basename(recycledHome),
+ runtimeId,
+ sessionIdHash: 'b'.repeat(64),
+ })}\n`,
+ );
+
+ const handle = await new PiAgent(buildDeps()).startSession({
+ sessionId: 'after-pid-reuse',
+ workingDir: cwd,
+ model: 'm',
+ });
+ try {
+ await waitFor(() => !existsSync(recycledHome));
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('shares one process-start probe memo across config homes owned by the same process', async () => {
+ const ownerPid = process.ppid;
+ const ownerStartTimeSec = 1;
+ const ownerHomes = ['c'.repeat(32), 'd'.repeat(32)].map((runtimeId) => {
+ const ownerHome = path.join(agentHome, 'run-tmp', runtimeId);
+ mkdirSync(ownerHome, { recursive: true });
+ writeFileSync(
+ path.join(ownerHome, '.cindy-owner.json'),
+ `${JSON.stringify({
+ version: 2,
+ ownerPid,
+ ownerStartTimeSec,
+ createdAt: 1,
+ directoryName: runtimeId,
+ runtimeId,
+ sessionIdHash: 'e'.repeat(64),
+ })}\n`,
+ );
+ return ownerHome;
+ });
+ const probeMemos: unknown[] = [];
+ vi.spyOn(piSubagentRuns, 'isPiHostProcessInstanceAliveAsync')
+ .mockImplementation(async (identity, memo) => {
+ if (identity.pid === ownerPid) probeMemos.push(memo);
+ return true;
+ });
+
+ const handle = await new PiAgent(buildDeps()).startSession({
+ sessionId: 'shared-owner-probe-memo',
+ workingDir: cwd,
+ model: 'm',
+ });
+ try {
+ await vi.waitFor(() => expect(probeMemos).toHaveLength(ownerHomes.length));
+ // pi-subagent-runs separately locks that one shared memo means one
+ // PowerShell/ps start-time probe per owner pid and sweep.
+ expect(probeMemos[0]).toBeInstanceOf(Map);
+ expect(probeMemos[1]).toBe(probeMemos[0]);
+ for (const ownerHome of ownerHomes) expect(existsSync(ownerHome)).toBe(true);
+ } finally {
+ await handle.close();
+ }
+ });
+
- it('preserves markerless legacy homes even when the host process scan finds no live Pi', async () => {
++ it('preserves markerless legacy homes after the background sweep completes', async () => {
+ const legacyHome = path.join(agentHome, 'run-tmp', '0123456789abcdef');
+ mkdirSync(legacyHome, { recursive: true });
+ writeFileSync(path.join(legacyHome, 'models.json'), '{}\n');
-
- // Simulate the removed host hint so a future sweep cannot accidentally
- // reinstate markerless deletion based only on post-spawn process evidence.
- const deps = {
- ...buildDeps(),
- canReclaimLegacyPiConfigHomes: async () => true,
- };
- const handle = await new PiAgent(deps).startSession({
- sessionId: 'legacy-preserve-pre-spawn',
- workingDir: cwd,
- model: 'm',
++ const { promises: fs } = await import('node:fs');
++ const originalOpendir = fs.opendir.bind(fs);
++ let sweepFinished!: () => void;
++ const swept = new Promise<void>((resolve) => { sweepFinished = resolve; });
++ vi.spyOn(fs, 'opendir').mockImplementation(async (...args) => {
++ const directory = await originalOpendir(...args);
++ if (path.resolve(String(args[0])) !== path.resolve(agentHome, 'run-tmp')) return directory;
++ const iterate = directory[Symbol.asyncIterator].bind(directory);
++ directory[Symbol.asyncIterator] = async function* () {
++ try { yield* iterate(); } finally { sweepFinished(); }
++ return undefined;
++ };
++ return directory;
++ });
++ const handle = await new PiAgent(buildDeps()).startSession({
++ sessionId: 'legacy-preserve-pre-spawn', workingDir: cwd, model: 'm',
+ });
+ try {
- expect(existsSync(legacyHome)).toBe(true);
++ await swept;
++ expect(readFileSync(path.join(legacyHome, 'models.json'), 'utf8')).toBe('{}\n');
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it("reclaims failed cleanup without deleting same-process or other-live-process sessions", async () => {
+ const { promises: fs } = await import("node:fs");
+ const agent = new PiAgent(buildDeps());
+ const orphaned = await agent.startSession({
+ sessionId: "orphaned",
+ workingDir: cwd,
+ model: "m",
+ });
+ const active = await agent.startSession({
+ sessionId: "active",
+ workingDir: cwd,
+ model: "m",
+ });
+ const orphanedHome = knobs.spawnedEnvs.find(
+ (env) => env.CINDY_PI_SESSION_ID === "orphaned",
+ )!.PI_CODING_AGENT_DIR!;
+ const activeHome = knobs.spawnedEnvs.find(
+ (env) => env.CINDY_PI_SESSION_ID === "active",
+ )!.PI_CODING_AGENT_DIR!;
+ const liveOwnerHome = path.join(agentHome, "run-tmp", "live-owner-home");
+ const originalRm = fs.rm.bind(fs);
+ let orphanRemovalFailures = 3;
+ const rmSpy = vi
+ .spyOn(fs, "rm")
+ .mockImplementation(async (target, options) => {
+ if (
+ path.resolve(String(target)) === path.resolve(orphanedHome) &&
+ orphanRemovalFailures > 0
+ ) {
+ orphanRemovalFailures -= 1;
+ throw Object.assign(new Error("transient config-home lock"), {
+ code: "EPERM",
+ });
+ }
+ return originalRm(target, options);
+ });
+ try {
+ await orphaned.close();
+ await waitFor(() => orphanRemovalFailures === 0);
+ expect(existsSync(orphanedHome)).toBe(true);
+ expect(existsSync(path.join(activeHome, "models.json"))).toBe(true);
+
+ const deadOwnerHome = path.join(agentHome, "run-tmp", "dead-owner-home");
+ mkdirSync(deadOwnerHome, { recursive: true });
+ writeFileSync(
+ path.join(deadOwnerHome, ".cindy-owner.json"),
+ `${JSON.stringify({
+ version: 1,
+ ownerPid: 2_147_483_647,
+ createdAt: 1,
+ directoryName: path.basename(deadOwnerHome),
+ })}\n`,
+ );
+ expect(process.ppid).toBeGreaterThan(0);
+ mkdirSync(liveOwnerHome, { recursive: true });
+ writeFileSync(
+ path.join(liveOwnerHome, ".cindy-owner.json"),
+ `${JSON.stringify({
+ version: 1,
+ ownerPid: process.ppid,
+ createdAt: 1,
+ directoryName: path.basename(liveOwnerHome),
+ })}\n`,
+ );
+ const next = await agent.startSession({
+ sessionId: "next",
+ workingDir: cwd,
+ model: "m",
+ });
+ try {
+ await waitFor(() => !existsSync(orphanedHome) && !existsSync(deadOwnerHome));
+ expect(existsSync(path.join(activeHome, "models.json"))).toBe(true);
+ expect(existsSync(liveOwnerHome)).toBe(true);
+ } finally {
+ await next.close();
+ }
+ } finally {
+ rmSpy.mockRestore();
+ await active.close();
+ await originalRm(orphanedHome, { recursive: true, force: true });
+ await originalRm(liveOwnerHome, { recursive: true, force: true });
+ }
+ });
});
-/** 轮询等待条件成立(configHome cleanup 是 void fs.rm fire-and-forget,不阻塞 close)。 */
+/** 轮询等待条件成立(onExit 等同步回调里的 configHome cleanup 仍是 fire-and-forget)。 */
async function waitFor(cond: () => boolean, timeoutMs = 2000): Promise<void> {
const start = Date.now();
while (!cond()) {
diff --cc packages/maker-core/src/agents/pi/index.ts
index b51fd04df0,169a8be484..141159c10f
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@@ -23,8 -24,10 +24,10 @@@ import { snapshotDisabledSkillLaunch, c
import os from 'node:os';
import path from 'node:path';
--import { promises as fs } from 'node:fs';
++import { constants as fsConstants, promises as fs } from 'node:fs';
import { createHash, createHmac, randomBytes } from 'node:crypto';
+ import { piSupportedEfforts } from '@cindy/model-providers/pi-thinking-levels';
+ import { readPiGlobalContext } from './global-context.js';
/**
* 轮 40-w4-t5 CRITICAL:远端 agentHome 是 POSIX 路径($HOME/... 或展开后的
@@@ -487,298 -505,11 +508,299 @@@ async function stageManagedRipgrep(conf
const binDir = joinRemotePosixPath(configHome, 'bin');
const targetPath = path.join(binDir, process.platform === 'win32' ? 'rg.exe' : 'rg');
await fs.mkdir(binDir, { recursive: true });
-- await fs.copyFile(sourcePath, targetPath);
++ // CoW clones keep private file identity; unsupported filesystems fall back to copying.
++ // A hard link would let one runtime overwrite the managed binary and its siblings.
++ await fs.copyFile(sourcePath, targetPath, fsConstants.COPYFILE_FICLONE);
if (process.platform !== 'win32') await fs.chmod(targetPath, 0o755);
return targetPath;
}
+const LOCAL_CONFIG_HOME_OWNER_FILE = '.cindy-owner.json';
+const LOCAL_CONFIG_HOME_OWNER_VERSION = 2;
+const LOCAL_CONFIG_HOME_REMOVE_RETRY_DELAYS_MS = [0, 25, 100] as const;
+/** One background turn may inspect only this many directory entries. */
+const LOCAL_CONFIG_HOME_SWEEP_ENTRY_BUDGET = 8;
+/** Stop a round after the current async operation once this soft budget expires. */
+const LOCAL_CONFIG_HOME_SWEEP_TIME_BUDGET_MS = 250;
+const LOCAL_CONFIG_HOME_RUNTIME_ID_RE = /^[a-f0-9]{32}$/;
+const SHA256_HEX_RE = /^[a-f0-9]{64}$/;
+const activeLocalConfigHomes = new Set<string>();
+const activeLocalConfigHomeSweeps = new Set<string>();
+
+/** Durable proof used only to decide whether a local per-session config home is reclaimable. */
+interface LocalConfigHomeOwnerV1 {
+ version: 1;
+ ownerPid: number;
+ createdAt: number;
+ directoryName: string;
+}
+
+interface LocalConfigHomeOwnerV2 {
+ version: typeof LOCAL_CONFIG_HOME_OWNER_VERSION;
+ ownerPid: number;
+ ownerStartTimeSec: number;
+ createdAt: number;
+ directoryName: string;
+ runtimeId: string;
+ sessionIdHash: string;
+}
+
+type LocalConfigHomeOwner = LocalConfigHomeOwnerV1 | LocalConfigHomeOwnerV2;
+
+/** Minimal logging interface required by local config-home reclamation policy. */
+interface ConfigHomeCleanupLogger {
+ debug(message: string, fields?: Record<string, unknown>): void;
+}
+
+type PiStartupStage = 'mcp-ready' | 'pi-spawn' | 'rpc-ready' | 'first-model-request';
+
+function logPiStartupStage(
+ logger: AgentDeps['logger'],
+ startupTraceId: string,
+ stage: PiStartupStage,
+ startedAt: number,
+ status: 'ok' | 'degraded' | 'skipped',
+ counts: Record<string, number> = {},
+): void {
+ logger.info('pi startup stage', {
+ startupTraceId,
+ stage,
+ durationMs: Math.max(0, Date.now() - startedAt),
+ status,
+ ...counts,
+ });
+}
+
+function localConfigHomeKey(configHome: string): string {
+ const resolved = path.resolve(configHome);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+}
+
+async function registerLocalConfigHome(
+ configHome: string,
+ sessionId: string,
+ runtimeId: string,
+): Promise<void> {
+ const normalized = path.resolve(configHome);
+ if (path.basename(normalized) !== runtimeId || !LOCAL_CONFIG_HOME_RUNTIME_ID_RE.test(runtimeId)) {
+ throw new Error('pi: invalid local config-home runtime identity');
+ }
+ const owner: LocalConfigHomeOwnerV2 = {
+ version: LOCAL_CONFIG_HOME_OWNER_VERSION,
+ ownerPid: process.pid,
+ ownerStartTimeSec: piHostProcessStartTimeSec(),
+ createdAt: Date.now(),
+ directoryName: path.basename(normalized),
+ runtimeId,
+ sessionIdHash: createHash('sha256').update(sessionId).digest('hex'),
+ };
- await fs.writeFile(
- path.join(normalized, LOCAL_CONFIG_HOME_OWNER_FILE),
- `${JSON.stringify(owner)}\n`,
- { encoding: 'utf8', mode: 0o600, flag: 'wx' },
- );
++ // Publish local liveness before the marker becomes visible to another sweep.
+ activeLocalConfigHomes.add(localConfigHomeKey(normalized));
++ try {
++ await fs.writeFile(
++ path.join(normalized, LOCAL_CONFIG_HOME_OWNER_FILE),
++ `${JSON.stringify(owner)}\n`,
++ { encoding: 'utf8', mode: 0o600, flag: 'wx' },
++ );
++ } catch (error) {
++ activeLocalConfigHomes.delete(localConfigHomeKey(normalized));
++ throw error;
++ }
+}
+
+function unregisterLocalConfigHome(configHome: string): void {
+ activeLocalConfigHomes.delete(localConfigHomeKey(configHome));
+}
+
+async function readLocalConfigHomeOwner(configHome: string): Promise<LocalConfigHomeOwner | null> {
+ const markerPath = path.join(configHome, LOCAL_CONFIG_HOME_OWNER_FILE);
+ try {
+ const markerStat = await fs.lstat(markerPath);
+ if (!markerStat.isFile() || markerStat.size > 1024) return null;
+ const parsed = JSON.parse(await fs.readFile(markerPath, 'utf8')) as Record<string, unknown>;
+ if (
+ !Number.isSafeInteger(parsed.ownerPid)
+ || (parsed.ownerPid as number) <= 0
+ || !Number.isSafeInteger(parsed.createdAt)
+ || (parsed.createdAt as number) <= 0
+ || parsed.directoryName !== path.basename(configHome)
+ ) return null;
+ if (parsed.version === 1) {
+ return {
+ version: 1,
+ ownerPid: parsed.ownerPid as number,
+ createdAt: parsed.createdAt as number,
+ directoryName: parsed.directoryName,
+ };
+ }
+ if (
+ parsed.version !== LOCAL_CONFIG_HOME_OWNER_VERSION
+ || !Number.isSafeInteger(parsed.ownerStartTimeSec)
+ || (parsed.ownerStartTimeSec as number) <= 0
+ || typeof parsed.runtimeId !== 'string'
+ || parsed.runtimeId !== parsed.directoryName
+ || !LOCAL_CONFIG_HOME_RUNTIME_ID_RE.test(parsed.runtimeId)
+ || typeof parsed.sessionIdHash !== 'string'
+ || !SHA256_HEX_RE.test(parsed.sessionIdHash)
+ ) return null;
+ return {
+ version: LOCAL_CONFIG_HOME_OWNER_VERSION,
+ ownerPid: parsed.ownerPid as number,
+ ownerStartTimeSec: parsed.ownerStartTimeSec as number,
+ createdAt: parsed.createdAt as number,
+ directoryName: parsed.directoryName,
+ runtimeId: parsed.runtimeId,
+ sessionIdHash: parsed.sessionIdHash,
+ };
+ } catch {
+ return null;
+ }
+}
+
+function isLocalProcessAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
+ }
+}
+
+async function localConfigHomeOwnerIsActive(
+ owner: LocalConfigHomeOwner,
+ configHome: string,
+ startTimeMemo?: ProcessStartTimeMemo,
+): Promise<boolean> {
+ if (owner.version === 1) {
+ return owner.ownerPid === process.pid
+ ? activeLocalConfigHomes.has(localConfigHomeKey(configHome))
+ : isLocalProcessAlive(owner.ownerPid);
+ }
+ if (!await isPiHostProcessInstanceAliveAsync({
+ pid: owner.ownerPid,
+ startTimeSec: owner.ownerStartTimeSec,
+ }, startTimeMemo)) return false;
+ return owner.ownerPid !== process.pid
+ || activeLocalConfigHomes.has(localConfigHomeKey(configHome));
+}
+
+function sameLocalConfigHomeOwner(
+ left: LocalConfigHomeOwner,
+ right: LocalConfigHomeOwner,
+): boolean {
+ if (left.version !== right.version) return false;
+ if (
+ left.ownerPid !== right.ownerPid
+ || left.createdAt !== right.createdAt
+ || left.directoryName !== right.directoryName
+ ) return false;
+ return left.version === 1 || (
+ right.version === LOCAL_CONFIG_HOME_OWNER_VERSION
+ && left.ownerStartTimeSec === right.ownerStartTimeSec
+ && left.runtimeId === right.runtimeId
+ && left.sessionIdHash === right.sessionIdHash
+ );
+}
+
+async function removeLocalConfigHomeWithRetry(
+ configHome: string,
+): Promise<{ removed: true } | { removed: false; error: unknown }> {
+ let lastError: unknown = new Error('pi configHome cleanup failed');
+ for (const delayMs of LOCAL_CONFIG_HOME_REMOVE_RETRY_DELAYS_MS) {
+ if (delayMs > 0) {
+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
+ }
+ try {
+ await fs.rm(configHome, { recursive: true, force: true });
+ return { removed: true };
+ } catch (error) {
+ lastError = error;
+ }
+ }
+ return { removed: false, error: lastError };
+}
+
+async function sweepStaleLocalConfigHomes(
+ agentHome: string,
+ logger: ConfigHomeCleanupLogger,
+): Promise<void> {
+ const runTmp = path.resolve(agentHome, 'run-tmp');
+ let entries;
+ try {
- entries = await fs.readdir(runTmp, { withFileTypes: true });
++ entries = await fs.opendir(runTmp, { bufferSize: LOCAL_CONFIG_HOME_SWEEP_ENTRY_BUDGET });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ logger.debug('pi configHome orphan scan failed (non-fatal)', {
+ message: error instanceof Error ? error.message : String(error),
+ });
+ return;
+ }
- let offset = 0;
- while (offset < entries.length) {
- if (offset > 0) {
- // A large backlog is split into separate event-loop turns. This bounds
- // each reclaim round and lets startup, IPC, and rendering work proceed.
++ let ownerStartTimeMemo: ProcessStartTimeMemo = new Map();
++ let roundStartedAt = Date.now();
++ let inspected = 0;
++ // Stream the directory: the backlog itself must not become one unbounded allocation.
++ for await (const entry of entries) {
++ if (inspected >= LOCAL_CONFIG_HOME_SWEEP_ENTRY_BUDGET
++ || (inspected > 0 && Date.now() - roundStartedAt >= LOCAL_CONFIG_HOME_SWEEP_TIME_BUDGET_MS)) {
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, 0);
+ timer.unref();
+ });
++ ownerStartTimeMemo = new Map();
++ roundStartedAt = Date.now();
++ inspected = 0;
+ }
- // Re-probe every owner incarnation in every round. Carrying this memo across
- // the yield could hide a pid that died and was recycled between rounds.
- const ownerStartTimeMemo: ProcessStartTimeMemo = new Map();
- const roundStartedAt = Date.now();
- let inspected = 0;
- while (offset < entries.length && inspected < LOCAL_CONFIG_HOME_SWEEP_ENTRY_BUDGET) {
- if (
- inspected > 0
- && Date.now() - roundStartedAt >= LOCAL_CONFIG_HOME_SWEEP_TIME_BUDGET_MS
- ) break;
- const entry = entries[offset++]!;
- inspected += 1;
- if (!entry.isDirectory()) continue;
- const candidate = path.resolve(runTmp, entry.name);
- if (path.dirname(candidate) !== runTmp) continue;
- const owner = await readLocalConfigHomeOwner(candidate);
- // Markerless homes may belong to an older Cindy instance between directory
- // creation and Pi spawn. No process snapshot can prove them reclaimable.
- if (!owner) continue;
- if (await localConfigHomeOwnerIsActive(owner, candidate, ownerStartTimeMemo)) continue;
-
- // Re-read immediately before deletion. A directory whose marker changed or
- // whose owner became active is no longer the orphan we proved above.
- const currentOwner = await readLocalConfigHomeOwner(candidate);
- if (
- !currentOwner
- || !sameLocalConfigHomeOwner(currentOwner, owner)
- ) continue;
- if (await localConfigHomeOwnerIsActive(currentOwner, candidate, ownerStartTimeMemo)) continue;
-
- const outcome = await removeLocalConfigHomeWithRetry(candidate);
- if (!outcome.removed) {
- logger.debug('pi configHome orphan cleanup failed (retried next startSession)', {
- configHomeId: entry.name,
- message: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
- });
- }
++ inspected += 1;
++ if (!entry.isDirectory()) continue;
++ const candidate = path.resolve(runTmp, entry.name);
++ if (path.dirname(candidate) !== runTmp) continue;
++ const owner = await readLocalConfigHomeOwner(candidate);
++ // Markerless homes may belong to an older Cindy instance between directory
++ // creation and Pi spawn. No process snapshot can prove them reclaimable.
++ if (!owner) continue;
++ if (await localConfigHomeOwnerIsActive(owner, candidate, ownerStartTimeMemo)) continue;
++
++ // Re-read immediately before deletion. A directory whose marker changed or
++ // whose owner became active is no longer the orphan we proved above.
++ const currentOwner = await readLocalConfigHomeOwner(candidate);
++ if (
++ !currentOwner
++ || !sameLocalConfigHomeOwner(currentOwner, owner)
++ ) continue;
++ if (await localConfigHomeOwnerIsActive(currentOwner, candidate, ownerStartTimeMemo)) continue;
++
++ const outcome = await removeLocalConfigHomeWithRetry(candidate);
++ if (!outcome.removed) {
++ logger.debug('pi configHome orphan cleanup failed (retried next startSession)', {
++ configHomeId: entry.name,
++ message: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
++ });
+ }
+ }
+}
+
+/** Coalesce startup-triggered sweeps without putting reclamation on the startup critical path. */
+function scheduleStaleLocalConfigHomeSweep(
+ agentHome: string,
+ logger: ConfigHomeCleanupLogger,
+): void {
+ const sweepKey = localConfigHomeKey(path.resolve(agentHome, 'run-tmp'));
+ if (activeLocalConfigHomeSweeps.has(sweepKey)) return;
+ activeLocalConfigHomeSweeps.add(sweepKey);
+ const timer = setTimeout(() => {
+ void sweepStaleLocalConfigHomes(agentHome, logger)
+ .catch((error) => {
+ logger.debug('pi configHome orphan scan failed (non-fatal)', {
+ message: error instanceof Error ? error.message : String(error),
+ });
+ })
+ .finally(() => {
+ activeLocalConfigHomeSweeps.delete(sweepKey);
+ });
+ }, 0);
+ timer.unref();
+}
+
/** cindy Effort → pi thinking level(pi 无 ultra)。思考开关走 setThinkingEnabled / thinkingEnabled。 */
function effortToPiThinkingLevel(effort: Effort): string {
return effort === 'ultra' ? 'max' : effort;
@@@ -2771,58 -2513,45 +2816,67 @@@ export class PiAgent extends BaseAgent
// 远端再叠 models.json+settings.json hash:startSession 在 pi/ensure 之前就会写
// 这两份快照。若只按 sessionId 分目录, 另一实例改路由或 retry 策略会先覆盖
// 仍在跑的旧 Pi / 子代理热读快照。
+ const localConfigHomeRuntimeId = remote ? undefined : randomBytes(16).toString('hex');
+ // Bot contexts remain profile-only. SSH tasks use the remote user's rules,
+ // never the controlling desktop's personal instructions.
+ const globalContextFiles = opts.botRuntimeProfile ? [] : await readPiGlobalContext(
+ this.deps.resolvePiGlobalContextHome?.(opts.remoteHostId),
+ fileOps,
+ );
+ const globalContextHash = globalContextFiles.length > 0
+ ? createHash('sha256').update(JSON.stringify(globalContextFiles)).digest('hex').slice(0, 16)
+ : '';
let configHome = remote
? joinRemotePosixPath(agentHome, 'run-tmp', stableSessionPathSegment(opts.sessionId))
- : joinRemotePosixPath(agentHome, 'run-tmp', randomBytes(8).toString('hex'));
+ : joinRemotePosixPath(agentHome, 'run-tmp', localConfigHomeRuntimeId!);
let configHomeCleaned = false;
- // 清理失败(SSH 断链时 fileOps.rm 抛错)不置标志 —— 下次会话的 startSession
- // 会主动清陈旧 configHome(见下),且不因「一次失败永久跳过」累积泄漏
- // (R4-2 竞态 1/6)。
- const cleanupConfigHome = (): void => {
- if (configHomeCleaned) return;
- void rmPath(configHome, { recursive: true }).then(
- () => {
- configHomeCleaned = true;
- },
- // 失败不置标志(下次 startSession 清陈旧目录兜底), 但必须留日志——
- // 否则远端 SSH fs 卡死等根因不可见(R7 审计 L-3)。
- (err) => {
- this.deps.logger.debug('pi configHome cleanup failed (retried next startSession)', {
- configHome,
- message: err instanceof Error ? err.message : String(err),
- });
- },
- );
+ let configHomeCleanupPromise: Promise<void> | undefined;
+ const cleanupConfigHome = (): Promise<void> => {
+ if (configHomeCleaned) return Promise.resolve();
+ if (configHomeCleanupPromise) return configHomeCleanupPromise;
+ if (!remote) unregisterLocalConfigHome(configHome);
+ const pending = (async () => {
+ if (remote) {
+ await rmPath(configHome, { recursive: true }, true);
+ } else {
+ const outcome = await removeLocalConfigHomeWithRetry(configHome);
+ if (!outcome.removed) throw outcome.error;
+ }
+ configHomeCleaned = true;
+ })().catch((err) => {
+ // Keep the owner marker and cleaned=false. A later lifecycle callback
+ // retries directly; the next local start also reclaims this directory
+ // after proving that its owner/session is no longer active.
+ this.deps.logger.debug('pi configHome cleanup failed (retried next startSession)', {
+ configHomeId: remote ? path.posix.basename(configHome) : path.basename(configHome),
+ message: err instanceof Error ? err.message : String(err),
+ });
+ }).finally(() => {
+ if (configHomeCleanupPromise === pending) configHomeCleanupPromise = undefined;
+ });
+ configHomeCleanupPromise = pending;
+ return pending;
};
- // 轮 40-w4-t4 CRITICAL:不再在新会话启动时清 run-tmp 其它目录 —— 远端
- // 并发会话 A 的 configHome 会被 B 的启动清理删除(无 owner/lease 校验),
- // 破坏 A 的 bridge extension/models.json 运行期快照。清理只绑定到
- // 本会话自己的 close/失败(cleanupConfigHome);run-tmp 残留(断链时清理
- // 失败的孤儿)由本会话 close 路径的低频清理覆盖, 不牺牲活跃会话。
- // 注:断链残留的孤儿 configHome 会累积 —— 但删错活跃会话是毁任务,
- // 宁可残留(可由用户手动清或未来加 lease 机制), 不误删。
+ // Until a handle owns the lifecycle, any setup rejection must remove this
+ // private home. An unconfirmed process close transfers cleanup to the
+ // session-keyed quarantine instead, because its Pi process may still read it.
+ let configHomeLifecycleTransferred = false;
+ let configHomeCleanupDeferredToQuarantine = false;
+ let localConfigHomeCreated = false;
+ try {
+ if (!remote) {
+ await fs.mkdir(path.dirname(configHome), { recursive: true, mode: 0o700 });
+ await fs.mkdir(configHome, { mode: 0o700 });
+ localConfigHomeCreated = true;
+ await registerLocalConfigHome(
+ configHome,
+ opts.sessionId ?? '<anonymous>',
+ localConfigHomeRuntimeId!,
+ );
+ }
+ // Local run-tmp sweeping is owner-aware: a live pid, or a configHome still
+ // registered by this process, is never removed. Remote daemon homes keep
+ // their existing stable identity and are not swept by local filesystem logic.
if (remote) {
const preview = await this.writeModelsJson(configHome, nativeProviders, retainedRuntimeModel, authProviderId, {
remote,
@@@ -3189,11 -2931,15 +3256,17 @@@
// Phase 1 不桥 orca/memory/ghost)。外部 HTTP MCP 直连不受影响。
const remoteSkipMcpBridge = Boolean(
opts.remoteHostId && this.deps.remotePiSkipMcpBridge?.(opts.remoteHostId));
+ const mcpReadyStartedAt = Date.now();
+ let mcpReadyStatus: 'ok' | 'degraded' | 'skipped' = 'skipped';
if (!reviewMode && !remoteSkipMcpBridge && this.deps.preparePiExtraSpawnConfig) {
try {
- const extra = await this.deps.preparePiExtraSpawnConfig(this.deps.mcpProviders ?? [], {
+ const extra = await this.deps.preparePiExtraSpawnConfig(
+ // The Desktop bridge is generation-cached, so it must be built from the
+ // full provider superset. Per-Bot narrowing happens on the returned
+ // per-session descriptor; otherwise whichever session starts first
+ // accidentally defines every later Pi session's tool surface.
+ this.deps.mcpProviders ?? [],
+ {
sessionId: opts.sessionId,
...(opts.sessionInstanceId ? { sessionInstanceId: opts.sessionInstanceId } : {}),
workingDir: opts.workingDir,
@@@ -4635,9 -4455,10 +4792,12 @@@
return proxyLeaseInitialInspection;
};
let durableSpawnEnv: NodeJS.ProcessEnv = {};
+ let piSpawnStartedAt: number | undefined;
+ let piSpawnLogged = false;
try {
+ for (const file of globalContextFiles) {
+ await writeFile(joinRemotePosixPath(configHome, file.name), file.content);
+ }
// 远端不 stage 本地 rg(本机二进制远端无意义)—— 远端走 PATH 上的 rg(远端 POSIX
// 系统常见),与 CC/Codex 远端一致(不注入受管工具路径)。
const managedRipgrepPath = remote
@@@ -5401,30 -5218,31 +5570,32 @@@
try {
await proc.close();
} catch (error) {
- closeError = error;
+ if (!remote) configHomeCleanupDeferredToQuarantine = true;
+ let confirmStopped!: () => void;
+ const whenStopped = new Promise<void>((resolve) => { confirmStopped = resolve; });
+ cleanupPending = new AgentStartupCleanupPendingError(
+ `pi startup failed and process cleanup remains unconfirmed: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: err, whenStopped },
+ );
this.failedStartupCleanups.set(startupCleanupKey, {
proc,
promise: null,
+ confirmStopped,
...(!remote
? { cleanupLocal: () => {
- cleanupConfigHome();
+ void cleanupConfigHome();
cleanupRuntimeFiles();
} }
: {}),
});
}
- if (!remote && !closeError) {
+ if (!remote && !cleanupPending) {
- cleanupConfigHome();
+ await cleanupConfigHome();
cleanupRuntimeFiles();
}
- if (closeError) {
- throw new Error(
- `pi startup failed and process cleanup remains unconfirmed: ${closeError instanceof Error ? closeError.message : String(closeError)}`,
- { cause: err },
- );
- }
- throw err;
+ if (cleanupPending) throw cleanupPending;
+ // Only a successful close proves exit; do not infer it from the startup error.
+ throw new AgentStartupStoppedError(err);
}
const launchSubagentRunner = (request: PiSubagentRunnerLaunchRequest): Promise<void> =>
diff --cc packages/maker-core/src/agents/pi/pi-subagent-runs.ts
index 5dccf4b2d5,5e3f88e94b..061c4b761a
--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts
@@@ -405,7 -405,7 +405,7 @@@ function parseLaunchFence(value: unknow
*/
function fenceMatchesOwnIncarnation(fence: PiSubagentLaunchFence): boolean {
if (fence.hostStartTimeSec === undefined) return true;
-- return Math.abs(ownProcessStartTimeSec() - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
++ return Math.abs(piHostProcessStartTimeSec() - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
}
/**
@@@ -516,7 -516,7 +516,7 @@@ export async function acquirePiSubagent
await writeAtomicJson(file, {
version: 1,
hostPid: process.pid,
-- hostStartTimeSec: ownProcessStartTimeSec(),
++ hostStartTimeSec: piHostProcessStartTimeSec(),
leaseId,
createdAt: Date.now(),
} satisfies PiSubagentLaunchFence);
@@@ -677,7 -677,7 +677,7 @@@ export async function clearStalePiSubag
if (fence && isProcessAlive(fence.hostPid) !== false) {
if (fence.hostStartTimeSec === undefined) return;
const startTimeSec = fence.hostPid === process.pid
-- ? ownProcessStartTimeSec()
++ ? piHostProcessStartTimeSec()
: probeProcessStartTimeSec(fence.hostPid, Date.now());
if (startTimeSec === null) return;
if (Math.abs(startTimeSec - fence.hostStartTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC) return;
@@@ -1018,18 -1018,13 +1018,13 @@@ export function piSubagentRuntimeOwnerI
// a live foreign owner reads as an orphan the moment the gap exceeds the
// tolerance. A legacy id has no start time, so liveness stays conservative.
return hostPid === process.pid
-- ? `${hostPid}.${ownProcessStartTimeSec()}:${scopeId}`
++ ? `${hostPid}.${piHostProcessStartTimeSec()}:${scopeId}`
: `${hostPid}:${scopeId}`;
}
--/** Wall-clock second this process started, in the form the owner id records. */
--function ownProcessStartTimeSec(): number {
- return OWN_PROCESS_START_TIME_SEC;
- }
-
- /** Process-incarnation stamp shared by other host-owned Pi runtime records. */
++/** Wall-clock start second shared by host-owned Pi runtime records. */
+export function piHostProcessStartTimeSec(): number {
- return ownProcessStartTimeSec();
+ return OWN_PROCESS_START_TIME_SEC;
}
export interface PiSubagentOwnerIdentity {
@@@ -1310,34 -1258,12 +1305,26 @@@ function isOwnerInstanceAlive
if (isProcessAlive(identity.pid) === false) return false;
if (identity.startTimeSec === undefined) return true;
const startTimeSec = identity.pid === process.pid
-- ? ownProcessStartTimeSec()
++ ? piHostProcessStartTimeSec()
: readProcessStartTimeSec(identity.pid, memo);
if (startTimeSec === null) return true;
return Math.abs(startTimeSec - identity.startTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
}
- /** Conservative liveness check for a Pi host process incarnation. */
- export function isPiHostProcessInstanceAlive(
- identity: PiSubagentOwnerIdentity,
- startTimeMemo?: ProcessStartTimeMemo,
- ): boolean {
- return isOwnerInstanceAlive(identity, startTimeMemo);
- }
-
+/** Non-blocking incarnation check for background config-home reclamation. */
+export async function isPiHostProcessInstanceAliveAsync(
+ identity: PiSubagentOwnerIdentity,
+ startTimeMemo?: ProcessStartTimeMemo,
+): Promise<boolean> {
+ if (isProcessAlive(identity.pid) === false) return false;
+ if (identity.startTimeSec === undefined) return true;
+ const startTimeSec = identity.pid === process.pid
- ? ownProcessStartTimeSec()
++ ? piHostProcessStartTimeSec()
+ : await readProcessStartTimeSecAsync(identity.pid, startTimeMemo);
+ if (startTimeSec === null) return true;
+ return Math.abs(startTimeSec - identity.startTimeSec) <= OWNER_START_TIME_TOLERANCE_SEC;
+}
+
function isProcessAlive(pid: number | undefined): boolean | null {
if (!Number.isSafeInteger(pid) || (pid ?? 0) <= 0) return null;
try {
@@@ -2313,7 -2239,7 +2300,7 @@@ async function acquirePiSubagentResumeC
version: 1,
...(runtimeOwnerId ? { runtimeOwnerId } : {}),
hostPid,
-- hostStartTimeSec: ownProcessStartTimeSec(),
++ hostStartTimeSec: piHostProcessStartTimeSec(),
claimedAt: Date.now(),
})}\n`;
const release = async (): Promise<void> => {
diff --cc packages/maker-core/src/maker.shutdown.test.ts
index 0bafef7f7d,e44e11d2db..0f94513cee
--- a/packages/maker-core/src/maker.shutdown.test.ts
+++ b/packages/maker-core/src/maker.shutdown.test.ts
@@@ -86,7 -86,75 +86,75 @@@ function createAgent(handle: AgentSessi
} as unknown as BaseAgent;
}
-function createDeferred<T = void>(): { promise: Promise<T>; resolve: (value?: T | PromiseLike<T>) => void } {
- let resolve!: (value?: T | PromiseLike<T>) => void;
++function createDeferred<T = void>(): { promise: Promise<T>; resolve: (value: T | PromiseLike<T>) => void } {
++ let resolve!: (value: T | PromiseLike<T>) => void;
+ const promise = new Promise<T>((res) => { resolve = res; });
+ return { promise, resolve };
+ }
+
describe('Maker.shutdown', () => {
+ it('waits for deferred startup cleanup hooks before resolving', async () => {
+ const stopped = createDeferred();
+ const cleanupGate = createDeferred();
+ let cleanupEntered = false;
+ const pending = new AgentStartupCleanupPendingError('startup cleanup pending', {
+ cause: new Error('adapter startup failed'),
+ whenStopped: stopped.promise,
+ });
+ const agent = createAgent(createHandle({ agentKind: 'pi' }));
+ agent.startSession = vi.fn().mockRejectedValue(pending);
+ const maker = new Maker({
+ agents: { pi: agent },
+ storage: createStorage(),
+ logger,
+ lifecycleHooks: {
+ onStartCleanupSucceeded: async () => {
+ cleanupEntered = true;
+ await cleanupGate.promise;
+ },
+ },
+ });
+ await expect(maker.createSession({ id: 's-deferred-cleanup', agentKind: 'pi', workingDir: '/w', model: 'm' }))
+ .rejects.toBe(pending);
+
+ let shutdownSettled = false;
+ const shutdown = maker.shutdown().then(() => { shutdownSettled = true; });
+ stopped.resolve();
+ await vi.waitFor(() => expect(cleanupEntered).toBe(true));
+ expect(shutdownSettled).toBe(false);
+
+ cleanupGate.resolve();
+ await shutdown;
+ expect(shutdownSettled).toBe(true);
+ });
+
+ it('waits for session lifecycle cleanup hooks before resolving', async () => {
+ let releaseCleanup!: () => void;
+ const cleanupGate = new Promise<void>((resolve) => { releaseCleanup = resolve; });
+ let cleanupEntered = false;
+ const maker = new Maker({
+ agents: { 'claude-code': createAgent(createHandle({})) },
+ storage: createStorage(),
+ logger,
+ lifecycleHooks: {
+ onClose: async () => {
+ cleanupEntered = true;
+ await cleanupGate;
+ },
+ },
+ });
+ await maker.createSession({ id: 's-cleanup', agentKind: 'claude-code', workingDir: '/w', model: 'm' });
+
+ let shutdownSettled = false;
+ const shutdown = maker.shutdown().then(() => { shutdownSettled = true; });
+ await vi.waitFor(() => expect(cleanupEntered).toBe(true));
+ expect(shutdownSettled).toBe(false);
+
+ releaseCleanup();
+ await shutdown;
+ expect(shutdownSettled).toBe(true);
+ });
+
it('detaches remote-capable sessions instead of full-closing them', async () => {
const close = vi.fn(async () => undefined);
const detach = vi.fn(async () => undefined);