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。

Merge upstream main and resolve Pi package conflicts

lizzjine852df8551b4
diff --cc apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
index 4b6a60e299,8e27abb176..002098ac23
--- 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
@@@ -37,8 -38,11 +39,10 @@@ const runtime = vi.hoisted(() => (
spawns: [] as Array<{ args: string[]; env: Record<string, string | undefined>; detached?: boolean }>,
holdMutationCommand: false,
pendingClose: null as null | ((code: number) => void),
+ spawnHook: null as null | ((args: string[]) => void),
}));
-const loggerRuntime = vi.hoisted(() => ({ warn: vi.fn() }));
+
const processRuntime = vi.hoisted(() => ({
killTree: vi.fn(),
pendingTreeSettled: null as null | (() => void),
@@@ -52,10 -56,6 +56,11 @@@ const lockRuntime = vi.hoisted(() => (
nextStatus: null as null | { held: false; reason: 'busy' | 'unavailable' },
}));
+const loggerRuntime = vi.hoisted(() => ({
++ warn: vi.fn(),
+ info: vi.fn(),
+}));
+
vi.mock('electron', () => ({
app: { getPath: () => runtime.userData },
}));
@@@ -66,7 -66,7 +71,7 @@@ vi.mock('../../agent-binaries/index.js'
vi.mock('../../logger.js', () => ({
createLogger: () => ({
- trace: vi.fn(), debug: vi.fn(), info: loggerRuntime.info, warn: vi.fn(), error: vi.fn(), fatal: vi.fn(),
- trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: loggerRuntime.warn, error: vi.fn(), fatal: vi.fn(),
++ trace: vi.fn(), debug: vi.fn(), info: loggerRuntime.info, warn: loggerRuntime.warn, error: vi.fn(), fatal: vi.fn(),
child() { return this; },
}),
}));
@@@ -556,6 -602,283 +608,303 @@@ describe('Pi package executable-code bo
expect(installed.packages).toMatchObject([{ source, enabled: true }]);
});
+ it('feeds installed roots to Pi native discovery without requiring Cindy approval', async () => {
+ const { root, source } = await createPackage();
+ const store = await import('../pi-package-store.js');
+
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([root]);
+
+ await mutateAuthorized(store, { action: 'set-enabled', source, enabled: false });
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([]);
+ });
+
++ it('collects startup metadata without copying native packages into a session snapshot', async () => {
++ const { root } = await createSkillOnlyPackage('npm:native-startup-metadata');
++ 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(root, 'skills', 'managed-skill', 'SKILL.md'),
++ })],
++ packageRoots: [root],
++ });
++ expect(copySpy).not.toHaveBeenCalled();
++ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([root]);
++ } finally {
++ copySpy.mockRestore();
++ }
++ });
++
+ 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`;
+ const packageHome = path.join(runtime.userData, 'pi-package-home');
+ await fs.mkdir(packageHome, { recursive: true });
+ await fs.writeFile(path.join(packageHome, 'settings.json'), '{"packages":');
+ const store = await import('../pi-package-store.js');
+
+ await expect(store.resolveManagedPiNativePackagePaths()).rejects.toThrow('state is unavailable');
+ expect(loggerRuntime.warn).toHaveBeenCalledWith(
+ 'Pi package filter settings unavailable',
+ { failureCategory: 'state-unavailable' },
+ );
+ });
+
+ it('preserves native filters from a valid settings file above the inspection byte limit', async () => {
+ const { root, source } = await createPackage({ source: 'npm:filtered-large-settings' });
+ runtime.listOutput = `User packages:\n ${source} (filtered)\n ${root}\n`;
+ const packageHome = path.join(runtime.userData, 'pi-package-home');
+ const settingsContents = JSON.stringify({
+ packages: [{
+ source,
+ extensions: ['extensions/*.ts', '!extensions/legacy.ts'],
+ skills: [],
+ }],
+ nativePadding: 'x'.repeat(1_048_576),
+ });
+ expect(Buffer.byteLength(settingsContents)).toBeGreaterThan(1_048_576);
+ await fs.mkdir(packageHome, { recursive: true });
+ await fs.writeFile(path.join(packageHome, 'settings.json'), settingsContents);
+ const store = await import('../pi-package-store.js');
+
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([{
+ source: root,
+ extensions: ['extensions/*.ts', '!extensions/legacy.ts'],
+ skills: [],
+ }]);
+ expect(loggerRuntime.warn.mock.calls).toEqual([]);
+ });
+
+ it.skipIf(!canLinkFile)('preserves native filters from a settings symlink outside package home', async () => {
+ const { root, source } = await createPackage({ source: 'npm:filtered-linked-settings' });
+ runtime.listOutput = `User packages:\n ${source} (filtered)\n ${root}\n`;
+ const packageHome = path.join(runtime.userData, 'pi-package-home');
+ const externalSettings = path.join(runtime.userData, 'dotfiles-settings.json');
+ await fs.mkdir(packageHome, { recursive: true });
+ await fs.writeFile(externalSettings, JSON.stringify({
+ packages: [{
+ source,
+ extensions: ['extensions/*.ts', '!extensions/legacy.ts'],
+ skills: [],
+ }],
+ }));
+ await fs.symlink(externalSettings, path.join(packageHome, 'settings.json'), 'file');
+ const store = await import('../pi-package-store.js');
+
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([{
+ source: root,
+ extensions: ['extensions/*.ts', '!extensions/legacy.ts'],
+ skills: [],
+ }]);
+ expect(loggerRuntime.warn.mock.calls).toEqual([]);
+ });
+
+ it('keeps an unfiltered native package when optional filter settings are unavailable', async () => {
+ const { root } = await createPackage({ source: 'npm:unfiltered-settings-failure' });
+ const settingsFile = path.join(runtime.userData, 'pi-package-home', 'settings.json');
+ await fs.mkdir(path.dirname(settingsFile), { recursive: true });
+ await fs.writeFile(settingsFile, '{"packages":');
+ const store = await import('../pi-package-store.js');
+
+ await expect(store.resolveManagedPiNativePackagePaths()).resolves.toEqual([root]);
+ });
+
+ it('preserves Pi object-form resource filters when projecting an installed root', async () => {
+ const { root, source } = await createPackage({ source: 'npm:filtered-package' });
+ runtime.listOutput = `User packages:\n ${source} (filtered)\n ${root}\n`;
+ const packageHome = path.join(runtime.userData, 'pi-package-home');
+ await fs.mkdir(packageHome, { recursive: true });
+ await fs.writeFile(path.join(packageHome, 'settings.json'), JSON.stringify({
+ packages: [{
+ source,
+ extensions: ['extensions/*.ts', '!extensions/legacy.ts'],
+ skills: [],
+ prompts: ['prompts/review.md'],
+ }],
+ }));
+ const store = await import('../pi-package-store.js');
+
+ const projected = await store.resolveManagedPiNativePackagePaths();
+ expect(loggerRuntime.warn.mock.calls).toEqual([]);
+ expect(projected).toEqual([{
+ source: root,
+ extensions: ['extensions/*.ts', '!extensions/legacy.ts'],
+ skills: [],
+ prompts: ['prompts/review.md'],
+ }]);
+ });
+
+ it('keeps compatibility analysis informational during install', async () => {
+ const { root, source } = await createPackage();
+ await fs.writeFile(path.join(root, 'extensions', 'index.ts'), `
+ export default function setup(pi: any) {
+ pi.on('session_start', (_event: unknown, ctx: any) => {
+ ctx.ui.setStatus('compatibility-note', 'still launchable');
+ });
+ }
+ `);
+ const store = await import('../pi-package-store.js');
+
+ const installed = await mutateAuthorized(store, { action: 'install', source });
+
+ expect(installed.affectedPackage).toMatchObject({
+ source,
+ enabled: true,
+ resources: expect.arrayContaining([expect.objectContaining({
+ kind: 'extension',
+ compatibility: 'partial',
+ compatibilityIssues: ['status-display'],
+ })]),
+ });
+ });
+
+ it('clears an old explicit disable after reinstall even when post-install analysis fails', async () => {
+ const { source } = await createPackage();
+ const stateDir = path.join(runtime.userData, 'pi-package-home');
+ const stateFile = path.join(stateDir, 'cindy-package-state.json');
+ await fs.mkdir(stateDir, { recursive: true });
+ await fs.writeFile(stateFile, JSON.stringify({
+ version: 3,
+ disabledSources: [source, 'npm:keep-disabled'],
+ approvedExtensionSources: [],
+ approvedExtensionFingerprints: {},
+ snapshotUnavailableRoots: {},
+ }));
+ runtime.listOutcomes.push({ stderr: 'analysis unavailable', exitCode: 1 });
+ const store = await import('../pi-package-store.js');
+
+ await expect(mutateAuthorized(store, { action: 'install', source })).resolves.toMatchObject({
+ affectedPackage: { source, enabled: true },
+ });
+ const state = JSON.parse(await fs.readFile(stateFile, 'utf8')) as { disabledSources: string[] };
+ expect(state.disabledSources).toEqual(['npm:keep-disabled']);
+ });
+
+ it.each(['install', 'update'] as const)(
+ 'builds a Git-style package on %s and republishes the runtime fence after generated bytes settle',
+ async (action) => {
+ const { root, source } = await createPackage();
+ await fs.writeFile(path.join(root, 'package.json'), JSON.stringify({
+ name: 'generated-extension',
+ version: '1.0.0',
+ pi: {
+ extensions: ['./build/adapters/pi/extension.js'],
+ skills: ['./skills'],
+ },
+ scripts: { build: 'node build.mjs' },
+ }));
+ await fs.rm(path.join(root, 'extensions'), { recursive: true, force: true });
+ await fs.rm(path.join(root, 'prompts'), { recursive: true, force: true });
+ await fs.mkdir(path.join(root, 'skills', 'generated'), { recursive: true });
+ await fs.writeFile(path.join(root, 'skills', 'generated', 'SKILL.md'), '# Generated\n');
+ let fenceGeneration = 0;
+ let generationDuringBuild = -1;
+ runtime.spawnHook = (args) => {
+ if (args.at(-2) !== 'run' || args.at(-1) !== 'build') return;
+ generationDuringBuild = fenceGeneration;
+ const entry = path.join(root, 'build', 'adapters', 'pi', 'extension.js');
+ mkdirSync(path.dirname(entry), { recursive: true });
+ writeFileSync(entry, 'export default function setup() {}\n');
+ };
+ const store = await import('../pi-package-store.js');
+ const runtimeFence = vi.fn(() => { fenceGeneration += 1; });
+
+ const installed = await mutateAuthorized(store, { action, source }, {
+ onRuntimeInvalidationPublished: runtimeFence,
+ });
+
+ const spawnedArgs = runtime.spawns.map(({ args }) => args);
+ expect(spawnedArgs.some((args) => (
+ args.slice(-4).join('\0') === [
+ 'install', '--include=dev', '--no-audit', '--no-fund',
+ ].join('\0')
+ ))).toBe(true);
+ expect(spawnedArgs.some((args) => args.slice(-2).join('\0') === 'run\0build')).toBe(true);
+ expect(installed.affectedPackage).toMatchObject({
+ source,
+ enabled: true,
+ resources: expect.arrayContaining([expect.objectContaining({ kind: 'extension' })]),
+ });
+ expect(generationDuringBuild).toBe(1);
+ expect(runtimeFence).toHaveBeenNthCalledWith(1, 'commit');
+ expect(runtimeFence).toHaveBeenNthCalledWith(2, 'post-build');
+ });
+
+ it.each([
+ [
+ 'npm install',
+ 'install',
+ 'install',
+ 'getaddrinfo ENOTFOUND https://user:[email protected]/pkg?token=query-secret#fragment-secret /private/host/path',
+ 'source-unavailable',
+ ],
+ [
+ 'npm build',
+ 'update',
+ 'build',
+ 'fetch failed https://user:[email protected]/pkg?token=query-secret#fragment-secret /private/host/path',
+ 'source-unavailable',
+ ],
+ ['normal npm install', 'install', 'install', 'npm ERR! code ETARGET No matching version found', 'version-not-found'],
+ ['normal npm build', 'update', 'build', 'npm ERR! code E404 package not found', 'package-not-found'],
+ ] as const)('keeps native Pi success and logs only a stable category after %s fails', async (
+ _label,
+ action,
+ phase,
+ stderr,
+ failureCategory,
+ ) => {
+ const { root, source } = await createPackage();
+ await fs.writeFile(path.join(root, 'package.json'), JSON.stringify({
+ name: 'broken-generated-extension',
+ version: '1.0.0',
+ pi: {
+ extensions: ['./build/adapters/pi/extension.js'],
+ skills: ['./skills'],
+ },
+ scripts: { build: 'node build.mjs' },
+ }));
+ await fs.rm(path.join(root, 'extensions'), { recursive: true, force: true });
+ await fs.rm(path.join(root, 'prompts'), { recursive: true, force: true });
+ await fs.mkdir(path.join(root, 'skills', 'generated'), { recursive: true });
+ await fs.writeFile(path.join(root, 'skills', 'generated', 'SKILL.md'), '# Generated\n');
+ let fenceGeneration = 0;
+ let generationDuringFailure = -1;
+ runtime.spawnHook = (args) => {
+ const isTarget = phase === 'install'
+ ? args.slice(-4).join('\0') === 'install\0--include=dev\0--no-audit\0--no-fund'
+ : args.slice(-2).join('\0') === 'run\0build';
+ if (isTarget) generationDuringFailure = fenceGeneration;
+ runtime.stderr = isTarget ? stderr : '';
+ runtime.exitCode = isTarget ? 1 : 0;
+ };
+ const store = await import('../pi-package-store.js');
+ const runtimeFence = vi.fn(() => { fenceGeneration += 1; });
+
+ const result = await mutateAuthorized(store, { action, source }, {
+ onRuntimeInvalidationPublished: runtimeFence,
+ });
+
+ expect(result.affectedPackage).toMatchObject({ source, enabled: true });
+ const assistanceLog = loggerRuntime.warn.mock.calls.find(
+ ([message]) => message === (action === 'update'
+ ? 'optional Pi package update build assistance failed'
+ : 'optional Pi package build assistance failed'),
+ );
+ expect(assistanceLog?.[1]).toEqual({ failureCategory, mayHaveChangedState: true });
+ expect(generationDuringFailure).toBe(1);
+ expect(runtimeFence).toHaveBeenNthCalledWith(1, 'commit');
+ expect(runtimeFence).toHaveBeenNthCalledWith(2, 'post-build');
+ const published = JSON.stringify({ logs: loggerRuntime.warn.mock.calls, result });
+ expect(published).not.toContain('api-key');
+ expect(published).not.toContain('query-secret');
+ expect(published).not.toContain('fragment-secret');
+ expect(published).not.toContain('/private/host/path');
+ });
+
it('keeps an explicitly disabled Extension package disabled after a confirmed update', async () => {
const { source } = await createPackage();
const store = await import('../pi-package-store.js');
@@@ -1584,529 -1891,21 +1925,528 @@@
await expect(store.listPiPackages()).resolves.toMatchObject({
packages: [
{ enabled: true },
- { enabled: false, warning: 'inspection-limit' },
- { enabled: false, warning: 'inspection-limit' },
+ { enabled: true, warning: 'inspection-limit' },
+ { 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: false, warning: 'inspection-limit' }],
++ 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);
+ 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 () => {
++ 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({
- snapshotRoot: path.join(runtime.userData, 'inspection-limit-first-snapshot'),
++ ...(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({
- snapshotRoot: path.join(runtime.userData, 'inspection-limit-second-snapshot'),
++ ...(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: false, warning: 'inspection-limit' },
++ { 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',
- )) as { disabledSources: string[]; snapshotUnavailableRoots: Record<string, string> };
- expect(state.disabledSources).toEqual([]);
- expect(state.snapshotUnavailableRoots).toEqual({
- [await fs.realpath(packageRoots[1]!)]: 'inspection-limit',
- [await fs.realpath(packageRoots[2]!)]: 'inspection-limit',
+ )) as { snapshotUnavailablePackages: Array<{ source: string }> };
+ expect(state.snapshotUnavailablePackages.map((entry) => entry.source)).toEqual([
+ oversizedSource,
+ ]);
+ });
+
+ it('retries an inspection-stage duration limit instead of persisting it', async () => {
+ 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
+ && canonicalCandidate === canonicalSkillsRoot
+ ) {
+ delayedInspection = true;
+ now += 2_001;
+ }
+ return result;
});
+ try {
+ await expect(store.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, 'inspection-duration-first-snapshot'),
+ })).resolves.toMatchObject({ packageRoots: [] });
+ await expect(store.listPiPackages()).resolves.toMatchObject({
- packages: [{ source, enabled: false, warning: 'inspection-limit' }],
++ packages: [{ source, enabled: true, warning: 'inspection-limit' }],
+ });
+
+ const stateFile = await fs.readFile(
+ path.join(runtime.userData, 'pi-package-home', 'cindy-package-state.json'),
+ 'utf8',
+ ).catch(() => null);
+ if (stateFile) {
+ expect(JSON.parse(stateFile)).toMatchObject({ snapshotUnavailablePackages: [] });
+ }
+
+ const recoveredRoot = path.join(runtime.userData, 'inspection-duration-recovered-snapshot');
+ await expect(store.resolveManagedPiPackageResources({
+ snapshotRoot: recoveredRoot,
+ })).resolves.toMatchObject({
+ skills: [
+ expect.objectContaining({
+ path: path.join(recoveredRoot, '0', 'skills', 'managed-skill', 'SKILL.md'),
+ }),
+ ],
+ packageRoots: [path.join(recoveredRoot, '0')],
+ });
+ } finally {
+ readdirSpy.mockRestore();
+ nowSpy.mockRestore();
+ }
+ });
+
+ it('does not reuse a persisted inspection-limit after the installation is replaced in place', async () => {
+ const { root, source } = await createSkillOnlyPackage('npm:replaced-installation');
+ const store = await import('../pi-package-store.js');
+ await expect(
+ store.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, 'old-installation-limited-snapshot'),
+ snapshotLimits: {
+ maxEntries: 1,
+ maxBytes: 1024 * 1024,
+ maxDurationMs: 10_000,
+ },
+ }),
+ ).resolves.toMatchObject({ packageRoots: [] });
+
+ await fs.rm(root, { recursive: true, force: true });
+ await fs.mkdir(path.join(root, 'skills', 'managed-skill'), { recursive: true });
+ 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'),
+ '# Replaced installation\n',
+ );
+
+ vi.resetModules();
+ const replacementStore = await import('../pi-package-store.js');
+ await expect(replacementStore.listPiPackages()).resolves.toMatchObject({
+ packages: [
+ expect.objectContaining({
+ source,
+ enabled: true,
+ }),
+ ],
+ });
+ const recoveredRoot = path.join(runtime.userData, 'new-installation-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 persisted inspection-limit after deep package content shrinks under a stable root identity', async () => {
+ const { root, source } = await createSkillOnlyPackage('npm:mutated-installation');
+ 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);
+ 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');
+ 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();
+ nowSpy.mockRestore();
+ }
});
+ it.each([
+ ['install', 'install', undefined],
+ ['update', 'update', undefined],
+ ['remove', 'remove', undefined],
+ ['enable', 'set-enabled', true],
+ ['disable', 'set-enabled', false],
+ ] as const)(
+ 'a production %s mutation clears the durable snapshot failure before fresh inspection',
+ async (_label, action, enabled) => {
+ const { source } = await createSkillOnlyPackage(
+ `npm:mutation-recovery-${action}-${String(enabled)}`,
+ );
+ const store = await import('../pi-package-store.js');
- const enableIdentity = await store.capturePiPackageEnableIdentity(source);
+ await expect(
+ store.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, `limited-before-${action}-${String(enabled)}`),
+ snapshotLimits: {
+ maxEntries: 1,
+ maxBytes: 1024 * 1024,
+ maxDurationMs: 10_000,
+ },
+ }),
+ ).resolves.toMatchObject({ packageRoots: [] });
+
+ const request: PiPackageMutationRequest =
+ action === 'set-enabled' ? { action, source, enabled: enabled! } : { action, source };
- if (action === 'set-enabled' && enabled === true) {
- const { issuePiPackageMutationGrant } = await import('../pi-package-mutation-grant.js');
- await store.mutatePiPackage(
- request,
- issuePiPackageMutationGrant(request, {
- expectedPackageFingerprint: enableIdentity.expectedPackageFingerprint,
- }),
- );
- } else if (action === 'set-enabled') {
++ if (action === 'set-enabled' && enabled === false) {
+ await store.mutatePiPackage(request);
+ } else {
+ await mutateAuthorized(store, request);
+ }
+
+ if (enabled === false) {
+ await expect(store.listPiPackages()).resolves.toMatchObject({
+ packages: [{ source, enabled: false }],
+ });
+ } else {
+ const recoveredRoot = path.join(
+ runtime.userData,
+ `recovered-after-${action}-${String(enabled)}`,
+ );
+ await expect(
+ store.resolveManagedPiPackageResources({
+ snapshotRoot: recoveredRoot,
+ }),
+ ).resolves.toMatchObject({
+ skills: [
+ expect.objectContaining({
+ path: path.join(recoveredRoot, '0', 'skills', 'managed-skill', 'SKILL.md'),
+ }),
+ ],
+ packageRoots: [path.join(recoveredRoot, '0')],
+ });
+ }
+ const state = JSON.parse(
+ await fs.readFile(
+ path.join(runtime.userData, 'pi-package-home', 'cindy-package-state.json'),
+ 'utf8',
+ ),
+ ) as { snapshotUnavailablePackages: unknown[] };
+ expect(state.snapshotUnavailablePackages).toEqual([]);
+ },
+ );
+
it('does not run a skipped descendant extension from an unverified ancestor snapshot', async () => {
const ancestorRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-pi-package-approved-overlap-'));
roots.push(ancestorRoot);
@@@ -2300,7 -2100,9 +2642,9 @@@
extensions: [path.join(recoveredRoot, '0', 'extensions', 'index.ts')],
packageRoots: [path.join(recoveredRoot, '0')],
});
- await vi.waitFor(() => expect(firstListener).toHaveBeenCalled(), { timeout: 2_000 });
- await vi.waitFor(() => expect(firstListener).toHaveBeenCalledWith('external'), {
++ await vi.waitFor(() => expect(firstListener).toHaveBeenCalledWith('external-runtime'), {
+ timeout: 2_000,
+ });
await expect(firstStore.listPiPackages()).resolves.toMatchObject({
packages: [{ source, enabled: true }],
});
@@@ -2446,48 -2248,20 +2790,52 @@@
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.disabledSources).toEqual([source]);
+ expect(migrated.snapshotUnavailablePackages).toEqual([]);
+ });
+
- it.each([
- ['transient I/O', 'EIO'],
- ['permission', 'EACCES'],
- ])('fails closed without replacing disabled state after a %s read failure', async (_label, code) => {
- const { source } = await createSkillOnlyPackage('npm:disabled-skill-package');
+ 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';
+ const created = await createPackage({ source: relativeSource });
const stateDir = path.join(runtime.userData, 'pi-package-home');
+ const absoluteSource = path.join(stateDir, 'same-directory', 'relative-package');
+ await fs.mkdir(path.dirname(absoluteSource), { recursive: true });
+ await fs.rename(created.root, absoluteSource);
+ runtime.listOutput = `User packages:\n ${relativeSource}\n ${absoluteSource}\n`;
+ await fs.mkdir(stateDir, { recursive: true });
const stateFile = path.join(stateDir, 'cindy-package-state.json');
- const persistedState = `${JSON.stringify({
+ await fs.writeFile(stateFile, JSON.stringify({
version: 3,
- disabledSources: [source],
+ disabledSources: [relativeSource, sibling],
approvedExtensionSources: [],
approvedExtensionFingerprints: {},
snapshotUnavailableRoots: {},
@@@ -2681,6 -3494,46 +4068,48 @@@
unsubscribe();
});
+ it('does not let an immediate view publication overwrite a peer runtime invalidation', async () => {
+ const { source } = await createPackage();
+ const firstStore = await import('../pi-package-store.js');
+ const listener = vi.fn();
+ const unsubscribe = firstStore.onPiPackagesChanged(listener);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ vi.resetModules();
+ const secondStore = await import('../pi-package-store.js');
+ try {
+ await mutateAuthorized(secondStore, { action: 'update', source });
+ await secondStore.resolveManagedPiPackageResources({
+ snapshotRoot: path.join(runtime.userData, 'view-after-runtime-snapshot'),
+ snapshotLimits: {
- maxEntries: 100,
++ // Deterministic limits publish a durable advisory view. Duration
++ // failures remain transient and intentionally do not publish one.
++ maxEntries: 1,
+ maxBytes: 1024 * 1024,
- maxDurationMs: 0,
++ maxDurationMs: 10_000,
+ },
+ });
+
+ await vi.waitFor(() => expect(listener).toHaveBeenCalledWith('external-runtime'), {
+ timeout: 2_000,
+ });
+ await expect(fs.readFile(
+ path.join(runtime.userData, 'pi-package-home', 'cindy-package-runtime-change-token'),
+ 'utf8',
+ )).resolves.toMatch(/^runtime:/);
+ await expect(fs.readFile(
+ path.join(runtime.userData, 'pi-package-home', 'cindy-package-change-token'),
+ 'utf8',
+ )).resolves.toMatch(/^runtime:/);
+ await expect(fs.readFile(
+ path.join(runtime.userData, 'pi-package-home', 'cindy-package-view-change-token'),
+ 'utf8',
+ )).resolves.toMatch(/^view:/);
+ } finally {
+ unsubscribe();
+ }
+ });
+
it('fails closed before touching the package tree when the shared lock is unavailable', async () => {
const { source } = await createPackage();
const store = await import('../pi-package-store.js');
diff --cc apps/desktop/src/main/maker-host/pi-package-store.ts
index d5ddbadf40,58365ae2ca..1f92270eae
--- a/apps/desktop/src/main/maker-host/pi-package-store.ts
+++ b/apps/desktop/src/main/maker-host/pi-package-store.ts
@@@ -80,11 -83,21 +84,21 @@@ const DEFAULT_SNAPSHOT_LIMITS: PiPackag
maxBytes: 128 * 1024 * 1024,
maxDurationMs: 15_000,
};
-const STATE_VERSION = 3;
+const STATE_VERSION = 4;
const CHANGE_TOKEN_POLL_MS = 250;
- const changeListeners = new Set<() => void>();
+ export type PiPackagesChangeOrigin = 'local' | 'external' | 'external-runtime';
+ const changeListeners = new Set<(origin: PiPackagesChangeOrigin) => void>();
+ const packageMutationMayHaveChangedErrors = new WeakSet<object>();
let changeTokenWatcherActive = false;
- let lastObservedChangeToken: string | null | undefined;
+ let changeTokenWatcherStartedAtMs: number | undefined;
+ let lastObservedRuntimeChangeToken: string | null | undefined;
+ let runtimeChangeTokenReadFailedBeforeBaseline = false;
+ let runtimeRecoveryLegacyBaseline: string | null = null;
+ let runtimeRecoveryLegacyBaselineInitialized = false;
+ let lastObservedLegacyChangeToken: string | null | undefined;
+ let lastObservedViewChangeToken: string | null | undefined;
+ let lastNotifiedRuntimeChangeToken: string | null | undefined;
+ let lastExternallyNotifiedRuntimeChangeToken: string | null | undefined;
let changeTokenReadInFlight: Promise<void> | undefined;
let changeTokenReadQueued = false;
const changeTokenWatchListener = () => void observePiPackageChangeToken();
@@@ -379,7 -440,8 +542,8 @@@ let mutationTail: Promise<void> = Promi
let inspectionPromise: Promise<InspectedPackage[]> | undefined;
let inspectionCache: { expiresAt: number; value: InspectedPackage[] } | undefined;
let inspectionGeneration = 0;
-const snapshotUnavailableRoots = new Map<string, SnapshotUnavailableWarning>();
+const snapshotUnavailablePackages = new Map<string, SnapshotUnavailablePackageProjection>();
+ const pendingEnabledSources = new Set<string>();
function packageHome(): string {
return path.join(app.getPath('userData'), 'pi-package-home');
@@@ -1271,12 -1430,16 +1632,21 @@@ function resourceView(kind: Exclude<PiP
};
}
+ function unknownExtensionResourceView(file: string): PiPackageResourceView {
+ return {
+ kind: 'extension',
+ name: truncateDisplayField(path.basename(file), MAX_DISPLAY_NAME_BYTES),
+ compatibility: 'unknown',
+ compatibilityIssues: ['analysis-incomplete'],
+ };
+ }
+
-async function extensionResourceView(root: string, file: string): Promise<PiPackageResourceView> {
+async function extensionResourceView(
+ root: string,
+ file: string,
+ startupTiming?: PiPackageStartupTiming,
+): Promise<PiPackageResourceView> {
+ const startedAt = Date.now();
try {
const analysis = await analyzePiExtensionCompatibility(file, root);
return {
@@@ -1289,14 -1452,7 +1659,9 @@@
...(analysis.detectedApis.length > 0 ? { detectedApis: analysis.detectedApis } : {}),
};
} catch {
- return {
- kind: 'extension',
- name: truncateDisplayField(path.basename(file), MAX_DISPLAY_NAME_BYTES),
- compatibility: 'unknown',
- compatibilityIssues: ['analysis-incomplete'],
- };
+ return unknownExtensionResourceView(file);
+ } finally {
+ recordPiPackageStartupDuration(startupTiming, 'package-compatibility', startedAt);
}
}
@@@ -1523,17 -1650,17 +1881,19 @@@ async function inspectPackage
collectFilesByExtension(await confinedExistingPaths(root, themeInputs), ['.json'], budget),
]);
assertInspectionBudget(budget);
- if (extensions.length > MAX_EXTENSION_FILES) throw new PiPackageInspectionLimitError();
+ if (extensions.length > MAX_EXTENSION_FILES) {
+ throw new PiPackageInspectionLimitError('entries');
+ }
- // Babel parsing happens in Electron's main process. Keep analysis
- // sequential and re-check the package-wide wall-clock budget between
- // entries so a package cannot fan out thousands of CPU-heavy parses.
+ // Compatibility parsing is advisory and must never decide whether code is
+ // installable. Keep it sequential and bounded; once its package-wide time
+ // allowance is spent, project remaining entries as unknown rather than
+ // failing inspection or withholding launch resources.
const extensionResources: PiPackageResourceView[] = [];
+ const compatibilityDeadline = Date.now() + MAX_INSPECTION_MS;
for (const file of extensions) {
- assertInspectionBudget(budget);
- extensionResources.push(await extensionResourceView(root, file, startupTiming));
- assertInspectionBudget(budget);
+ extensionResources.push(Date.now() < compatibilityDeadline
- ? await extensionResourceView(root, file)
++ ? await extensionResourceView(root, file, startupTiming)
+ : unknownExtensionResourceView(file));
}
const resources: PiPackageResourceView[] = [
...extensionResources,
@@@ -1590,12 -1715,18 +1948,20 @@@
...(warning ? { warning } : {}),
},
launch: enabled && hasLaunchResources
- ? { extensions, skills, promptTemplates: prompts, packageRoots: [launchRoot] }
+ ? { extensions, skills, promptTemplates: prompts, packageRoots: [snapshotRoot] }
: empty,
promptCommands,
+ ...(Array.isArray(declared?.extensions)
+ && declared.extensions.length > 0
+ && extensions.length === 0
+ ? { missingDeclaredExtensions: true as const }
+ : {}),
+ ...(typeof manifest.scripts?.build === 'string' && manifest.scripts.build.trim()
+ ? { buildScript: manifest.scripts.build.trim() }
+ : {}),
installedRoot: root,
+ installationIdentity,
+ snapshotRoot,
...(contentFingerprint ? { contentFingerprint } : {}),
...(staleApproval ? { staleApproval: true } : {}),
};
@@@ -1633,87 -1750,27 +1999,84 @@@
},
launch: empty,
promptCommands: [],
- ...(installedRoot ? { installedRoot } : {}),
+ ...(installedRoot || pkg.installedPath
+ ? { installedRoot: installedRoot ?? pkg.installedPath }
+ : {}),
+ ...(installationIdentity ? { installationIdentity } : {}),
+ ...(snapshotRoot ? { snapshotRoot } : {}),
+ ...(snapshotUnavailable ? { snapshotUnavailable } : {}),
};
}
}
-async function inspectAllPackagesUncached(): Promise<InspectedPackage[]> {
+async function persistedSnapshotLimitProjection(
+ pkg: ListedPackage,
+ state: PiPackageState,
+): Promise<InspectedPackage | undefined> {
+ if (!pkg.installedPath || pkg.filtered) return undefined;
+ if (state.snapshotUnavailablePackages.length === 0) return undefined;
+ const { displaySource, unsafe } = projectPackageSource(pkg.source);
+ if (unsafe) return undefined;
+ try {
+ const { canonicalPath: installedRoot, stat } = await resolveStablePackagePath(
+ pkg.installedPath,
+ 'Pi package root changed while resolving its snapshot failure',
+ );
+ const snapshotRoot = await snapshotRootForInstalledPackage(pkg.source, installedRoot);
+ const installationIdentity = await packageInstallationIdentity(installedRoot, stat);
+ const persisted = state.snapshotUnavailablePackages.find(
+ (entry) =>
+ entry.source === pkg.source &&
+ path.resolve(entry.installedRoot) === path.resolve(installedRoot) &&
+ path.resolve(entry.snapshotRoot) === path.resolve(snapshotRoot) &&
+ entry.installationIdentity === installationIdentity,
+ );
+ if (!persisted || isSnapshotUnavailableRetryDue(persisted)) return undefined;
+ return {
+ rawSource: pkg.source,
+ view: {
+ source: displaySource,
+ name: displaySource,
+ enabled: false,
+ canToggle: false,
+ resources: [],
+ warning: 'inspection-limit',
+ },
+ launch: { extensions: [], skills: [], promptTemplates: [], packageRoots: [] },
+ promptCommands: [],
+ installedRoot,
+ installationIdentity,
+ snapshotRoot,
+ snapshotUnavailable: persisted,
+ };
+ } catch {
+ // Path identity could not be proven cheaply. Fall through to the regular
+ // fail-closed inspection so transient filesystem failures remain retryable.
+ return undefined;
+ }
+}
+
+async function inspectAllPackagesUncached(
+ options: {
+ ignorePersistedSnapshotUnavailable?: boolean;
+ startupTiming?: PiPackageStartupTiming;
+ } = {},
+): Promise<InspectedPackage[]> {
- const [{ stdout }, stateResult] = await Promise.all([
+ const [listed, stateResult] = await Promise.all([
- runPiPackageListCommand(),
+ measurePiPackageStartupStage(
+ options.startupTiming,
+ 'package-list',
- () => runPiPackageCommand(
- ['list', '--no-approve'],
- COMMAND_TIMEOUT_MS,
- { requireCompleteStdout: true },
- ),
++ () => 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);
}
- const listed = parsePiPackageListOutput(stdout);
+ 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);
@@@ -1822,11 -1858,37 +2187,39 @@@ async function inspectAllPackagesFreshU
const staleInspection = inspectionPromise;
if (staleInspection) await staleInspection.catch(() => undefined);
invalidateInspectionCache();
- return inspectAllPackages();
+ return options.ignorePersistedSnapshotUnavailable || options.startupTiming
+ ? inspectAllPackagesUncached(options)
+ : inspectAllPackages();
}
+ async function projectNativePackageViews(
+ inspected: InspectedPackage[],
+ ): Promise<PiPackageView[]> {
+ const state = await readStateWithoutBlockingPi();
+ const disabled = new Set(state.disabledSources);
+ return inspected.map((pkg) => {
+ const warning = snapshotUnavailableWarningForPackage(pkg) ?? pkg.view.warning;
+ const mutationTarget = pkg.view.mutationTarget
+ ?? (pkg.view.source !== pkg.rawSource ? packageMutationTarget(pkg.rawSource) : undefined);
+ const {
+ requiresExtensionApproval: _ignoredApproval,
+ manageable: _ignoredManageable,
+ canToggle,
+ ...view
+ } = pkg.view;
+ // Pi's list output is the install truth. Cindy inspection, compatibility,
+ // fingerprint, or snapshot failures stay advisory and cannot disable it.
+ const installed = Boolean(pkg.installedRoot);
+ return {
+ ...view,
+ ...(mutationTarget ? { mutationTarget } : {}),
+ enabled: installed && !isPackageSourceDisabled(disabled, pkg.rawSource),
+ ...(!installed && canToggle === false ? { canToggle: false as const } : {}),
+ ...(warning ? { warning } : {}),
+ };
+ });
+ }
+
async function listPiPackagesNow(): Promise<PiPackageListResult> {
if (!getReadyBinaryPath('pi')) return { available: false, packages: [] };
const inspected = await inspectAllPackages();
@@@ -1844,130 -1903,21 +2234,62 @@@ export async function listPiPackages()
return listPiPackagesNow();
}
- export interface PiPackageEnableIdentity {
- displayLabel: string;
- expectedPackageFingerprint: string;
- }
-
- function nativeConfirmationField(value: string, maxBytes: number): string {
- return truncateDisplayField(
- escapePiPackageNativeDialogText(value).replace(/\s+/g, ' '),
- maxBytes,
- );
- }
-
- function piPackageEnableDisplayLabel(
- target: InspectedPackage,
- packageFingerprint: string,
- ): string {
- let name = nativeConfirmationField(target.view.name, MAX_DISPLAY_NAME_BYTES);
- if (
- !name
- || path.isAbsolute(name)
- || path.win32.isAbsolute(name)
- || name.includes('/')
- || name.includes('\\')
- ) {
- name = nativeConfirmationField(
- target.installedRoot ? path.basename(target.installedRoot) : 'Pi extension',
- MAX_DISPLAY_NAME_BYTES,
- ) || 'Pi extension';
- }
- const rawVersion = target.view.version
- ? nativeConfirmationField(target.view.version, MAX_DISPLAY_VERSION_BYTES)
- : '';
- const version = rawVersion
- && !path.isAbsolute(rawVersion)
- && !path.win32.isAbsolute(rawVersion)
- && !rawVersion.includes('/')
- && !rawVersion.includes('\\')
- ? rawVersion
- : '';
- const packageLabel = version ? `${name} (${version})` : name;
- return `${packageLabel}\nSHA-256: ${packageFingerprint}`;
- }
-
- /**
- * Captures the Main-inspected package identity shown before enabling it. The
- * later mutation must match the same content fingerprint again under the
- * shared lock; Renderer-provided display fields never enter this object.
- */
- export async function capturePiPackageEnableIdentity(source: string): Promise<PiPackageEnableIdentity> {
- const normalizedSource = requireSource(source);
- return enqueueMutation(async () => {
- await requireState();
- const inspected = await inspectAllPackagesFreshUnderMutationLock();
- const target = await findAffectedInspectedPackage(inspected, normalizedSource);
- if (!target) throw new Error('Pi package is not installed');
- if (!hasToggleableResources(target.view.resources)) {
- throw new Error('Pi package has no launchable resources');
- }
- if (!target.contentFingerprint) {
- throw new Error('Pi package fingerprint is unavailable');
- }
- return {
- displayLabel: piPackageEnableDisplayLabel(target, target.contentFingerprint),
- expectedPackageFingerprint: target.contentFingerprint,
- };
- });
- }
-
async function persistSnapshotUnavailableProjection(
- unavailableRoots: Iterable<readonly [string, SnapshotUnavailableWarning]>,
+ unavailableRoots: Iterable<readonly [string, SnapshotUnavailableRootProjection]>,
+ inspected: readonly InspectedPackage[] = [],
): Promise<boolean> {
const state = await requireState();
- const next: Record<string, SnapshotUnavailableWarning> = {};
- for (const [root, warning] of unavailableRoots) {
- next[path.resolve(root)] = warning;
- }
- const entries = Object.entries(next).sort(([left], [right]) => left.localeCompare(right));
- const currentEntries = Object.entries(state.snapshotUnavailableRoots)
- .sort(([left], [right]) => left.localeCompare(right));
- const changed = entries.length !== currentEntries.length
- || entries.some(([root, warning], index) => (
- root !== currentEntries[index]?.[0] || warning !== currentEntries[index]?.[1]
- ));
+ 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>();
+ for (const pkg of inspected) {
+ const retained = pkg.snapshotUnavailable;
+ if (retained) {
+ // A package-level inspection failure is already bound to its exact
+ // installation. Do not lower it to the shared npm resolver root, which
+ // would quarantine healthy sibling packages that happen to copy together.
+ const key = snapshotUnavailablePackageKey(retained);
+ projectionByIdentity.set(key, retained);
+ durableByIdentity.set(key, retained);
+ }
+ if (!pkg.installedRoot || !pkg.installationIdentity) continue;
+ for (const snapshotRoot of pkg.launch.packageRoots) {
+ const rootProjection = projectionsByRoot.get(path.resolve(snapshotRoot));
+ if (!rootProjection) continue;
+ try {
+ const { canonicalPath, stat } = await resolveStablePackagePath(
+ pkg.installedRoot,
+ 'Pi package root changed while persisting its snapshot failure',
+ );
+ if (path.resolve(canonicalPath) !== path.resolve(pkg.installedRoot)) continue;
+ const currentInstallationIdentity = await packageInstallationIdentity(canonicalPath, stat);
+ if (currentInstallationIdentity !== pkg.installationIdentity) continue;
+ const projection: SnapshotUnavailablePackageProjection = {
+ source: pkg.rawSource,
+ installedRoot: canonicalPath,
+ installationIdentity: currentInstallationIdentity,
+ snapshotRoot: path.resolve(snapshotRoot),
+ warning: rootProjection.warning,
+ };
+ const key = snapshotUnavailablePackageKey(projection);
+ projectionByIdentity.set(key, projection);
+ if (rootProjection.warning === 'inspection-limit' && rootProjection.durable) {
+ durableByIdentity.set(key, {
+ ...projection,
+ warning: 'inspection-limit',
+ retryAfterEpochMs: Date.now() + SNAPSHOT_UNAVAILABLE_RETRY_MS,
+ });
+ }
+ } catch {
+ // Identity cannot be proven, so the failure remains retryable.
+ }
+ }
+ }
+ const nextPackages = sortSnapshotUnavailablePackages([...durableByIdentity.values()]);
+ const changed = JSON.stringify(nextPackages) !== JSON.stringify(state.snapshotUnavailablePackages);
if (changed) {
await writeState({
...state,
@@@ -1981,33 -1931,105 +2303,112 @@@
function snapshotUnavailableWarningForPackage(
pkg: InspectedPackage,
): SnapshotUnavailableWarning | undefined {
- let warning: SnapshotUnavailableWarning | undefined;
- for (const root of pkg.launch.packageRoots) {
- const candidate = snapshotUnavailableRoots.get(path.resolve(root));
- if (candidate === 'inspection-failed') return candidate;
- if (candidate) warning = candidate;
- }
- return warning;
+ if (pkg.snapshotUnavailable) return pkg.snapshotUnavailable.warning;
+ if (!pkg.installedRoot || !pkg.installationIdentity || !pkg.snapshotRoot) return undefined;
+ return snapshotUnavailablePackages.get(snapshotUnavailablePackageKey({
+ source: pkg.rawSource,
+ installedRoot: pkg.installedRoot,
+ installationIdentity: pkg.installationIdentity,
+ snapshotRoot: pkg.snapshotRoot,
+ }))?.warning;
}
+ async function readNativePackageSettingsText(home: string): Promise<string> {
+ const settingsPath = path.join(home, 'settings.json');
+ // This is Pi's native launch configuration, not advisory package metadata.
+ // Follow the same user-managed symlink Pi follows instead of applying Cindy's
+ // package confinement or inspection byte budget to this projection.
+ const handle = await fs.open(settingsPath, 'r');
+ try {
+ const stat = await handle.stat();
+ const followedStat = await fs.stat(settingsPath);
+ if (!stat.isFile() || !sameStableFileIdentity(stat, followedStat)) {
+ throw new Error('Pi package settings changed before reading');
+ }
+ const buffer = await handle.readFile();
+ const [after, followedAfter] = await Promise.all([
+ handle.stat(),
+ fs.stat(settingsPath),
+ ]);
+ if (
+ !sameStableFileIdentity(stat, after)
+ || !sameStableFileIdentity(after, followedAfter)
+ || buffer.length !== after.size
+ ) {
+ throw new Error('Pi package settings changed while reading');
+ }
+ return buffer.toString('utf8');
+ } finally {
+ await handle.close();
+ }
+ }
+
+ async function readNativePackageObjectSpecs(): Promise<Map<string, Record<string, unknown>> | null> {
+ try {
+ const home = await fs.realpath(packageHome());
+ const parsed = JSON.parse(await readNativePackageSettingsText(home)) as { packages?: unknown };
+ if (!Array.isArray(parsed.packages)) return new Map();
+ return new Map(parsed.packages.flatMap((entry) => {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return [];
+ const spec = entry as Record<string, unknown>;
+ return typeof spec.source === 'string' ? [[spec.source, spec] as const] : [];
+ }));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+ }
+
+ export async function resolveManagedPiNativePackagePaths(): Promise<PiNativePackageEntry[]> {
+ if (!getReadyBinaryPath('pi')) return [];
+ const [listed, state] = await Promise.all([
+ runPiPackageListCommand(),
+ readStateWithoutBlockingPi(),
+ ]);
+ const disabled = new Set(state.disabledSources);
+ let objectSpecs: Map<string, Record<string, unknown>> | null = null;
+ try {
+ objectSpecs = await readNativePackageObjectSpecs();
+ } catch {
+ log.warn('Pi package filter settings unavailable', {
+ failureCategory: 'state-unavailable',
+ });
+ }
+ // Feed Pi installed roots while preserving any native object-form filters.
+ // Pi then owns resource discovery without reinstalling the package.
+ const entries = listed.flatMap((pkg): PiNativePackageEntry[] => {
+ if (!pkg.installedPath || isPackageSourceDisabled(disabled, pkg.source)) return [];
+ const spec = objectSpecs?.get(pkg.source);
+ if (spec) return [{ ...spec, source: pkg.installedPath }];
+ // Never silently drop or widen a natively filtered package. If its exact
+ // filter cannot be recovered, fail startup with the existing actionable
+ // package-state error instead of pretending the installed package vanished.
+ if (pkg.filtered) throw new PiPackageStateUnavailableError();
+ return [pkg.installedPath];
+ });
+ return entries.filter((entry, index) => (
+ entries.findIndex((candidate) => JSON.stringify(candidate) === JSON.stringify(entry)) === index
+ ));
+ }
+
export async function resolveManagedPiPackageResources(
- options?: { snapshotRoot: string; snapshotLimits?: PiPackageSnapshotLimits },
+ options?: {
- snapshotRoot: string;
++ snapshotRoot?: string;
+ snapshotLimits?: PiPackageSnapshotLimits;
+ startupTraceId?: string;
+ },
): Promise<PiManagedPackageResources> {
+ const startupTiming = createPiPackageStartupTiming(options?.startupTraceId);
++ const snapshotRoot = options?.snapshotRoot;
if (!getReadyBinaryPath('pi')) {
return { extensions: [], skills: [], promptTemplates: [], packageRoots: [] };
}
try {
const resolveResources = async (forceFresh = false): Promise<PiManagedPackageResources> => {
const inspected = forceFresh
- ? await inspectAllPackagesFreshUnderMutationLock()
+ ? await inspectAllPackagesFreshUnderMutationLock({ startupTiming })
: await inspectAllPackages();
-- if (options) {
++ if (snapshotRoot) {
const staleApprovals = inspected
.filter((pkg) => pkg.staleApproval)
.map((pkg) => pkg.rawSource);
@@@ -2022,18 -2044,7 +2423,25 @@@
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.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 (!options) return resources;
++ 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) {
@@@ -2044,12 -2055,11 +2452,12 @@@
approvalsByRoot.set(root, approvals);
}
}
+ const snapshotStartedAt = Date.now();
try {
-- const snapshotLimits = options.snapshotLimits ?? DEFAULT_SNAPSHOT_LIMITS;
++ const snapshotLimits = options?.snapshotLimits ?? DEFAULT_SNAPSHOT_LIMITS;
let staged = await stageManagedPackageSnapshot(
resources,
-- options.snapshotRoot,
++ snapshotRoot,
snapshotLimits,
);
const stageMetadata = snapshotStageMetadata.get(staged);
@@@ -2106,14 -2101,7 +2514,14 @@@
}
}
if (changedSources.size > 0) {
- await fs.rm(options.snapshotRoot, { recursive: true, force: true });
+ if (startupTiming) {
+ startupTiming.degraded = true;
+ startupTiming.skippedPackageCount = Math.max(
+ startupTiming.skippedPackageCount,
+ changedSources.size,
+ );
+ }
- await fs.rm(options.snapshotRoot, { recursive: true, force: true });
++ await fs.rm(snapshotRoot, { recursive: true, force: true });
await revokeExtensionApproval(changedSources);
await publishPiPackagesChanged();
return { extensions: [], skills: [], promptTemplates: [], packageRoots: [] };
@@@ -2201,7 -2157,7 +2609,7 @@@
}
return staged;
} catch (error) {
-- await fs.rm(options.snapshotRoot, { recursive: true, force: true }).catch(() => undefined);
++ await fs.rm(snapshotRoot, { recursive: true, force: true }).catch(() => undefined);
const warning = error instanceof PiPackageSnapshotLimitError
? 'inspection-limit'
: 'inspection-failed';
@@@ -2217,11 -2167,9 +2625,11 @@@
await publishPiPackagesChanged({ invalidateCache: false });
}
throw error;
+ } finally {
+ recordPiPackageStartupDuration(startupTiming, 'package-snapshot', snapshotStartedAt);
}
};
-- if (options) return await enqueueMutation(() => resolveResources(true));
++ if (snapshotRoot || startupTiming) return await enqueueMutation(() => resolveResources(true));
await mutationTail;
return await resolveResources();
} catch (error) {
@@@ -3090,79 -2984,186 +3491,195 @@@ export async function mutatePiPackage
throw new Error('Relative local Pi package sources require a task working directory');
}
let mutationMayHaveChangedState = false;
- return enqueueMutation(async () => {
- // Never mutate the package tree or replace the durable preference file if
- // the existing state cannot be read. Otherwise a transient read failure
- // could erase explicit disables after a successful package command.
- await requireState();
- if (await persistSnapshotUnavailableProjection([])) {
- mutationMayHaveChangedState = true;
+ let runtimeInvalidationPublished = false;
+ const publishRuntimeInvalidation = async (
+ invalidateCache = false,
+ phase: PiPackageRuntimeInvalidationPhase = 'commit',
+ ): Promise<void> => {
+ if (runtimeInvalidationPublished && phase === 'commit') return;
+ runtimeInvalidationPublished = true;
+ try {
+ // Fence startup and bind runtimes before token I/O yields. A post-build
+ // edge advances the fence again for runtimes admitted during assistance.
+ await hooks?.onRuntimeInvalidationPublished?.(phase);
+ } catch {
+ // Convergence is best-effort after the durable package mutation edge;
+ // never rewrite native success because a local runtime did not close.
+ log.warn('Pi package runtime convergence callback failed', {
+ failureCategory: 'runtime-invalidation-failed',
+ });
}
- // Every mutation starts from one fresh projection acquired after the
- // shared cross-process lock. A packaged/dev/--passive peer may have
- // installed, removed, updated, or changed approval state since this
- // process populated its cache; no mutation may persist decisions derived
- // from that lock-external snapshot.
- const inspectedBeforeMutation = await inspectAllPackagesFreshUnderMutationLock({
- ignorePersistedSnapshotUnavailable: true,
- });
- const preMutationFreshApprovals = await captureExtensionApprovalIdentities(
- inspectedBeforeMutation.filter((pkg) => (
- pkg.view.requiresExtensionApproval !== true
- && pkg.view.resources.some((resource) => resource.kind === 'extension')
- )),
+ await publishPiPackagesChanged({ invalidateCache, runtimeInvalidation: true });
++ // Reset advisory limits only after the runtime fence is published: cache
++ // I/O must not postpone retirement of runtimes that still use old bytes.
++ try {
++ await persistSnapshotUnavailableProjection([]);
++ } catch {
++ log.warn('Pi package mutation committed; inspection cache reset deferred', {
++ failureCategory: 'projection-unavailable',
++ });
++ }
+ };
+ try {
+ return await enqueueMutation(async () => {
+ // Renderer rows with credential/query/fragment-bearing sources carry only a
+ // one-way opaque target. Resolve it from Pi's current native list inside the
+ // mutation lock so the secret source never crosses into Renderer state.
+ const source = await resolvePackageMutationTarget(
+ requestedSource,
+ request.mutationTarget,
+ // Enabling and native commands must resolve an opaque row against Pi's
+ // current roster. Disabling can durably deny the Main-minted opaque target.
+ request.action === 'set-enabled'
+ ? request.enabled === true
+ : Boolean(request.mutationTarget),
);
+ const logSource = projectPackageSource(source).displaySource;
+ try {
+ await reconcilePendingEnabledSources();
+ } catch {
+ // The active journal remains the effective enable source until a later
+ // mutation can fold it into the durable disable ledger.
+ log.warn('Pi pending enable reconciliation deferred');
+ }
+ // Cindy projection state is optional metadata. Native Pi package commands
+ // run before any Cindy inspection; an analyzer timeout or unknown future
+ // package shape therefore cannot delay or veto the upstream command.
+ const inspectedBeforeMutation: InspectedPackage[] = [];
let affectedSource: string | undefined;
+ let installEnableProjectionUnavailable = false;
+ const runNativeMutationCommand = async (args: string[]): Promise<void> => {
+ try {
+ await runPiPackageCommand(args);
+ mutationMayHaveChangedState = true;
+ } catch (error) {
+ mutationMayHaveChangedState = piPackageMutationFailureCategory(error) === 'native-command-failed';
+ throw error;
+ }
+ };
if (request.action === 'install') {
- mutationMayHaveChangedState = true;
- // Reinstalling an existing source can replace executable code. Revoke
- // before invoking Pi so even a partially failed install cannot inherit a
- // stale approval on the next runtime. A successful install is itself the
- // user decision to enable the new bytes.
const previous = await findAffectedInspectedPackage(inspectedBeforeMutation, source);
- await revokeExtensionApproval([
- ...sourceAliases(source),
- ...(previous ? sourceAliases(previous.rawSource) : []),
- ]);
- invalidateInspectionCache();
- await runPiPackageCommand(['install', source, '--no-approve']);
+ // The package command may run dependency and build scripts. Keep the old
+ // optional snapshot identity until that command succeeds. Native Pi
+ // enablement never depends on this Cindy metadata.
+ await runNativeMutationCommand(['install', source, '--no-approve']);
+ const installAliases = [...new Set((await Promise.all([
+ sourceAliasesWithCanonical(requestedSource),
+ sourceAliasesWithCanonical(source),
+ ])).flat())];
+ let effectiveInstallAliases = installAliases;
+ let installEnableStateCommitted = false;
+ // Explicit reinstall means enabled only after its precise aliases leave
+ // the durable disable ledger. Reconcile that effective state before the
+ // runtime fence so a startup admitted by the new generation cannot read
+ // the old disable projection and survive without the reinstalled package.
+ try {
+ effectiveInstallAliases = await expandAliasesWithDisabledSources(installAliases);
+ await clearDisabledPackageSources(effectiveInstallAliases);
+ installEnableStateCommitted = true;
+ const pending = await readPendingEnabledSources();
+ for (const alias of effectiveInstallAliases) pending.delete(alias);
+ await writePendingEnabledSources(pending);
+ } catch (error) {
+ // Only a failed authoritative state commit needs the existing pending
+ // journal fallback. Once the disable ledger is clear, journal cleanup
+ // is auxiliary and cannot turn the committed enable into a false
+ // projection-unavailable result.
+ if (!installEnableStateCommitted) {
+ try {
+ await persistPendingEnabledSources(effectiveInstallAliases);
+ } catch {
+ // Native install remains committed, but a process-local override
+ // cannot prove enabled state to another Main or after restart.
+ installEnableProjectionUnavailable = true;
+ }
+ }
+ log.warn('Pi package installed; enable-ledger reconciliation deferred', {
+ action: 'install',
+ failureCategory: 'state-unavailable',
+ });
+ }
+ await publishRuntimeInvalidation();
invalidateInspectionCache();
- const inspectedAfterInstall = await inspectAllPackages();
- const affected = await findAffectedInspectedPackage(inspectedAfterInstall, source);
- affectedSource = affected?.rawSource;
- await persistEnabledExtensionApprovals({
- inspected: inspectedAfterInstall,
- rebaseSources: await unchangedExtensionClosureSources(
- preMutationFreshApprovals,
- inspectedAfterInstall,
- ),
- ...(affected ? { enable: affected } : {}),
- });
+ let inspectedAfterInstall: InspectedPackage[] = [];
+ try {
+ inspectedAfterInstall = await inspectAllPackages();
+ } catch {
+ log.warn('Pi package installed; Cindy post-install analysis unavailable', {
+ action: 'install',
+ failureCategory: 'projection-unavailable',
+ });
+ }
+ let affected = await findAffectedInspectedPackage(inspectedAfterInstall, source);
+ if (affected?.missingDeclaredExtensions) {
+ const buildTarget = affected;
+ // Best-effort convenience for Git packages that omit generated output.
+ // Pi already accepted the install, so a Cindy-added build attempt may
+ // improve it but can never reverse that native success.
+ let built = false;
+ try {
+ built = await buildMissingDeclaredPiExtensions(buildTarget);
+ } catch (error) {
+ log.warn('optional Pi package build assistance failed', {
+ failureCategory: piPackageMutationFailureCategory(error),
+ mayHaveChangedState: true,
+ });
+ } finally {
+ await publishRuntimeInvalidation(true, 'post-build');
+ }
+ if (built) {
+ invalidateInspectionCache();
+ inspectedAfterInstall = await inspectAllPackages();
+ affected = await findAffectedInspectedPackage(inspectedAfterInstall, source);
+ }
+ }
+ affectedSource = affected?.rawSource ?? previous?.rawSource ?? source;
+ const approvalAliases = affected
+ ? [...new Set([...installAliases, ...await sourceAliasesWithCanonical(affected.rawSource)])]
+ : installAliases;
+ try {
+ await revokeExtensionApproval(approvalAliases);
+ await persistEnabledExtensionApprovals({
+ ...(affected ? { enable: affected } : {}),
+ });
+ } catch (error) {
+ log.warn('Pi package installed but optional Cindy snapshot metadata refresh failed', {
+ source: logSource,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
} else if (request.action === 'remove') {
- mutationMayHaveChangedState = true;
const previous = await findAffectedInspectedPackage(inspectedBeforeMutation, source);
- await runPiPackageCommand([
+ await runNativeMutationCommand([
'remove',
mutationCommandSource(source, previous),
'--no-approve',
]);
- const state = await requireState();
- const removedSources = new Set([
- ...sourceAliases(source),
- ...(previous ? sourceAliases(previous.rawSource) : []),
- ]);
- await writeState({
- version: STATE_VERSION,
- disabledSources: state.disabledSources.filter((item) => !removedSources.has(item)),
- approvedExtensionSources: state.approvedExtensionSources.filter((item) => !removedSources.has(item)),
- approvedExtensionFingerprints: Object.fromEntries(
- Object.entries(state.approvedExtensionFingerprints)
- .filter(([item]) => !removedSources.has(item)),
- ),
- snapshotUnavailablePackages: state.snapshotUnavailablePackages,
- });
+ await publishRuntimeInvalidation();
+ try {
+ const state = await requireState();
+ const removedSources = new Set([
+ ...sourceAliases(source),
+ packageMutationTarget(source),
+ ...(previous ? [...sourceAliases(previous.rawSource), packageMutationTarget(previous.rawSource)] : []),
+ ]);
+ await writeState({
+ version: STATE_VERSION,
+ disabledSources: state.disabledSources.filter((item) => !removedSources.has(item)),
+ approvedExtensionSources: state.approvedExtensionSources.filter((item) => !removedSources.has(item)),
+ approvedExtensionFingerprints: Object.fromEntries(
+ Object.entries(state.approvedExtensionFingerprints)
+ .filter(([item]) => !removedSources.has(item)),
+ ),
- snapshotUnavailableRoots: state.snapshotUnavailableRoots,
++ snapshotUnavailablePackages: state.snapshotUnavailablePackages,
+ });
+ } catch (error) {
+ log.warn('Pi package removed but Cindy projection cleanup failed', {
+ source: logSource,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
} else if (request.action === 'update') {
- mutationMayHaveChangedState = true;
const previous = await findAffectedInspectedPackage(inspectedBeforeMutation, source);
const updateAliases = [
...sourceAliases(source),
@@@ -3237,16 -3300,84 +3816,84 @@@
approvedExtensionFingerprints: Object.fromEntries(
Object.entries(approvedFingerprints).sort(([left], [right]) => left.localeCompare(right)),
),
- snapshotUnavailablePackages: state.snapshotUnavailablePackages,
- snapshotUnavailableRoots: state.snapshotUnavailableRoots,
++ snapshotUnavailablePackages: [],
});
+ // Only a completed atomic replacement is a durable state enablement edge.
+ mutationMayHaveChangedState = true;
+ await publishRuntimeInvalidation();
}
invalidateInspectionCache();
- const result = await listPiPackagesNow();
- const affectedPackage = affectedSource
- ? findAffectedPiPackage(result.packages, affectedSource)
- : findAffectedPiPackage(result.packages, source);
- const mutationResult = { ...result, changed: true, ...(affectedPackage ? { affectedPackage } : {}) };
- await publishPiPackagesChanged({ invalidateCache: false });
+ let result: PiPackageListResult;
+ let projectionUnavailable = false;
+ try {
+ result = await listPiPackagesNow();
+ } catch {
+ log.warn('Pi package mutation succeeded; Cindy list projection unavailable', {
+ action: request.action,
+ failureCategory: 'projection-unavailable',
+ });
+ result = { available: false, packages: [] };
+ projectionUnavailable = true;
+ }
+ if (installEnableProjectionUnavailable) {
+ // Do not publish the stale disable ledger or a process-local override as
+ // an authoritative enabled result when neither existing store converged.
+ result = { available: false, packages: [] };
+ projectionUnavailable = true;
+ }
+ const affectedLookupSource = affectedSource ?? source;
+ const affectedPackage = findAffectedPiPackage(result.packages, affectedLookupSource)
+ ?? result.packages.find((pkg) => (
+ pkg.mutationTarget === request.mutationTarget
+ || pkg.mutationTarget === packageMutationTarget(affectedLookupSource)
+ ));
+ if (request.action === 'install'
+ && !installEnableProjectionUnavailable
+ && affectedPackage?.enabled !== true) {
+ // Native Pi already accepted the package. Keep a useful receipt even if
+ // Cindy could not project its new/unknown manifest shape.
+ const fallbackProjection = projectPackageSource(source);
+ const fallbackSource = fallbackProjection.displaySource;
+ const fallback: PiPackageView = {
+ source: fallbackSource,
+ ...(fallbackSource !== source ? { mutationTarget: packageMutationTarget(source) } : {}),
+ name: fallbackSource,
+ enabled: true,
+ resources: [],
+ warning: 'inspection-failed',
+ };
+ const mutationResult = {
+ ...result,
+ changed: true,
+ packages: [...result.packages, fallback],
+ affectedPackage: fallback,
+ ...(projectionUnavailable ? { projectionUnavailable: true as const } : {}),
+ };
+ await publishRuntimeInvalidation();
+ return mutationResult;
+ }
+ if (request.action === 'set-enabled' && request.enabled === true) {
+ // Persist optional snapshot metadata only after the user-visible enable
+ // result is already determined from Pi's installed package state. Any
+ // inspection/fingerprint failure is swallowed and cannot veto enablement.
+ try {
+ const inspected = await inspectAllPackages();
+ const target = await findAffectedInspectedPackage(inspected, affectedSource ?? source);
+ if (target) await persistEnabledExtensionApprovals({ enable: target });
+ } catch (error) {
+ log.warn('Pi package enabled; optional Cindy snapshot metadata unavailable', {
+ source: logSource,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ const mutationResult = {
+ ...result,
+ changed: true,
+ ...(affectedPackage ? { affectedPackage } : {}),
+ ...(projectionUnavailable ? { projectionUnavailable: true as const } : {}),
+ };
+ await publishRuntimeInvalidation();
return mutationResult;
}, async () => {
// Any action may already have changed Pi's package tree or Cindy's state
diff --cc packages/maker-core/src/agents/base-agent.ts
index 0f674afced,40ce356d4d..7d5c2d9f3c
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@@ -543,16 -577,11 +577,15 @@@ export interface AgentDeps
resolvePiAgentHome?: (remoteHostId?: string | null) => string | undefined;
/**
- * Pi-only: Cindy-owned packages explicitly enabled for a new runtime on this device.
- * The host owns package installation, compatibility inspection, persistence,
- * and path confinement. Device-link remote control still executes on this host
- * and therefore uses these resources. SSH remoteHostId and Review runtimes do not.
+ * Pi-only: advisory metadata for Cindy UI/command projection. This resolver
+ * may inspect or snapshot known resources, but its result is never the launch
+ * allowlist; resolvePiNativePackagePaths preserves Pi-native discovery.
*/
- resolvePiManagedPackageResources?: (options?: { snapshotRoot: string }) => Promise<{
+ resolvePiManagedPackageResources?: (options?: {
- snapshotRoot: string;
++ snapshotRoot?: string;
+ /** Redacted per-start correlation id for structured startup timing logs. */
+ startupTraceId?: string;
+ }) => Promise<{
extensions: string[];
skills: Array<{ path: string; name: string; description?: string }>;
promptTemplates: string[];
diff --cc packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts
index 7b27957d79,7b27957d79..dfe6658666
--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentForeground.test.ts
@@@ -23,7 -23,7 +23,7 @@@ async function fixture()
const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-pi-subagent-foreground-'));
roots.push(root);
const configHome = path.join(root, 'pi-home');
-- const extensions = path.join(configHome, 'extensions');
++ const extensions = path.join(configHome, 'internal-extensions');
const runRoot = path.join(root, 'runs');
await mkdir(extensions, { recursive: true });
await mkdir(runRoot, { recursive: true });
diff --cc packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index d74ff0428c,0b09403831..1d1e3416ed
--- 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
@@@ -12,8 -12,17 +12,18 @@@
* resume 路径、启动 RPC 也不会即时拒),控制流本身才是被测对象。
*/
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+ import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+ } from 'node:fs';
+import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@@ -2296,10 -2347,10 +2348,12 @@@ describe('PiAgent.startSession failure
sessionId: 'approved',
}));
expect(resolvePiManagedPackageResources).toHaveBeenCalledOnce();
- expect(resolvePiManagedPackageResources).toHaveBeenCalledWith(expect.objectContaining({
- snapshotRoot: path.join(approvedHome, 'managed-packages'),
- expect(resolvePiManagedPackageResources).toHaveBeenCalledWith();
++ expect(resolvePiManagedPackageResources).toHaveBeenCalledWith({
+ startupTraceId: expect.stringMatching(/^[a-f0-9]{16}$/),
- }));
++ });
+ expect(resolvePiNativePackagePaths).toHaveBeenCalledOnce();
+ expect(JSON.parse(readFileSync(path.join(approvedHome, 'settings.json'), 'utf8')))
+ .toMatchObject({ packages: [packageRoot] });
await vi.waitFor(() => {
expect(approvedHandle.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
status: 'approved', approvalRevision: 'rev-approved-only', requestedSkillCount: 1,
diff --cc packages/maker-core/src/agents/pi/cindy-subagent-source.ts
index feaed69a34,feaed69a34..75bbcec794
--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts
@@@ -1,5 -1,5 +1,5 @@@
/**
-- * cindy-subagent —— 写进 pi `PI_CODING_AGENT_DIR/extensions/` 的扩展源码(字符串常量)。
++ * cindy-subagent —— 写进 pi `PI_CODING_AGENT_DIR/internal-extensions/` 的扩展源码(字符串常量)。
*
* 为什么是 Cindy 自己的实现,而不是装社区包:
* - pi 上游刻意不内置子代理,社区(`pi-subagents` 等)一律以「扩展 + 子 pi 进程」补齐。
@@@ -14,7 -14,7 +14,7 @@@
*
* 安全形态(重要,别当冗余删掉):
* - 子进程**继承 `PI_CODING_AGENT_DIR`**,但显式 `--no-extensions` 关闭隐式发现,再只用
-- * `--extension <configHome>/extensions/cindy-bridge.ts` 回装权限门。这样 project extension
++ * `--extension <runDir>/cindy-bridge.ts` 回装从内部扩展目录复制的权限门。这样 project extension
* 永远不会执行,bridge 的 tool_call 拦截 + 凭证路径硬拦仍对子代理生效。
* - 只读角色固定 read/grep/find/ls;worker/custom-write 才拿 edit/write/bash。Ask/Auto
* 下 bridge 产生的 `extension_ui_request` 由 durable runner 记录,父 PI adapter 转交
@@@ -896,7 -896,7 +896,7 @@@ async function launchDurableRun(binary
try { chmodSync(permissionFile, 0o600); } catch (err) { /* best effort on Windows */ }
mkdirSync(childConfigHome, { recursive: true, mode: 0o700 });
copyFileSync(join(configHome, 'models.json'), join(childConfigHome, 'models.json'));
-- copyFileSync(join(configHome, 'extensions', 'cindy-bridge.ts'), bridgeExtension);
++ copyFileSync(join(configHome, 'internal-extensions', 'cindy-bridge.ts'), bridgeExtension);
try { chmodSync(join(childConfigHome, 'models.json'), 0o600); } catch (err) { /* best effort on Windows */ }
try { chmodSync(bridgeExtension, 0o600); } catch (err) { /* best effort on Windows */ }
mkdirSync(childSessionRoot, { recursive: true, mode: 0o700 });
diff --cc packages/maker-core/src/agents/pi/index.ts
index e2a59fa937,608ff860af..7dcd5f04a3
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@@ -3000,16 -2898,50 +3234,50 @@@ export class PiAgent extends BaseAgent
promptTemplates: string[];
packageRoots: string[];
} = { extensions: [], skills: [], promptTemplates: [], packageRoots: [] };
- if (!reviewMode && !opts.remoteHostId && this.deps.resolvePiManagedPackageResources) {
- try {
- managedPackageResources = await this.deps.resolvePiManagedPackageResources({
- snapshotRoot: path.join(configHome, 'managed-packages'),
- startupTraceId,
- });
- } catch {
- this.deps.logger.warn('pi managed package resolver failed closed', {
- sessionId: opts.sessionId ?? null,
- });
+ let nativePackagePaths: PiNativePackageEntry[] = [];
+ if (!reviewMode && !opts.remoteHostId) {
+ if (this.deps.resolvePiNativePackagePaths) {
+ try {
+ nativePackagePaths = await this.deps.resolvePiNativePackagePaths();
+ await this.writePiRuntimeSettings(configHome, {
+ contextWindow: startupContextWindow,
+ piCompactionPct: sessionPiAutoCompactPct,
+ packages: nativePackagePaths,
+ });
+ } catch {
+ // Projection runs after config/runtime files and the MCP session route
+ // exist, but before a handle owns their normal close path. Roll back
+ // exactly that unpublished startup state before surfacing the failure.
+ try {
+ disposeSessionCtx?.();
+ } catch {
+ /* best-effort: cleanup failure must not mask package-state failure */
+ }
+ disposeSessionCtx = undefined;
+ cleanupConfigHome();
+ cleanupRuntimeFiles();
+ // Do not substitute Cindy's static analyzer as an allowlist or launch
+ // with an empty package projection. That would silently drop native
+ // Pi packages while claiming the task started normally.
+ this.deps.logger.warn('pi native package projection unavailable', {
+ sessionId: opts.sessionId ?? null,
+ failureCategory: 'state-unavailable',
+ });
+ const strings = resolvePiExtensionUiStrings(this.deps);
+ throw new Error(
+ strings.mutationFailure?.['state-unavailable'] ?? strings.mutationFailed,
+ );
+ }
+ }
+ if (this.deps.resolvePiManagedPackageResources) {
+ try {
+ // Advisory metadata only (command palette, labels, diagnostics).
- managedPackageResources = await this.deps.resolvePiManagedPackageResources();
++ managedPackageResources = await this.deps.resolvePiManagedPackageResources({ startupTraceId });
+ } catch {
+ this.deps.logger.warn('pi managed package metadata unavailable', {
+ sessionId: opts.sessionId ?? null,
+ });
+ }
}
}