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): detect in-place skill changes while snapshotting

nana0f255c725639
diff --cc packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
index 23179d94d6,0000000000..7f09209fa8
mode 100644,000000..100644
--- a/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/project-resource-assembly.test.ts
@@@ -1,583 -1,0 +1,632 @@@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ constants,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ renameSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { promises as fsPromises } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import {
+ assembleApprovedPiProjectResources,
+ reconcilePiProjectResourceRuntime,
+ stageApprovedPiProjectResources,
+ unavailablePiProjectResourceAssembly,
+} from '../project-resource-assembly.js';
+import { piProjectKey } from '../project-trust.js';
+import type {
+ PiProjectApprovalSnapshot,
+ PiProjectTrustInputSnapshot,
+} from '../../../types/pi-project-trust.js';
+
+function inputFor(
+ workingDir: string,
+ approval: PiProjectApprovalSnapshot | null,
+ skills = [`${workingDir}/.pi/skills/demo`],
+): PiProjectTrustInputSnapshot {
+ const repoRoot = workingDir.split('/').slice(0, 3).join('/');
+ return {
+ identity: {
+ workingDir,
+ canonicalWorkingDir: workingDir,
+ canonicalRepoRoot: repoRoot,
+ repoRootStatus: 'resolved',
+ platform: 'posix',
+ canonicalPathEncoding: 'utf8-lossless',
+ },
+ approval,
+ discovered: {
+ skills,
+ canonicalSkillEvidence: skills.map((skillPath) => ({
+ discoveredPath: skillPath,
+ canonicalPath: skillPath,
+ })),
+ settings: [`${workingDir}/.pi/settings.json`],
+ packages: [`${workingDir}/.pi/settings.json#packages`],
+ extensions: [`${workingDir}/.pi/extensions/project.ts`],
+ },
+ };
+}
+
+const approved = (workingDir: string, revision: string): PiProjectApprovalSnapshot => ({
+ status: 'approved',
+ scope: 'working-dir',
+ scopeKey: `${workingDir.split('/').slice(0, 3).join('/')}\0${workingDir}`,
+ revision,
+});
+
+function inputForRepoRoot(
+ workingDir: string,
+ revision: string,
+ skills: readonly string[],
+): PiProjectTrustInputSnapshot {
+ const identity: PiProjectTrustInputSnapshot['identity'] = {
+ workingDir,
+ canonicalWorkingDir: workingDir,
+ canonicalRepoRoot: workingDir,
+ repoRootStatus: 'resolved',
+ platform: process.platform === 'win32' ? 'win32' : 'posix',
+ canonicalPathEncoding: process.platform === 'win32' ? 'utf16-lossless' : 'utf8-lossless',
+ ...(process.platform === 'win32'
+ ? { windowsCaseComparison: 'ordinal-insensitive' as const }
+ : {}),
+ };
+ const scopeKey = piProjectKey(identity);
+ if (!scopeKey) throw new Error('test project identity must be canonical');
+ return {
+ identity,
+ approval: {
+ status: 'approved',
+ scope: 'working-dir',
+ scopeKey,
+ revision,
+ },
+ discovered: {
+ skills,
+ canonicalSkillEvidence: skills.map((skillPath) => ({
+ discoveredPath: skillPath,
+ canonicalPath: skillPath,
+ })),
+ settings: [],
+ packages: [],
+ extensions: [],
+ },
+ };
+}
+
+const available = {
+ stat: async (candidate: string) => ({
+ isDirectory: () => !candidate.toLowerCase().endsWith('.md'),
+ isFile: () => candidate.toLowerCase().endsWith('.md'),
+ }),
+ realpath: async (skillPath: string) => skillPath,
+ findNearestGitRoot: async (workingDir: string) => workingDir.split('/').slice(0, 3).join('/'),
+};
+
+describe('Pi approved project resource assembly', () => {
+ it('freezes only explicitly eligible project skill paths', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, workingDir, available);
+
+ expect(result.skillPaths).toEqual(input.discovered.skills);
+ expect(result.diagnostic).toEqual({
+ status: 'approved',
+ reason: 'approval-matched',
+ approvalRevision: 'rev-a',
+ requestedSkillCount: 1,
+ });
+ expect(result.decision?.launch).toEqual({
+ approve: false,
+ writeTrustJson: false,
+ inheritUserPiHome: false,
+ allowPackages: false,
+ allowExtensions: false,
+ });
+ expect(result.decision?.eligibleSettingsPaths).toEqual([]);
+ expect(result.decision?.settingsProjection).toBeNull();
+ expect(Object.isFrozen(result.skillPaths)).toBe(true);
+ expect(Object.isFrozen(result.diagnostic)).toBe(true);
+ expect(Object.isFrozen(result)).toBe(true);
+ });
+
+ it.each([
+ ['missing', null, 'approval-missing'],
+ ['unapproved', { status: 'unapproved', reason: 'user-denied' }, 'user-denied'],
+ ['revoked', { status: 'revoked', revision: 'revoked-2', reason: 'user-revoked' }, 'user-revoked'],
+ ['stale', { status: 'stale', revision: 'stale-2', reason: 'repo-moved' }, 'repo-moved'],
+ ['unavailable', { status: 'unavailable', reason: 'authority-offline' }, 'authority-offline'],
+ ] as const)('keeps %s approval discovered and fail-closed', async (_label, approval, reason) => {
+ const workingDir = '/repo-a/packages/app';
+ const result = await assembleApprovedPiProjectResources(
+ inputFor(workingDir, approval),
+ workingDir,
+ available,
+ );
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe(reason);
+ expect(result.decision?.resources.skills).toBe('discovered');
+ });
+
+ it('diagnoses a missing authority without manufacturing trust input', () => {
+ expect(unavailablePiProjectResourceAssembly('approval-resolver-unavailable')).toEqual({
+ decision: null,
+ skillPaths: [],
+ launchSkillPaths: [],
+ diagnostic: {
+ status: 'unavailable',
+ reason: 'approval-resolver-unavailable',
+ approvalRevision: null,
+ requestedSkillCount: 0,
+ },
+ });
+ });
+
+ it('invalidates the entire approved set when one path disappeared before launch', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const first = `${workingDir}/.pi/skills/first`;
+ const missing = `${workingDir}/.agents/skills/missing`;
+ const stat = vi.fn(async (skillPath: string) => {
+ if (skillPath === missing) throw new Error('ENOENT');
+ return { isDirectory: () => true, isFile: () => false };
+ });
+ const result = await assembleApprovedPiProjectResources(
+ inputFor(workingDir, approved(workingDir, 'rev-a'), [first, missing]),
+ workingDir,
+ { ...available, stat },
+ );
+
+ expect(stat).toHaveBeenCalled();
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skill-path-unavailable');
+ expect(result.decision?.resources.skills).toBe('eligible');
+ });
+
+ it('diagnoses canonical evidence changes without partially loading the remaining skill', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ input.discovered.canonicalSkillEvidence = [{
+ discoveredPath: input.discovered.skills[0]!,
+ canonicalPath: '/outside/retargeted-skill',
+ }];
+ const result = await assembleApprovedPiProjectResources(input, workingDir, available);
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skills-ineligible');
+ expect(result.decision?.resources.skills).toBe('discovered');
+ });
+
+ it('keeps concurrent workingDir approval snapshots isolated', async () => {
+ const firstDir = '/repo-a/packages/app';
+ const secondDir = '/repo-b/packages/app';
+ const [first, second] = await Promise.all([
+ assembleApprovedPiProjectResources(
+ inputFor(firstDir, approved(firstDir, 'rev-a')),
+ firstDir,
+ available,
+ ),
+ assembleApprovedPiProjectResources(
+ inputFor(secondDir, { status: 'revoked', revision: 'rev-b', reason: 'user-revoked' }),
+ secondDir,
+ available,
+ ),
+ ]);
+
+ expect(first.skillPaths).toEqual([`${firstDir}/.pi/skills/demo`]);
+ expect(first.diagnostic.approvalRevision).toBe('rev-a');
+ expect(second.skillPaths).toEqual([]);
+ expect(second.diagnostic).toMatchObject({
+ status: 'revoked',
+ reason: 'user-revoked',
+ approvalRevision: 'rev-b',
+ });
+ });
+
+ it('invalidates the whole set when a canonical skill path is retargeted after approval', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
+ realpath: async (candidate) => candidate === input.discovered.skills[0]
+ ? '/outside/retargeted-skill'
+ : candidate,
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skill-path-changed');
+ });
+
+ it('invalidates a skill whose SKILL.md entrypoint is retargeted after discovery', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const skillFile = `${input.discovered.skills[0]}/SKILL.md`;
+ const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
+ realpath: async (candidate) => candidate === skillFile
+ ? '/outside/retargeted-SKILL.md'
+ : candidate,
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skill-path-changed');
+ });
+
+ it('allows a directory SKILL.md symlink that still resolves inside the approved repo', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const skillFile = `${input.discovered.skills[0]}/SKILL.md`;
+ const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
+ realpath: async (candidate) => candidate === skillFile
+ ? '/repo-a/packages/shared/demo.md'
+ : candidate,
+ });
+
+ expect(result.skillPaths).toEqual(input.discovered.skills);
+ expect(result.diagnostic.reason).toBe('approval-matched');
+ });
+
+ it('keeps a single-file markdown skill discovered because Cindy project scanning only approves directories', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const skillFile = `${workingDir}/.pi/skills/demo.md`;
+ const result = await assembleApprovedPiProjectResources(
+ inputFor(workingDir, approved(workingDir, 'rev-a'), [skillFile]),
+ workingDir,
+ available,
+ );
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.launchSkillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skill-path-unavailable');
+ });
+
+ it('pins a complete directory skill inside configHome before Pi receives it', async () => {
+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-stage-')));
+ const configHome = path.join(root, 'config-home');
+ const workingDir = path.join(root, 'repo', 'packages', 'app');
+ const skillPath = path.join(workingDir, '.pi', 'skills', 'demo');
+ try {
+ mkdirSync(path.join(workingDir, '.git'), { recursive: true });
+ mkdirSync(path.join(skillPath, 'assets'), { recursive: true });
+ mkdirSync(configHome, { recursive: true });
+ writeFileSync(path.join(skillPath, 'SKILL.md'), '# approved snapshot\n');
+ writeFileSync(path.join(skillPath, 'assets', 'fixture.txt'), 'snapshot asset\n');
+ const input = inputForRepoRoot(workingDir, 'rev-stage', [skillPath]);
+ const assembled = await assembleApprovedPiProjectResources(input, workingDir);
+ const openSpy = vi.spyOn(fsPromises, 'open');
+ const staged = await stageApprovedPiProjectResources(assembled, configHome);
+
+ expect(staged.skillPaths).toEqual([skillPath]);
+ expect(staged.launchSkillPaths).toHaveLength(1);
+ expect(staged.launchSkillPaths[0]).toBe(
+ path.join(configHome, 'project-resources', 'skills', '0', 'demo'),
+ );
+ expect(readFileSync(path.join(staged.launchSkillPaths[0]!, 'SKILL.md'), 'utf8'))
+ .toBe('# approved snapshot\n');
+ expect(readFileSync(path.join(staged.launchSkillPaths[0]!, 'assets', 'fixture.txt'), 'utf8'))
+ .toBe('snapshot asset\n');
+ const nonBlockingFlag = constants.O_NONBLOCK ?? 0;
+ expect((openSpy.mock.calls[0]?.[1] as number) & nonBlockingFlag)
+ .toBe(nonBlockingFlag);
+ } finally {
+ vi.restoreAllMocks();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('keeps the launch snapshot immutable when the project skill is retargeted before spawn', async () => {
+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-retarget-')));
+ const configHome = path.join(root, 'config-home');
+ const workingDir = path.join(root, 'repo');
+ const skillPath = path.join(workingDir, '.pi', 'skills', 'demo');
+ const outsideSkill = path.join(root, 'outside-skill');
+ try {
+ mkdirSync(path.join(workingDir, '.git'), { recursive: true });
+ mkdirSync(skillPath, { recursive: true });
+ mkdirSync(outsideSkill, { recursive: true });
+ mkdirSync(configHome, { recursive: true });
+ writeFileSync(path.join(skillPath, 'SKILL.md'), '# approved\n');
+ writeFileSync(path.join(outsideSkill, 'SKILL.md'), '# outside\n');
+ const assembled = await assembleApprovedPiProjectResources(
+ inputForRepoRoot(workingDir, 'rev-retarget', [skillPath]),
+ workingDir,
+ );
+ const staged = await stageApprovedPiProjectResources(assembled, configHome);
+
+ renameSync(skillPath, `${skillPath}-approved-old`);
+ symlinkSync(outsideSkill, skillPath, process.platform === 'win32' ? 'junction' : 'dir');
+
+ expect(readFileSync(path.join(staged.launchSkillPaths[0]!, 'SKILL.md'), 'utf8'))
+ .toBe('# approved\n');
+ expect(staged.launchSkillPaths[0]).not.toBe(skillPath);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
++ it('fails closed when an approved file is overwritten through the same inode while copying', async () => {
++ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-rewrite-')));
++ const configHome = path.join(root, 'config-home');
++ const workingDir = path.join(root, 'repo');
++ const skillPath = path.join(workingDir, '.pi', 'skills', 'demo');
++ const skillFile = path.join(skillPath, 'SKILL.md');
++ try {
++ mkdirSync(path.join(workingDir, '.git'), { recursive: true });
++ mkdirSync(skillPath, { recursive: true });
++ mkdirSync(configHome, { recursive: true });
++ writeFileSync(skillFile, '# approved content\n');
++ const assembled = await assembleApprovedPiProjectResources(
++ inputForRepoRoot(workingDir, 'rev-rewrite', [skillPath]),
++ workingDir,
++ );
++ const realOpen = fsPromises.open.bind(fsPromises);
++ let overwritten = false;
++ vi.spyOn(fsPromises, 'open').mockImplementation(async (candidate, flags, mode) => {
++ const handle = await realOpen(candidate, flags, mode);
++ if (String(candidate) !== skillFile) return handle;
++ const createReadStream = handle.createReadStream.bind(handle);
++ handle.createReadStream = ((options) => {
++ const stream = createReadStream(options);
++ if (!overwritten) {
++ stream.once('end', () => {
++ overwritten = true;
++ writeFileSync(skillFile, '# replacement content written in place\n');
++ });
++ }
++ return stream;
++ }) as typeof handle.createReadStream;
++ return handle;
++ });
++
++ const staged = await stageApprovedPiProjectResources(assembled, configHome);
++
++ expect(overwritten).toBe(true);
++ expect(staged.skillPaths).toEqual([]);
++ expect(staged.launchSkillPaths).toEqual([]);
++ expect(staged.diagnostic).toMatchObject({
++ reason: 'approved-skill-snapshot-failed',
++ requestedSkillCount: 0,
++ });
++ } finally {
++ vi.restoreAllMocks();
++ rmSync(root, { recursive: true, force: true });
++ }
++ });
++
+ it('fails the entire snapshot closed when a nested symlink escapes the approved repo', async () => {
+ const root = realpathSync.native(mkdtempSync(path.join(tmpdir(), 'pi-project-resource-escape-')));
+ const configHome = path.join(root, 'config-home');
+ const workingDir = path.join(root, 'repo');
+ const first = path.join(workingDir, '.pi', 'skills', 'first');
+ const second = path.join(workingDir, '.pi', 'skills', 'second');
+ const outsideDir = path.join(root, 'outside-dir');
+ try {
+ mkdirSync(path.join(workingDir, '.git'), { recursive: true });
+ mkdirSync(first, { recursive: true });
+ mkdirSync(second, { recursive: true });
+ mkdirSync(configHome, { recursive: true });
+ writeFileSync(path.join(first, 'SKILL.md'), '# first\n');
+ writeFileSync(path.join(second, 'SKILL.md'), '# second\n');
+ mkdirSync(outsideDir, { recursive: true });
+ writeFileSync(path.join(outsideDir, 'outside.txt'), 'outside\n');
+ symlinkSync(
+ outsideDir,
+ path.join(second, 'outside-dir'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ const assembled = await assembleApprovedPiProjectResources(
+ inputForRepoRoot(workingDir, 'rev-escape', [first, second]),
+ workingDir,
+ );
+ const staged = await stageApprovedPiProjectResources(assembled, configHome);
+
+ expect(staged.skillPaths).toEqual([]);
+ expect(staged.launchSkillPaths).toEqual([]);
+ expect(staged.diagnostic).toMatchObject({
+ reason: 'approved-skill-snapshot-failed',
+ requestedSkillCount: 0,
+ });
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ it('invalidates a skill whose SKILL.md entrypoint disappeared before launch', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const skillFile = `${input.discovered.skills[0]}/SKILL.md`;
+ const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
+ stat: async (candidate) => {
+ if (candidate === skillFile) throw new Error('ENOENT');
+ return available.stat(candidate);
+ },
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-skill-path-unavailable');
+ });
+
+ it('invalidates approved skills when the lexical workingDir is retargeted', async () => {
+ const workingDir = '/repo-a/packages/app-link';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
+ realpath: async (candidate) => candidate === input.identity.workingDir
+ ? '/outside/retargeted-working-dir'
+ : candidate,
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic.reason).toBe('approved-project-path-changed');
+ });
+
+ it('rejects an internally valid approval snapshot for another requested workingDir', async () => {
+ const approvedDir = '/repo-a/packages/app';
+ const requestedDir = '/repo-b/packages/app';
+ const input = inputFor(approvedDir, approved(approvedDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(
+ input,
+ requestedDir,
+ available,
+ );
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic).toMatchObject({
+ status: 'approved',
+ reason: 'approval-working-dir-mismatch',
+ approvalRevision: 'rev-a',
+ requestedSkillCount: 0,
+ });
+ });
+
+ it('rejects an approval snapshot when a nearer Git root appears before launch', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const input = inputFor(workingDir, approved(workingDir, 'rev-a'));
+ const result = await assembleApprovedPiProjectResources(input, workingDir, {
+ ...available,
+ findNearestGitRoot: async () => workingDir,
+ });
+
+ expect(result.skillPaths).toEqual([]);
+ expect(result.diagnostic).toMatchObject({
+ status: 'approved',
+ reason: 'approved-repo-root-changed',
+ approvalRevision: 'rev-a',
+ requestedSkillCount: 0,
+ });
+ });
+
+ it('reports loaded only when this get_commands catalog confirms every explicit path', async () => {
+ const workingDir = '/repo-a/packages/app';
+ const assembly = await assembleApprovedPiProjectResources(
+ inputFor(workingDir, approved(workingDir, 'rev-a')),
+ workingDir,
+ available,
+ );
+ const skillPath = assembly.skillPaths[0]!;
+ const runtimeAssembly = {
+ ...assembly,
+ launchSkillPaths: [skillPath],
+ };
+ const baseManifest = {
+ capturedAt: '2026-08-10T00:00:00.000Z',
+ generation: 1,
+ status: 'loaded' as const,
+ source: 'pi:get_commands' as const,
+ };
+
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: `${skillPath}/SKILL.md`,
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-confirmed',
+ requestedSkillCount: 1,
+ loadedSkillCount: 1,
+ loadedSkills: [{
+ sourcePath: skillPath,
+ runtimePath: skillPath,
+ commandName: 'skill:demo',
+ }],
+ });
+
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: { scope: 'user', source: 'auto', baseDir: skillPath },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ requestedSkillCount: 1,
+ loadedSkillCount: 0,
+ });
+
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'not-a-skill-command',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: `${skillPath}/SKILL.md`,
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ loadedSkillCount: 0,
+ loadedSkills: [],
+ });
+
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: '/other/SKILL.md',
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ loadedSkillCount: 0,
+ });
+
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: skillPath,
+ path: `${skillPath}/skill.md`,
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ loadedSkillCount: 0,
+ });
+
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
+ ...baseManifest,
+ commands: [{
+ name: 'skill:demo',
+ source: 'skill',
+ sourceInfo: {
+ scope: 'temporary',
+ source: 'local',
+ baseDir: `${skillPath}\0outside`,
+ path: `${skillPath}\0outside/SKILL.md`,
+ },
+ }],
+ })).toMatchObject({
+ reason: 'runtime-skills-missing',
+ loadedSkillCount: 0,
+ });
+ });
+});
diff --cc packages/maker-core/src/agents/pi/project-resource-assembly.ts
index 5c90ba6d4b,0000000000..e7822b4a3b
mode 100644,000000..100644
--- a/packages/maker-core/src/agents/pi/project-resource-assembly.ts
+++ b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
@@@ -1,453 -1,0 +1,497 @@@
+import fs from 'node:fs/promises';
+import { constants, createWriteStream } from 'node:fs';
+import path from 'node:path';
+import { pipeline } from 'node:stream/promises';
++import { createHash } from 'node:crypto';
++import type { FileHandle } from 'node:fs/promises';
+
+import type {
+ PiProjectTrustDecision,
+ PiProjectTrustInputSnapshot,
+ PiProjectTrustStatus,
+} from '../../types/pi-project-trust.js';
+import {
+ evaluatePiProjectTrust,
+ piCanonicalPathIsWithin,
+ piCanonicalPathsEqual,
+} from './project-trust.js';
+import type {
+ PiProjectResourceRuntimeDiagnostic,
+ PiRuntimeCapabilityManifest,
+} from '../../types/pi-runtime-capabilities.js';
+import { piExplicitSkillRuntimePath } from './skill-runtime-provenance.js';
+
+export interface PiProjectResourceAssemblyDiagnostic {
+ readonly status: PiProjectTrustStatus;
+ readonly reason: string;
+ readonly approvalRevision: string | null;
+ readonly requestedSkillCount: number;
+}
+
+export interface PiProjectResourceAssemblySnapshot {
+ readonly decision: PiProjectTrustDecision | null;
+ /** Canonical project paths represented by the host approval snapshot. */
+ readonly skillPaths: readonly string[];
+ /** Per-session immutable copies that are safe to pass to Pi. */
+ readonly launchSkillPaths: readonly string[];
+ readonly diagnostic: PiProjectResourceAssemblyDiagnostic;
+}
+
+type PiPathStat = { isDirectory(): boolean; isFile(): boolean };
+
+const unavailableDiagnostic = (
+ reason: string,
+): PiProjectResourceAssemblyDiagnostic => Object.freeze({
+ status: 'unavailable',
+ reason,
+ approvalRevision: null,
+ requestedSkillCount: 0,
+});
+
+export function unavailablePiProjectResourceAssembly(
+ reason: string,
+): PiProjectResourceAssemblySnapshot {
+ return Object.freeze({
+ decision: null,
+ skillPaths: Object.freeze([]),
+ launchSkillPaths: Object.freeze([]),
+ diagnostic: unavailableDiagnostic(reason),
+ });
+}
+
+async function findNearestGitRoot(
+ start: string,
+ stat: (path: string) => Promise<PiPathStat>,
+ pathApi: typeof path.posix | typeof path.win32,
+): Promise<string | null> {
+ let current = start;
+ while (true) {
+ try {
+ const marker = await stat(pathApi.join(current, '.git'));
+ if (marker.isDirectory() || marker.isFile()) return current;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ // Match project discovery: an unreadable marker is a conservative
+ // boundary, while a genuinely absent marker permits walking upward.
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') return current;
+ }
+ const parent = pathApi.dirname(current);
+ if (parent === current) return null;
+ current = parent;
+ }
+}
+
+async function validateSkillPathsImmediatelyBeforeLaunch(
+ skillPaths: readonly string[],
+ stat: (path: string) => Promise<PiPathStat>,
+ realpath: (path: string) => Promise<string>,
+ identity: PiProjectTrustInputSnapshot['identity'],
+ requestedWorkingDir: string,
+ resolveNearestGitRoot: (
+ workingDir: string,
+ stat: (path: string) => Promise<PiPathStat>,
+ pathApi: typeof path.posix | typeof path.win32,
+ ) => Promise<string | null>,
+): Promise<
+ 'available' | 'unavailable' | 'request-mismatch' | 'repo-mismatch' | 'project-changed' | 'skill-changed'
+> {
+ try {
+ const canonicalWorkingDir = identity.canonicalWorkingDir;
+ const canonicalRepoRoot = identity.canonicalRepoRoot;
+ if (!canonicalWorkingDir || !canonicalRepoRoot) return 'unavailable';
+ const pathApi = identity.platform === 'win32' ? path.win32 : path.posix;
+ const resolvedRequestedWorkingDir = await realpath(requestedWorkingDir);
+ const [resolvedWorkingDir, resolvedRepoRoot, currentRepoRoot, entries] =
+ await Promise.all([
+ realpath(identity.workingDir),
+ realpath(canonicalRepoRoot),
+ resolveNearestGitRoot(resolvedRequestedWorkingDir, stat, pathApi),
+ Promise.all(skillPaths.map(async (skillPath) => {
+ const stats = await stat(skillPath);
+ const resolvedPath = await realpath(skillPath);
+ if (!stats.isDirectory()) return { skillPath, stats, resolvedPath };
+ const skillFile = pathApi.join(skillPath, 'SKILL.md');
+ return {
+ skillPath,
+ stats,
+ resolvedPath,
+ skillFileStats: await stat(skillFile),
+ resolvedSkillFile: await realpath(skillFile),
+ };
+ })),
+ ]);
+ if (
+ !piCanonicalPathsEqual(identity, canonicalWorkingDir, resolvedWorkingDir)
+ || !piCanonicalPathsEqual(identity, canonicalRepoRoot, resolvedRepoRoot)
+ ) return 'project-changed';
+ if (!piCanonicalPathsEqual(identity, canonicalWorkingDir, resolvedRequestedWorkingDir)) {
+ return 'request-mismatch';
+ }
+ if (
+ !currentRepoRoot
+ || !piCanonicalPathsEqual(identity, canonicalRepoRoot, currentRepoRoot)
+ ) return 'repo-mismatch';
+ if (entries.some(({ stats, skillFileStats }) =>
+ !stats.isDirectory() || !skillFileStats?.isFile())) return 'unavailable';
+ return entries.every(({ skillPath, resolvedPath, stats, resolvedSkillFile }) =>
+ piCanonicalPathsEqual(identity, skillPath, resolvedPath)
+ && piCanonicalPathIsWithin(identity, canonicalRepoRoot, resolvedPath)
+ && (stats.isDirectory() && (
+ typeof resolvedSkillFile === 'string'
+ && piCanonicalPathIsWithin(identity, canonicalRepoRoot, resolvedSkillFile)
+ )))
+ ? 'available'
+ : 'skill-changed';
+ } catch {
+ return 'unavailable';
+ }
+}
+
+/**
+ * Convert one host-owned approval snapshot into a frozen, skills-only launch
+ * snapshot. The caller's actual workingDir is rebound to that snapshot here;
+ * a missing/changed path invalidates the whole approved set so a partial or
+ * cross-project launch cannot silently diverge from the audited evidence.
+ */
+export async function assembleApprovedPiProjectResources(
+ input: PiProjectTrustInputSnapshot | null,
+ requestedWorkingDir: string,
+ options: {
+ stat?: (path: string) => Promise<PiPathStat>;
+ realpath?: (path: string) => Promise<string>;
+ findNearestGitRoot?: (
+ workingDir: string,
+ stat: (path: string) => Promise<PiPathStat>,
+ pathApi: typeof path.posix | typeof path.win32,
+ ) => Promise<string | null>;
+ } = {},
+): Promise<PiProjectResourceAssemblySnapshot> {
+ if (!input) return unavailablePiProjectResourceAssembly('approval-snapshot-unavailable');
+
+ const decision = evaluatePiProjectTrust({
+ identity: input.identity,
+ approval: input.approval,
+ discovered: input.discovered,
+ capabilities: { explicitSkills: true },
+ });
+ const eligibleSkillPaths = [...decision.eligibleSkillPaths];
+ let reason = decision.reason;
+ let skillPaths: readonly string[] = eligibleSkillPaths;
+
+ if (
+ decision.status === 'approved' &&
+ input.discovered.skills.length > 0 &&
+ eligibleSkillPaths.length === 0
+ ) {
+ reason = 'approved-skills-ineligible';
+ } else if (eligibleSkillPaths.length > 0) {
+ const pathStatus = await validateSkillPathsImmediatelyBeforeLaunch(
+ eligibleSkillPaths,
+ options.stat ?? fs.stat,
+ options.realpath ?? fs.realpath,
+ input.identity,
+ requestedWorkingDir,
+ options.findNearestGitRoot ?? findNearestGitRoot,
+ );
+ if (pathStatus !== 'available') {
+ if (pathStatus === 'request-mismatch') reason = 'approval-working-dir-mismatch';
+ else if (pathStatus === 'repo-mismatch') reason = 'approved-repo-root-changed';
+ else if (pathStatus === 'project-changed') reason = 'approved-project-path-changed';
+ else if (pathStatus === 'skill-changed') reason = 'approved-skill-path-changed';
+ else reason = 'approved-skill-path-unavailable';
+ skillPaths = [];
+ }
+ }
+
+ const frozenSkillPaths = Object.freeze([...skillPaths]);
+ return Object.freeze({
+ decision,
+ skillPaths: frozenSkillPaths,
+ launchSkillPaths: Object.freeze([]),
+ diagnostic: Object.freeze({
+ status: decision.status,
+ reason,
+ approvalRevision: decision.approvalRevision,
+ requestedSkillCount: frozenSkillPaths.length,
+ }),
+ });
+}
+
+function localPathIsWithin(root: string, candidate: string): boolean {
+ const relative = path.relative(root, candidate);
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
+}
+
+function sameFileIdentity(
+ first: Pick<Awaited<ReturnType<typeof fs.lstat>>, 'dev' | 'ino'>,
+ second: Pick<Awaited<ReturnType<typeof fs.lstat>>, 'dev' | 'ino'>,
+): boolean {
+ return first.dev === second.dev && first.ino === second.ino;
+}
+
++function sameFileSnapshot(
++ first: Awaited<ReturnType<FileHandle['stat']>>,
++ second: Awaited<ReturnType<FileHandle['stat']>>,
++): boolean {
++ return sameFileIdentity(first, second)
++ && first.size === second.size
++ && first.mtimeMs === second.mtimeMs
++ && first.ctimeMs === second.ctimeMs;
++}
++
++async function hashOpenFile(handle: FileHandle): Promise<string> {
++ const hash = createHash('sha256');
++ for await (const chunk of handle.createReadStream({ start: 0, autoClose: false })) {
++ hash.update(chunk);
++ }
++ return hash.digest('hex');
++}
++
+async function materializeSkillEntry(
+ sourcePath: string,
+ targetPath: string,
+ canonicalRepoRoot: string,
+ activeDirectories: Set<string>,
+): Promise<void> {
+ const [entry, canonicalSource] = await Promise.all([
+ fs.lstat(sourcePath),
+ fs.realpath(sourcePath),
+ ]);
+ if (!localPathIsWithin(canonicalRepoRoot, canonicalSource)) {
+ throw new Error('approved skill entry escaped its repository');
+ }
+
+ if (entry.isSymbolicLink()) {
+ await materializeSkillEntry(canonicalSource, targetPath, canonicalRepoRoot, activeDirectories);
+ return;
+ }
+ if (entry.isDirectory()) {
+ if (activeDirectories.has(canonicalSource)) {
+ throw new Error('approved skill contains a directory cycle');
+ }
+ activeDirectories.add(canonicalSource);
+ try {
+ await fs.mkdir(targetPath, { recursive: false });
+ const children = await fs.readdir(sourcePath, { withFileTypes: true });
+ for (const child of children) {
+ await materializeSkillEntry(
+ path.join(sourcePath, child.name),
+ path.join(targetPath, child.name),
+ canonicalRepoRoot,
+ activeDirectories,
+ );
+ }
+ const [canonicalAfterCopy, entryAfterCopy] = await Promise.all([
+ fs.realpath(sourcePath),
+ fs.lstat(sourcePath),
+ ]);
+ if (
+ path.relative(canonicalAfterCopy, canonicalSource) !== ''
+ || !entryAfterCopy.isDirectory()
+ || !sameFileIdentity(entry, entryAfterCopy)
+ ) {
+ throw new Error('approved skill directory changed while snapshotting');
+ }
+ } finally {
+ activeDirectories.delete(canonicalSource);
+ }
+ return;
+ }
+ if (!entry.isFile()) throw new Error('approved skill contains a special file');
+
+ const sourceHandle = await fs.open(
+ sourcePath,
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
+ );
+ try {
+ const openedEntry = await sourceHandle.stat();
+ if (!openedEntry.isFile() || !sameFileIdentity(entry, openedEntry)) {
+ throw new Error('approved skill file changed before snapshot read');
+ }
+ await pipeline(
+ sourceHandle.createReadStream({ autoClose: false }),
+ createWriteStream(targetPath, { flags: 'wx', mode: openedEntry.mode }),
+ );
+ const [openedAfterCopy, sourcePathAfterCopy, sourceAfterCopy, targetAfterCopy] =
+ await Promise.all([
+ sourceHandle.stat(),
+ fs.lstat(sourcePath),
+ fs.realpath(sourcePath),
+ fs.lstat(targetPath),
+ ]);
+ if (
- !sameFileIdentity(openedEntry, openedAfterCopy)
++ !sameFileSnapshot(openedEntry, openedAfterCopy)
+ || !sameFileIdentity(openedEntry, sourcePathAfterCopy)
+ || path.relative(sourceAfterCopy, canonicalSource) !== ''
+ || !targetAfterCopy.isFile()
+ ) {
+ throw new Error('approved skill file changed while snapshotting');
+ }
++ const targetHandle = await fs.open(
++ targetPath,
++ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
++ );
++ try {
++ const [sourceDigest, targetDigest] = await Promise.all([
++ hashOpenFile(sourceHandle),
++ hashOpenFile(targetHandle),
++ ]);
++ const [sourceAfterStableRead, targetAfterStableRead] = await Promise.all([
++ sourceHandle.stat(),
++ targetHandle.stat(),
++ ]);
++ if (
++ sourceDigest !== targetDigest
++ || !sameFileSnapshot(openedAfterCopy, sourceAfterStableRead)
++ || !targetAfterStableRead.isFile()
++ || targetAfterStableRead.size !== sourceAfterStableRead.size
++ ) {
++ throw new Error('approved skill file content changed while snapshotting');
++ }
++ } finally {
++ await targetHandle.close();
++ }
+ await fs.chmod(targetPath, openedEntry.mode & 0o777);
+ } finally {
+ await sourceHandle.close();
+ }
+}
+
+async function assertMaterializedTreeContainsNoLinksOrSpecialFiles(root: string): Promise<void> {
+ const entries = await fs.readdir(root, { withFileTypes: true });
+ for (const entry of entries) {
+ const entryPath = path.join(root, entry.name);
+ const stats = await fs.lstat(entryPath);
+ if (stats.isSymbolicLink()) throw new Error('skill snapshot contains a symbolic link');
+ if (stats.isDirectory()) {
+ await assertMaterializedTreeContainsNoLinksOrSpecialFiles(entryPath);
+ } else if (!stats.isFile()) {
+ throw new Error('skill snapshot contains a special file');
+ }
+ }
+}
+
+/**
+ * Materialize every approved directory into this session's isolated configHome.
+ * Pi never receives a mutable project path: the whole set is staged off-path,
+ * audited, and atomically published only after every skill succeeds.
+ */
+export async function stageApprovedPiProjectResources(
+ assembly: PiProjectResourceAssemblySnapshot,
+ configHome: string,
+): Promise<PiProjectResourceAssemblySnapshot> {
+ if (assembly.skillPaths.length === 0) return assembly;
+ const canonicalRepoRoot = assembly.decision?.canonicalRepoRoot;
+ if (!canonicalRepoRoot) {
+ return Object.freeze({
+ ...assembly,
+ skillPaths: Object.freeze([]),
+ launchSkillPaths: Object.freeze([]),
+ diagnostic: Object.freeze({
+ ...assembly.diagnostic,
+ reason: 'approved-skill-snapshot-failed',
+ requestedSkillCount: 0,
+ }),
+ });
+ }
+
+ let temporaryRoot: string | null = null;
+ try {
+ temporaryRoot = await fs.mkdtemp(path.join(configHome, '.project-resources-'));
+ const temporarySkillsRoot = path.join(temporaryRoot, 'skills');
+ await fs.mkdir(temporarySkillsRoot);
+ const relativeLaunchPaths: string[] = [];
+ for (const [index, sourcePath] of assembly.skillPaths.entries()) {
+ const skillName = path.basename(sourcePath);
+ const relativePath = path.join('skills', String(index), skillName);
+ const targetPath = path.join(temporaryRoot, relativePath);
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
+ await materializeSkillEntry(
+ sourcePath,
+ targetPath,
+ canonicalRepoRoot,
+ new Set<string>(),
+ );
+ const [canonicalSourceAfterCopy, skillEntrypoint] = await Promise.all([
+ fs.realpath(sourcePath),
+ fs.lstat(path.join(targetPath, 'SKILL.md')),
+ ]);
+ if (path.resolve(canonicalSourceAfterCopy) !== path.resolve(sourcePath) || !skillEntrypoint.isFile()) {
+ throw new Error('approved skill changed before snapshot publication');
+ }
+ relativeLaunchPaths.push(relativePath);
+ }
+ await assertMaterializedTreeContainsNoLinksOrSpecialFiles(temporarySkillsRoot);
+
+ const publishedRoot = path.join(configHome, 'project-resources');
+ await fs.rename(temporaryRoot, publishedRoot);
+ temporaryRoot = null;
+ const launchSkillPaths = Object.freeze(relativeLaunchPaths.map((relativePath) =>
+ path.join(publishedRoot, relativePath)));
+ return Object.freeze({
+ ...assembly,
+ launchSkillPaths,
+ diagnostic: Object.freeze({
+ ...assembly.diagnostic,
+ requestedSkillCount: launchSkillPaths.length,
+ }),
+ });
+ } catch {
+ if (temporaryRoot) {
+ await fs.rm(temporaryRoot, { recursive: true, force: true }).catch(() => undefined);
+ }
+ return Object.freeze({
+ ...assembly,
+ skillPaths: Object.freeze([]),
+ launchSkillPaths: Object.freeze([]),
+ diagnostic: Object.freeze({
+ ...assembly.diagnostic,
+ reason: 'approved-skill-snapshot-failed',
+ requestedSkillCount: 0,
+ }),
+ });
+ }
+}
+
+function comparableRuntimePath(value: string): string {
+ // Explicit --skill provenance normally echoes the canonical argv path. Keep
+ // comparison case-sensitive here: a conservative false-negative is safer
+ // than claiming loaded on a case-sensitive Windows directory.
+ return path.resolve(value);
+}
+
+/**
+ * Reconcile the approved launch snapshot with this runtime's exact command
+ * catalog. Approval alone never upgrades a skill to loaded; missing commands
+ * remain diagnosable even when get_commands itself succeeded.
+ */
+export function reconcilePiProjectResourceRuntime(
+ assembly: PiProjectResourceAssemblySnapshot,
+ manifest: PiRuntimeCapabilityManifest,
+): PiProjectResourceRuntimeDiagnostic {
+ if (manifest.status !== 'loaded' || assembly.launchSkillPaths.length === 0) {
+ return assembly.diagnostic;
+ }
+
+ const expectedPaths = new Set(assembly.launchSkillPaths.map(comparableRuntimePath));
+ const loadedPaths = new Map(manifest.commands.flatMap((command) => {
+ const skillPath = piExplicitSkillRuntimePath(command);
+ return skillPath && command.name.startsWith('skill:')
+ ? [[comparableRuntimePath(skillPath), command.name] as const]
+ : [];
+ }));
+ const loadedSkills = assembly.launchSkillPaths.flatMap((runtimePath, index) => {
+ const commandName = loadedPaths.get(comparableRuntimePath(runtimePath));
+ const sourcePath = assembly.skillPaths[index];
+ return commandName && sourcePath ? [{ sourcePath, runtimePath, commandName }] : [];
+ });
+ const loadedSkillCount = [...expectedPaths].filter((skillPath) => loadedPaths.has(skillPath)).length;
+ return Object.freeze({
+ ...assembly.diagnostic,
+ reason: loadedSkillCount === expectedPaths.size
+ ? 'runtime-skills-confirmed'
+ : 'runtime-skills-missing',
+ loadedSkillCount,
+ loadedSkills: Object.freeze(loadedSkills.map((skill) => Object.freeze(skill))),
+ });
+}