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): snapshot approved project skills before launch

nana2e97fbde756f
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 3c989108ff..9043919914 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -93,10 +93,14 @@ Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、
8. **项目资源显式装配**:root、只读 subagent 与离线 fork 启动 Pi 时都必须显式传
`--no-approve --no-extensions`;root 仅用重复 `--extension` 回装 Cindy 自有 bridge/subagent
与 pinned plan-mode,并仅用重复 `--skill` 装配 host 从 PR3 approval snapshot 判定 eligible
- 的 canonical 项目 skill 路径。不得读取/复制项目 `.pi/settings.json`,不得传 `--approve`,
+ 的项目 skill 目录。eligible canonical 目录必须先完整物化到当前会话 `configHome` 的非自动
+ 扫描目录,再把隔离快照路径交给 Pi;不得把仍可变化的项目原路径直接放进 argv。复制期间
+ 任一越界 symlink、特殊文件或路径替换会使整组 skills fail closed。不得读取/复制项目
+ `.pi/settings.json`,不得传 `--approve`,
不得依赖 `PI_OFFLINE=1` 代替 packages/extensions 硬门。root 不传 `--no-skills`,以保留现有
- user/global skill 行为;项目 skill 的 `loaded` 只能由当前会话 `get_commands` 的 exact
- temporary/local provenance 证明。approval 真源缺失、异常、撤销、失效或路径消失时,新会话
+ user/global skill 行为;项目 skill 的 `loaded` 只能由当前会话 `get_commands` 对隔离快照路径
+ 的 exact temporary/local provenance 证明。approval 真源缺失、异常、撤销、失效、路径消失
+ 或快照失败时,新会话
一律不带项目 `--skill`,并在 per-session runtime manifest 记录诊断原因。
## 5. 已交付(2026-07 里程碑)
diff --git a/docs/dev-rules/pi-project-trust.md b/docs/dev-rules/pi-project-trust.md
index c2cda0874f..f56b946169 100644
--- a/docs/dev-rules/pi-project-trust.md
+++ b/docs/dev-rules/pi-project-trust.md
@@ -16,7 +16,7 @@
批准决策只产生 PR4 的候选输入:
-- `skills`:只有调用方显式证明 `explicitSkills: true`,且在新增的 `canonicalSkillEvidence` 中为每条发现路径提供 exact `discoveredPath`/`canonicalPath` 配对的 1:1 realpath 证据并验证 canonical path 位于批准 repo root 内时,才可用单独 skill 路径装配;旧的 `canonicalSkills` 字符串数组仅为兼容保留,不能单独构成资格证据。host 必须先从 `discovered.skills` 中排除 user、`extraDirs`、引用目录和其他 workspace root,canonical evidence 不能替代该 provenance 过滤。缺少证据、配对不一致、仓库外 symlink 目标或非 canonical 路径时保持 `discovered`。eligible 输出保留 canonical I/O path,不使用 comparison key 替代。能力位只有严格的布尔 `true` 才生效,缺省或其他 truthy 值均为 false。它不代表 Pi 已经 `loaded` 这些资源;
+- `skills`:只有调用方显式证明 `explicitSkills: true`,且在新增的 `canonicalSkillEvidence` 中为每条发现路径提供 exact `discoveredPath`/`canonicalPath` 配对的 1:1 realpath 证据并验证 canonical path 位于批准 repo root 内时,才可把含 `SKILL.md` 的 skill 目录交给 PR4 装配;单文件 Markdown 不属于当前 Cindy 项目发现契约,保持 `discovered`。旧的 `canonicalSkills` 字符串数组仅为兼容保留,不能单独构成资格证据。host 必须先从 `discovered.skills` 中排除 user、`extraDirs`、引用目录和其他 workspace root,canonical evidence 不能替代该 provenance 过滤。缺少证据、配对不一致、仓库外 symlink 目标或非 canonical 路径时保持 `discovered`。eligible 输出保留 canonical I/O path,不使用 comparison key 替代;PR4 必须将 eligible 目录完整物化到每会话隔离的 `configHome`,只把快照路径交给 Pi,任一复制或复核失败则整组 fail closed。能力位只有严格的布尔 `true` 才生效,缺省或其他 truthy 值均为 false。它不代表 Pi 已经 `loaded` 这些资源;
- `settings`:只有经字段白名单投影(输出 `settingsProjection.values`)、为每条发现路径提供带 exact `discoveredPath`/`canonicalPath` 配对的 1:1 realpath evidence 并验证 canonical path 位于批准 repo root 内,且同时证明 packages/extensions 关闭时才可装配;`settingsProjection.sourcePath` 必须是 `discovered.settings` 中的原始 lexical path,成功后输出才改写为对应 canonical I/O path。缺少 evidence、配对不一致、仓库外 symlink 目标或非 canonical 路径时保持 `discovered`。本契约默认不允许原始 `.pi/settings.json`。当前白名单只允许 pinned Pi v0.83.0 的 `compaction.reserveTokens` / `compaction.keepRecentTokens` 非负安全整数;未知字段、未来新增字段、`defaultProjectTrust`、provider/auth、路径及资源加载配置均 fail closed。输出是深克隆并冻结的启动快照;`eligibleSettingsPaths` 仅为兼容字段,包含投影使用的 canonical `sourcePath`,不能把发现到的原始 settings 路径当作可装配输入;空投影保持 `discovered`。
- `packages` / `extensions`:始终 `discovered` 或 `blocked`,不得安装、加载或执行。
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
index 6edce4d7db..5993b648d4 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
@@ -874,6 +874,40 @@ describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts
]));
});
+ it('loads an explicit immutable skill snapshot from a non-auto-scanned configHome directory', async () => {
+ const fixture = await createFixture('pi-rpc-config-home-snapshot-');
+ const snapshotSkill = path.join(
+ fixture.configHome,
+ 'project-resources',
+ 'skills',
+ '0',
+ 'snapshot-skill',
+ );
+ writeSkill(snapshotSkill, 'snapshot-skill');
+ const result = await runGetCommands({
+ binaryPath: PI_BINARY,
+ cwd: fixture.workingDir,
+ configHome: fixture.configHome,
+ sessionDir: fixture.sessionDir,
+ approve: false,
+ extraArgs: ['--no-extensions', '--skill', snapshotSkill],
+ });
+
+ expect(result.commands).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ name: 'skill:snapshot-skill',
+ source: 'skill',
+ sourceInfo: expect.objectContaining({
+ baseDir: snapshotSkill,
+ path: path.join(snapshotSkill, 'SKILL.md'),
+ source: 'local',
+ scope: 'temporary',
+ }),
+ }),
+ ]));
+ expect(result.commands.some((command) => command.name === 'skill:project-pi-skill')).toBe(false);
+ });
+
it('reports the exact file provenance for an explicit single-file skill', async () => {
const fixture = await createFixture('pi-rpc-explicit-file-skill-');
const explicitSkill = path.join(fixture.workingDir, '.pi', 'skills', 'single-file.md');
diff --git 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
index e0f8512003..675cd5e905 100644
--- 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
@@ -197,6 +197,10 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
: []);
}
+ function stagedSkillPath(configHome: string, index: number, sourcePath: string): string {
+ return path.join(configHome, 'project-resources', 'skills', String(index), path.basename(sourcePath));
+ }
+
const opts = () => ({
sessionId: 's1',
sessionInstanceId: 'pi-instance-1',
@@ -282,7 +286,9 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
const approvedHandle = await agent.startSession({ sessionId: 'approved', workingDir: cwd, model: 'm' });
const revokedHandle = await agent.startSession({ sessionId: 'revoked', workingDir: cwd, model: 'm' });
- expect(repeatedArgValues(knobs.spawnedArgs[0]!, '--skill')).toEqual([skillPath]);
+ expect(repeatedArgValues(knobs.spawnedArgs[0]!, '--skill')).toEqual([
+ stagedSkillPath(knobs.spawnedEnvs[0]!.PI_CODING_AGENT_DIR!, 0, skillPath),
+ ]);
expect(repeatedArgValues(knobs.spawnedArgs[1]!, '--skill')).toEqual([]);
await vi.waitFor(() => {
expect(approvedHandle.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
@@ -464,8 +470,12 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(home2.startsWith(runTmp)).toBe(true);
expect(existsSync(path.join(home1, 'models.json'))).toBe(true);
expect(existsSync(path.join(home2, 'models.json'))).toBe(true);
- expect(repeatedArgValues(knobs.spawnedArgs[s1Index]!, '--skill')).toEqual([skillOne]);
- expect(repeatedArgValues(knobs.spawnedArgs[s2Index]!, '--skill')).toEqual([skillTwo]);
+ expect(repeatedArgValues(knobs.spawnedArgs[s1Index]!, '--skill')).toEqual([
+ stagedSkillPath(home1, 0, skillOne),
+ ]);
+ expect(repeatedArgValues(knobs.spawnedArgs[s2Index]!, '--skill')).toEqual([
+ stagedSkillPath(home2, 0, skillTwo),
+ ]);
await vi.waitFor(() => {
expect(h1.getRuntimeCapabilities?.()?.projectResources).toMatchObject({
approvalRevision: 'rev-s1', requestedSkillCount: 1,
@@ -515,7 +525,9 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(knobs.spawnedEnvs[approvedIndex]!.CINDY_PI_PERMISSION_FILE).not.toBe(
knobs.spawnedEnvs[reviewIndex]!.CINDY_PI_PERMISSION_FILE,
);
- expect(repeatedArgValues(knobs.spawnedArgs[approvedIndex]!, '--skill')).toEqual([skillPath]);
+ expect(repeatedArgValues(knobs.spawnedArgs[approvedIndex]!, '--skill')).toEqual([
+ stagedSkillPath(approvedHome, 0, skillPath),
+ ]);
expect(repeatedArgValues(knobs.spawnedArgs[reviewIndex]!, '--skill')).toEqual([]);
expect(repeatedArgValues(knobs.spawnedArgs[approvedIndex]!, '--extension')).toEqual([
path.join(approvedHome, 'extensions', 'cindy-bridge.ts'),
diff --git 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
index c71e787c7e..23179d94d6 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,10 +1,26 @@
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,
@@ -46,6 +62,45 @@ const approved = (workingDir: string, revision: string): PiProjectApprovalSnapsh
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'),
@@ -105,6 +160,7 @@ describe('Pi approved project resource assembly', () => {
expect(unavailablePiProjectResourceAssembly('approval-resolver-unavailable')).toEqual({
decision: null,
skillPaths: [],
+ launchSkillPaths: [],
diagnostic: {
status: 'unavailable',
reason: 'approval-resolver-unavailable',
@@ -218,7 +274,7 @@ describe('Pi approved project resource assembly', () => {
expect(result.diagnostic.reason).toBe('approval-matched');
});
- it('allows an approved single-file markdown skill', async () => {
+ 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(
@@ -227,27 +283,111 @@ describe('Pi approved project resource assembly', () => {
available,
);
- expect(result.skillPaths).toEqual([skillFile]);
- expect(result.diagnostic.reason).toBe('approval-matched');
- expect(reconcilePiProjectResourceRuntime(result, {
- capturedAt: '2026-08-10T00:00:00.000Z',
- generation: 1,
- status: 'loaded',
- source: 'pi:get_commands',
- commands: [{
- name: 'skill:demo-file',
- source: 'skill',
- sourceInfo: {
- scope: 'temporary',
- source: 'local',
- baseDir: `${workingDir}/.pi/skills`,
- path: skillFile,
- },
- }],
- })).toMatchObject({
- reason: 'runtime-skills-confirmed',
- loadedSkillCount: 1,
- });
+ 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 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 () => {
@@ -324,6 +464,10 @@ describe('Pi approved project resource assembly', () => {
available,
);
const skillPath = assembly.skillPaths[0]!;
+ const runtimeAssembly = {
+ ...assembly,
+ launchSkillPaths: [skillPath],
+ };
const baseManifest = {
capturedAt: '2026-08-10T00:00:00.000Z',
generation: 1,
@@ -331,7 +475,7 @@ describe('Pi approved project resource assembly', () => {
source: 'pi:get_commands' as const,
};
- expect(reconcilePiProjectResourceRuntime(assembly, {
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
...baseManifest,
commands: [{
name: 'skill:demo',
@@ -347,9 +491,14 @@ describe('Pi approved project resource assembly', () => {
reason: 'runtime-skills-confirmed',
requestedSkillCount: 1,
loadedSkillCount: 1,
+ loadedSkills: [{
+ sourcePath: skillPath,
+ runtimePath: skillPath,
+ commandName: 'skill:demo',
+ }],
});
- expect(reconcilePiProjectResourceRuntime(assembly, {
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
...baseManifest,
commands: [{
name: 'skill:demo',
@@ -362,7 +511,25 @@ describe('Pi approved project resource assembly', () => {
loadedSkillCount: 0,
});
- expect(reconcilePiProjectResourceRuntime(assembly, {
+ 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',
@@ -379,7 +546,7 @@ describe('Pi approved project resource assembly', () => {
loadedSkillCount: 0,
});
- expect(reconcilePiProjectResourceRuntime(assembly, {
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
...baseManifest,
commands: [{
name: 'skill:demo',
@@ -396,7 +563,7 @@ describe('Pi approved project resource assembly', () => {
loadedSkillCount: 0,
});
- expect(reconcilePiProjectResourceRuntime(assembly, {
+ expect(reconcilePiProjectResourceRuntime(runtimeAssembly, {
...baseManifest,
commands: [{
name: 'skill:demo',
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 1e63cc7571..414350fb7e 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -89,6 +89,7 @@ import { capturePiRuntimeCapabilityManifest } from './runtime-capabilities.js';
import {
assembleApprovedPiProjectResources,
reconcilePiProjectResourceRuntime,
+ stageApprovedPiProjectResources,
unavailablePiProjectResourceAssembly,
} from './project-resource-assembly.js';
import {
@@ -1093,6 +1094,10 @@ export class PiAgent extends BaseAgent {
trustInput,
opts.workingDir,
);
+ projectResourceAssembly = await stageApprovedPiProjectResources(
+ projectResourceAssembly,
+ configHome,
+ );
} catch {
projectResourceAssembly = unavailablePiProjectResourceAssembly(
'approval-resolver-failed',
@@ -1125,7 +1130,7 @@ export class PiAgent extends BaseAgent {
'--extension', bridgeExtensionPath,
...(!reviewMode ? ['--extension', subagentExtensionPath] : []),
...(!reviewMode && planModeExtAvailable ? ['--extension', planModeExtPath] : []),
- ...projectResourceAssembly.skillPaths.flatMap((skillPath) => ['--skill', skillPath]),
+ ...projectResourceAssembly.launchSkillPaths.flatMap((skillPath) => ['--skill', skillPath]),
];
const queue: AsyncQueue<AgentEvent> = createAsyncQueue<AgentEvent>();
diff --git a/packages/maker-core/src/agents/pi/project-resource-assembly.ts b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
index 330d7e83f9..5c90ba6d4b 100644
--- a/packages/maker-core/src/agents/pi/project-resource-assembly.ts
+++ b/packages/maker-core/src/agents/pi/project-resource-assembly.ts
@@ -1,5 +1,7 @@
import fs from 'node:fs/promises';
+import { constants, createWriteStream } from 'node:fs';
import path from 'node:path';
+import { pipeline } from 'node:stream/promises';
import type {
PiProjectTrustDecision,
@@ -26,7 +28,10 @@ export interface PiProjectResourceAssemblyDiagnostic {
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;
}
@@ -47,6 +52,7 @@ export function unavailablePiProjectResourceAssembly(
return Object.freeze({
decision: null,
skillPaths: Object.freeze([]),
+ launchSkillPaths: Object.freeze([]),
diagnostic: unavailableDiagnostic(reason),
});
}
@@ -123,13 +129,12 @@ async function validateSkillPathsImmediatelyBeforeLaunch(
!currentRepoRoot
|| !piCanonicalPathsEqual(identity, canonicalRepoRoot, currentRepoRoot)
) return 'repo-mismatch';
- if (entries.some(({ skillPath, stats, skillFileStats }) =>
- (!stats.isDirectory() && (!stats.isFile() || pathApi.extname(skillPath) !== '.md'))
- || (stats.isDirectory() && !skillFileStats?.isFile()))) return 'unavailable';
+ 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() || (
+ && (stats.isDirectory() && (
typeof resolvedSkillFile === 'string'
&& piCanonicalPathIsWithin(identity, canonicalRepoRoot, resolvedSkillFile)
)))
@@ -200,6 +205,7 @@ export async function assembleApprovedPiProjectResources(
return Object.freeze({
decision,
skillPaths: frozenSkillPaths,
+ launchSkillPaths: Object.freeze([]),
diagnostic: Object.freeze({
status: decision.status,
reason,
@@ -209,6 +215,200 @@ export async function assembleApprovedPiProjectResources(
});
}
+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;
+}
+
+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)
+ || !sameFileIdentity(openedEntry, sourcePathAfterCopy)
+ || path.relative(sourceAfterCopy, canonicalSource) !== ''
+ || !targetAfterCopy.isFile()
+ ) {
+ throw new Error('approved skill file changed while snapshotting');
+ }
+ 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
@@ -225,15 +425,22 @@ export function reconcilePiProjectResourceRuntime(
assembly: PiProjectResourceAssemblySnapshot,
manifest: PiRuntimeCapabilityManifest,
): PiProjectResourceRuntimeDiagnostic {
- if (manifest.status !== 'loaded' || assembly.skillPaths.length === 0) {
+ if (manifest.status !== 'loaded' || assembly.launchSkillPaths.length === 0) {
return assembly.diagnostic;
}
- const expectedPaths = new Set(assembly.skillPaths.map(comparableRuntimePath));
- const loadedPaths = new Set(manifest.commands.flatMap((command) => {
+ const expectedPaths = new Set(assembly.launchSkillPaths.map(comparableRuntimePath));
+ const loadedPaths = new Map(manifest.commands.flatMap((command) => {
const skillPath = piExplicitSkillRuntimePath(command);
- return skillPath ? [comparableRuntimePath(skillPath)] : [];
+ 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,
@@ -241,5 +448,6 @@ export function reconcilePiProjectResourceRuntime(
? 'runtime-skills-confirmed'
: 'runtime-skills-missing',
loadedSkillCount,
+ loadedSkills: Object.freeze(loadedSkills.map((skill) => Object.freeze(skill))),
});
}
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index facc7a4460..3ef056f184 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -920,6 +920,18 @@ describe('Maker Pi runtime skill status', () => {
generation: 1,
status: 'loaded',
source: 'pi:get_commands',
+ projectResources: {
+ status: 'approved',
+ reason: 'runtime-skills-confirmed',
+ approvalRevision: `rev-${opts.sessionId}`,
+ requestedSkillCount: 1,
+ loadedSkillCount: 1,
+ loadedSkills: [{
+ sourcePath: `/repo/.pi/skills/${opts.sessionId}-skill`,
+ runtimePath: `/isolated/${opts.sessionId}/project-resources/skills/0/${opts.sessionId}-skill`,
+ commandName: `skill:${opts.sessionId}-frontmatter-name`,
+ }],
+ },
commands: [
{
name: `skill:${opts.sessionId}-frontmatter-name`,
@@ -927,8 +939,8 @@ describe('Maker Pi runtime skill status', () => {
sourceInfo: {
source: 'local',
scope: 'temporary',
- baseDir: `/repo/.pi/skills/${opts.sessionId}-skill`,
- path: `/repo/.pi/skills/${opts.sessionId}-skill/SKILL.md`,
+ baseDir: `/isolated/${opts.sessionId}/project-resources/skills/0/${opts.sessionId}-skill`,
+ path: `/isolated/${opts.sessionId}/project-resources/skills/0/${opts.sessionId}-skill/SKILL.md`,
},
},
{
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 142b79b251..adadd035af 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -167,6 +167,9 @@ function mergePiRuntimeSkillStatuses(
if (manifest?.status !== 'loaded') return result;
const loadedExplicitSkills = new Map<string, string>();
const loadedLegacyProjectSkills = new Map<string, string>();
+ for (const skill of manifest.projectResources?.loadedSkills ?? []) {
+ loadedExplicitSkills.set(canonicalPiRuntimePath(skill.sourcePath), skill.commandName);
+ }
for (const command of manifest.commands) {
const baseDir = command.sourceInfo.baseDir;
if (command.source !== 'skill' || !command.name.startsWith('skill:')) continue;
diff --git a/packages/maker-core/src/types/pi-runtime-capabilities.ts b/packages/maker-core/src/types/pi-runtime-capabilities.ts
index cd4fe250c1..d7aea767ab 100644
--- a/packages/maker-core/src/types/pi-runtime-capabilities.ts
+++ b/packages/maker-core/src/types/pi-runtime-capabilities.ts
@@ -53,6 +53,12 @@ export interface PiProjectResourceRuntimeDiagnostic {
requestedSkillCount: number;
/** Present only when this session's get_commands returned a valid catalog. */
loadedSkillCount?: number;
+ /** Exact source↔snapshot mappings confirmed by this session's get_commands. */
+ loadedSkills?: readonly {
+ sourcePath: string;
+ runtimePath: string;
+ commandName: string;
+ }[];
}
/**