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。

feat(pi): define Cindy project trust contract (#2056)

nanaco41f916f625e1
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index bc8c3f5eaa..a07adf3677 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -138,6 +138,9 @@ Cindy 显式设置:models.json、`--append-system-prompt`、`--session-dir`、
## 7. 上线后路线图(已与 Chris 对齐)
+项目 trust 的输入/输出契约见 [`pi-project-trust.md`](pi-project-trust.md)。该契约不改变本节
+所述运行时默认,也不授权 `--approve`、trust.json 或用户 Pi home 复用;这些属于后续装配 PR。
+
> 续做指南(每项怎么接着做 + file:line 锚点 + 坑)见 `docs/dev-rules/pi-remaining-work.md`。
- ✅ **HTML 导出**(已交付):`export_html` RPC 全链路,会话头部菜单「导出为 HTML」,
diff --git a/docs/dev-rules/pi-project-trust.md b/docs/dev-rules/pi-project-trust.md
new file mode 100644
index 0000000000..c2cda0874f
--- /dev/null
+++ b/docs/dev-rules/pi-project-trust.md
@@ -0,0 +1,35 @@
+# Cindy 管理的 Pi project trust 契约(#2013)
+
+本文件定义 PR4(#2014)可消费的输入/输出契约;本 Issue 不改变 Pi 运行时行为。
+
+## 真源与生命周期
+
+- trust 输入只能来自 Cindy 已有、可审计的项目 approval。当前 `origin/main` 尚未提供通用 project approval store,因此实现必须通过 host 注入 `PiProjectApprovalSnapshot`,不得把 `permissionMode`、工具审批、MCP approval、插件启用状态或 Pi 用户设置解释为项目 trust。
+- approval 在新建、重启、fork 或切换到新 `workingDir` 时重新求值;一个运行中的 Pi 进程使用启动时快照。撤销或失效对下一次新会话生效,不声称热卸载已加载资源。
+- `workingDir` 与 git repo root 必须先做 `realpath`/规范化,host 必须同时提供可信的 `platform`(`posix` / `win32`),不得从路径字符串猜测或缺省为 POSIX。POSIX canonical bytes 只有能无损往返 UTF-8 时才可标记 `utf8-lossless`;Windows canonical path 只有能无损往返 host Unicode string 时才可标记 `utf16-lossless`。编码标记与平台不匹配、含替换字符或无法证明无损时必须标记 `unavailable`,不得用有损字符串生成 approval key。解析失败、目录消失、repo 边界变化、symlink 指向变化均 fail closed。默认作用域是 `repo-root + workingDir`;只有 approval 明确声明 `repo-root` 才能让同一仓库的多个 workingDir 共享批准。`extraDirs`、引用目录和其他 workspace root 不继承。
+- 当前纯函数只在 host 明确提供 `windowsCaseComparison: ordinal-insensitive` 时对 ASCII Windows canonical path 做比较 key 的分隔符、扩展长度前缀和大小写归一化;若 host 报告 `case-sensitive`,则保留 comparison key 大小写;缺省、`unavailable` 或无法证明比较语义时统一 fail closed。比较 key 归一化不得覆盖 host 提供的 canonical I/O path,eligible 输出必须保留扩展长度前缀及尾随空格/点。`ordinal-insensitive` 下的非 ASCII Windows path 因 JavaScript Unicode folding 不等同于 Win32 ordinal comparison,也必须 fail closed 为 `unavailable`,直到 host 提供独立的 Win32 comparison identity。
+- `projectKey` 为 `${canonicalRepoRoot}\0${canonicalWorkingDir}`;Windows 比较身份决定是否折叠大小写,分隔符始终归一化。approval 的 `scopeKey` 对 `repo-root` 是 canonical root,对 `working-dir` 是同样的复合 key。
+
+## 状态与资源边界
+
+纯函数输出的状态只有 `approved`、`unapproved`、`revoked`、`stale`、`unavailable`。文件存在或 scanner 命中只能形成资源 `discovered`,不能宣称 Pi `loaded`;`loaded` 只能由 #2011 的 `get_commands` runtime manifest 证明。
+
+批准决策只产生 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` 这些资源;
+- `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`,不得安装、加载或执行。
+
+## 启动与隔离不变量
+
+- 不传 `--approve`,不写用户 `~/.pi/agent/trust.json`,不设置 `defaultProjectTrust=always`;trust.json、`defaultProjectTrust` 或等效配置的装配属于 #2014。
+- 不写或复用整个用户 `~/.pi/agent`,不继承 auth/provider/settings/trust/凭证。每会话 `PI_CODING_AGENT_DIR` 隔离、临时目录和并发 session 输入隔离保持不变。
+- `launch` 输出固定为 `approve:false`、`writeTrustJson:false`、`inheritUserPiHome:false`、`allowPackages:false`、`allowExtensions:false`。纯函数不读配置、不写文件、不启动 Pi。
+- 如果 Pi 无法同时做到“信任 skills/settings 但阻止 packages/extensions”,#2014 必须缩小为显式 skills-only,或阻断项目 settings;不得用 `--approve` 绕过。
+
+## 与既有边界对照
+
+- #1729:只允许 Cindy 已批准项目映射;禁止无条件 `--approve`、复用整个用户 Pi 目录与默认开放 packages/extensions。
+- #1705:packages/extensions 在非 TUI 宿主下的执行与呈现契约仍未解决;本契约不重开该范围。
+- #1967:隔离 `PI_CODING_AGENT_DIR` 是有意的并发/凭证边界;本契约不通过复制或链接用户 Pi home 规避隔离。
+- #2030:以 Pi v0.83.0 `get_commands` 夹具作为资源发现事实基线;#2053/#2011 的 manifest 类型合入后,只需复核字段接线,不复制其未合入类型。
diff --git a/packages/maker-core/src/agents/pi/__tests__/project-trust.test.ts b/packages/maker-core/src/agents/pi/__tests__/project-trust.test.ts
new file mode 100644
index 0000000000..8b6714a64d
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/__tests__/project-trust.test.ts
@@ -0,0 +1,811 @@
+import { describe, expect, it } from 'vitest';
+
+import { evaluatePiProjectTrust, piProjectKey } from '../project-trust.js';
+import type {
+ PiProjectApprovalSnapshot,
+ PiProjectDiscoveredResources,
+ PiProjectIdentityResolution,
+ PiProjectSettingsProjection,
+} from '../../../types/pi-project-trust.js';
+
+const identity: PiProjectIdentityResolution = {
+ workingDir: '/repo/packages/app',
+ canonicalWorkingDir: '/repo/packages/app',
+ canonicalRepoRoot: '/repo',
+ repoRootStatus: 'resolved',
+ platform: 'posix',
+ canonicalPathEncoding: 'utf8-lossless',
+};
+
+const discovered: PiProjectDiscoveredResources = {
+ skills: ['/repo/.pi/skills/a', '/repo/.agents/skills/b'],
+ canonicalSkillEvidence: [
+ { discoveredPath: '/repo/.pi/skills/a', canonicalPath: '/repo/.pi/skills/a' },
+ { discoveredPath: '/repo/.agents/skills/b', canonicalPath: '/repo/.agents/skills/b' },
+ ],
+ settings: ['/repo/.pi/settings.json'],
+ canonicalSettings: [{ discoveredPath: '/repo/.pi/settings.json', canonicalPath: '/repo/.pi/settings.json' }],
+ packages: ['/repo/.pi/package.json'],
+ extensions: ['/repo/.pi/extensions/x.ts'],
+};
+
+const approval = (overrides: Partial<Extract<PiProjectApprovalSnapshot, { status: 'approved' }>> = {}): PiProjectApprovalSnapshot => ({
+ status: 'approved',
+ scope: 'working-dir',
+ scopeKey: '/repo\0/repo/packages/app',
+ revision: 'rev-1',
+ ...overrides,
+});
+
+const provenSettingsCapabilities = {
+ projectedSettings: true,
+ packagesDisabled: true,
+ extensionsDisabled: true,
+} as const;
+
+function expectSettingsDiscovered(result: ReturnType<typeof evaluatePiProjectTrust>): void {
+ expect(result.resources.settings).toBe('discovered');
+ expect(result.settingsProjection).toBeNull();
+ expect(result.eligibleSettingsPaths).toEqual([]);
+}
+
+describe('Pi project trust contract', () => {
+ it('uses canonical repo root + workingDir and isolates sibling workingDirs', () => {
+ expect(piProjectKey(identity)).toBe('/repo\0/repo/packages/app');
+ expect(evaluatePiProjectTrust({ identity, approval: approval(), discovered }).status).toBe('approved');
+ expect(evaluatePiProjectTrust({
+ identity: { ...identity, canonicalWorkingDir: '/repo/packages/other' },
+ approval: approval(),
+ discovered,
+ }).status).toBe('unapproved');
+ });
+
+ it('allows explicit skills only; settings/packages/extensions stay separated', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.eligibleSkillPaths).toEqual(discovered.skills);
+ expect(result.eligibleSettingsPaths).toEqual([]);
+ expect(result.settingsProjection).toBeNull();
+ expect(result.resources).toEqual({
+ skills: 'eligible', settings: 'discovered', packages: 'discovered', extensions: 'discovered',
+ });
+ expect(result.launch).toEqual({
+ approve: false,
+ writeTrustJson: false,
+ inheritUserPiHome: false,
+ allowPackages: false,
+ allowExtensions: false,
+ });
+ });
+
+ it('keeps skills discovered when canonical realpath evidence is missing', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ canonicalSkills: discovered.skills,
+ canonicalSkillEvidence: undefined,
+ },
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.resources.skills).toBe('discovered');
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('rejects skill evidence whose discovered path does not match by position', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ canonicalSkillEvidence: [
+ { discoveredPath: '/outside/untrusted-skill', canonicalPath: '/repo/.pi/skills/a' },
+ { discoveredPath: '/repo/.agents/skills/b', canonicalPath: '/repo/.agents/skills/b' },
+ ],
+ },
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.resources.skills).toBe('discovered');
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('fails closed for malformed skill evidence supplied at the host boundary', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ canonicalSkillEvidence: [null, { discoveredPath: '/repo/.agents/skills/b', canonicalPath: '/repo/.agents/skills/b' }],
+ } as unknown as PiProjectDiscoveredResources,
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.resources.skills).toBe('discovered');
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('emits canonical I/O paths for an in-repo skill symlink target', () => {
+ const sourcePath = '/repo/.pi/skills/link';
+ const canonicalPath = '/repo/.agents/skills/target';
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ skills: [sourcePath],
+ canonicalSkillEvidence: [{ discoveredPath: sourcePath, canonicalPath }],
+ },
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.resources.skills).toBe('eligible');
+ expect(result.eligibleSkillPaths).toEqual([canonicalPath]);
+ });
+
+ it('maps a raw settings source path to its canonical I/O path', () => {
+ const sourcePath = '/repo/.pi/settings-link.json';
+ const canonicalPath = '/repo/.pi/settings.json';
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ settings: [sourcePath],
+ canonicalSettings: [{ discoveredPath: sourcePath, canonicalPath }],
+ },
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: { sourcePath, values: { compaction: { reserveTokens: 1 } } },
+ });
+ expect(result.resources.settings).toBe('eligible');
+ expect(result.settingsProjection?.sourcePath).toBe(canonicalPath);
+ expect(result.eligibleSettingsPaths).toEqual([canonicalPath]);
+ });
+
+ it('rejects canonical skill paths that resolve outside the approved repo root', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ canonicalSkillEvidence: [
+ { discoveredPath: '/repo/.pi/skills/a', canonicalPath: '/outside/shared-skill' },
+ { discoveredPath: '/repo/.agents/skills/b', canonicalPath: '/repo/.agents/skills/b' },
+ ],
+ },
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.resources.skills).toBe('discovered');
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('rejects non-canonical traversal segments in canonical skill evidence', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ canonicalSkillEvidence: [
+ { discoveredPath: '/repo/.pi/skills/a', canonicalPath: '/repo/../outside/shared-skill' },
+ { discoveredPath: '/repo/.agents/skills/b', canonicalPath: '/repo/.agents/skills/b' },
+ ],
+ },
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.resources.skills).toBe('discovered');
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('fails closed when the working directory is outside the resolved repository root', () => {
+ const result = evaluatePiProjectTrust({
+ identity: {
+ ...identity,
+ canonicalWorkingDir: '/outside/worktree',
+ },
+ approval: approval({ scope: 'repo-root', scopeKey: '/repo' }),
+ discovered,
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.status).toBe('unavailable');
+ expect(result.reason).toBe('working-dir-outside-repo-root');
+ expect(result.resources.skills).toBe('discovered');
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('keeps restrictive defaults when optional capability fields are undefined', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: {
+ explicitSkills: undefined,
+ projectedSettings: undefined,
+ packagesDisabled: undefined,
+ extensionsDisabled: undefined,
+ },
+ });
+ expect(result.eligibleSkillPaths).toEqual([]);
+ expect(result.eligibleSettingsPaths).toEqual([]);
+ expect(result.settingsProjection).toBeNull();
+ expect(result.launch.allowPackages).toBe(false);
+ expect(result.launch.allowExtensions).toBe(false);
+ });
+
+ it('treats truthy non-boolean capability values as false', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: {
+ explicitSkills: 1 as unknown as boolean,
+ projectedSettings: 'true' as unknown as boolean,
+ packagesDisabled: 1 as unknown as boolean,
+ extensionsDisabled: 'true' as unknown as boolean,
+ },
+ settingsProjection: projection,
+ });
+ expect(result.eligibleSkillPaths).toEqual([]);
+ expectSettingsDiscovered(result);
+ });
+
+ it.each([
+ ['missing', null, 'unapproved', 'approval-missing'],
+ ['unapproved', { status: 'unapproved', reason: 'user-denied' } as PiProjectApprovalSnapshot, 'unapproved', 'user-denied'],
+ ['revoked', { status: 'revoked', revision: 'revoked-2', reason: 'user-revoked' } as PiProjectApprovalSnapshot, 'revoked', 'user-revoked'],
+ ['stale', { status: 'stale', revision: 'stale-2', reason: 'revision-old' } as PiProjectApprovalSnapshot, 'stale', 'revision-old'],
+ ['unavailable', { status: 'unavailable', reason: 'store-offline' } as PiProjectApprovalSnapshot, 'unavailable', 'store-offline'],
+ ])('fails closed for %s approval', (_label, input, status, reason) => {
+ const result = evaluatePiProjectTrust({ identity, approval: input, discovered });
+ expect(result.status).toBe(status);
+ expect(result.reason).toBe(reason);
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('keeps revoked/stale approval revisions as audit evidence', () => {
+ expect(evaluatePiProjectTrust({
+ identity,
+ approval: { status: 'revoked', revision: 'revoked-2', reason: 'user-revoked' },
+ discovered,
+ }).approvalRevision).toBe('revoked-2');
+ expect(evaluatePiProjectTrust({
+ identity,
+ approval: { status: 'stale', revision: 'stale-2', reason: 'revision-old' },
+ discovered,
+ }).approvalRevision).toBe('stale-2');
+ });
+
+ it('fails closed when realpath or repository root resolution is unavailable', () => {
+ const result = evaluatePiProjectTrust({
+ identity: {
+ ...identity,
+ canonicalRepoRoot: '/repo/old-root',
+ canonicalWorkingDir: '/repo/old-root/packages/app',
+ repoRootStatus: 'unavailable',
+ },
+ approval: approval(),
+ discovered,
+ });
+ expect(result.status).toBe('unavailable');
+ expect(result.projectKey).toBeNull();
+ expect(result.resources.skills).toBe('discovered');
+ });
+
+ it('supports explicit repo-root approval for multiple workingDirs', () => {
+ const repoApproval = approval({ scope: 'repo-root', scopeKey: '/repo' });
+ expect(evaluatePiProjectTrust({
+ identity: { ...identity, canonicalWorkingDir: '/repo/packages/other' },
+ approval: repoApproval,
+ discovered,
+ }).status).toBe('approved');
+ });
+
+ it('normalizes symlink/realpath and Windows case/separators before matching', () => {
+ const result = evaluatePiProjectTrust({
+ identity: {
+ ...identity,
+ canonicalWorkingDir: 'C:/Repo/App',
+ canonicalRepoRoot: 'C:/Repo',
+ workingDir: 'C:\\repo\\app',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ },
+ approval: approval({ scopeKey: 'c:/repo\0c:/repo/app' }),
+ discovered,
+ });
+ expect(result.status).toBe('approved');
+ });
+
+ it('requires a host Windows comparison identity', () => {
+ const windowsIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: 'C:\\repo\\app',
+ canonicalWorkingDir: 'C:/repo/app',
+ canonicalRepoRoot: 'C:/repo',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ };
+ expect(evaluatePiProjectTrust({
+ identity: windowsIdentity,
+ approval: approval({ scopeKey: 'c:/repo\0c:/repo/app' }),
+ discovered,
+ }).status).toBe('unavailable');
+ });
+
+ it('preserves case when the host reports a case-sensitive Windows directory', () => {
+ const caseSensitiveIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: 'C:\\repo\\App',
+ canonicalWorkingDir: 'C:/repo/App',
+ canonicalRepoRoot: 'C:/repo',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'case-sensitive',
+ };
+ expect(evaluatePiProjectTrust({
+ identity: caseSensitiveIdentity,
+ approval: approval({ scopeKey: 'C:/repo\0C:/repo/App' }),
+ discovered,
+ }).status).toBe('approved');
+ expect(evaluatePiProjectTrust({
+ identity: caseSensitiveIdentity,
+ approval: approval({ scopeKey: 'c:/repo\0c:/repo/app' }),
+ discovered,
+ }).status).toBe('unapproved');
+ });
+
+ it('preserves a Windows drive root when deriving the project key', () => {
+ const driveRootIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: 'C:\\',
+ canonicalWorkingDir: 'C:/',
+ canonicalRepoRoot: 'C:/',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ };
+ const result = evaluatePiProjectTrust({
+ identity: driveRootIdentity,
+ approval: approval({ scope: 'repo-root', scopeKey: 'c:/' }),
+ discovered,
+ });
+ expect(result.status).toBe('approved');
+ expect(result.projectKey).toBe('c:/\0c:/');
+ });
+
+ it('normalizes Windows extended-length canonical paths', () => {
+ const extendedIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: '\\\\?\\C:\\Repo\\App',
+ canonicalWorkingDir: '//?/C:/Repo/App',
+ canonicalRepoRoot: '//?/C:/Repo',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ };
+ expect(evaluatePiProjectTrust({
+ identity: extendedIdentity,
+ approval: approval({ scopeKey: 'c:/repo\0c:/repo/app' }),
+ discovered,
+ }).status).toBe('approved');
+
+ const extendedUncIdentity: PiProjectIdentityResolution = {
+ ...extendedIdentity,
+ workingDir: '\\\\?\\UNC\\Server\\Share\\Repo\\App',
+ canonicalWorkingDir: '//?/UNC/Server/Share/Repo/App',
+ canonicalRepoRoot: '//?/UNC/Server/Share/Repo',
+ };
+ expect(evaluatePiProjectTrust({
+ identity: extendedUncIdentity,
+ approval: approval({ scopeKey: '//server/share/repo\0//server/share/repo/app' }),
+ discovered,
+ }).status).toBe('approved');
+ });
+
+ it.each([
+ {
+ label: 'drive',
+ canonicalRepoRoot: '//?/C:/Repo',
+ canonicalWorkingDir: '//?/C:/Repo/App',
+ scopeKey: 'c:/repo\0c:/repo/app',
+ },
+ {
+ label: 'UNC',
+ canonicalRepoRoot: '//?/UNC/Server/Share/Repo',
+ canonicalWorkingDir: '//?/UNC/Server/Share/Repo/App',
+ scopeKey: '//server/share/repo\0//server/share/repo/app',
+ },
+ ])('preserves extended-length %s I/O paths with trailing space/dot', ({ canonicalRepoRoot, canonicalWorkingDir, scopeKey }) => {
+ const skillPath = `${canonicalRepoRoot}/.pi/skills/skill `;
+ const settingsPath = `${canonicalRepoRoot}/.pi/settings.json.`;
+ const extendedResources: PiProjectDiscoveredResources = {
+ skills: [skillPath],
+ canonicalSkillEvidence: [{ discoveredPath: skillPath, canonicalPath: skillPath }],
+ settings: [settingsPath],
+ canonicalSettings: [{ discoveredPath: settingsPath, canonicalPath: settingsPath }],
+ packages: [],
+ extensions: [],
+ };
+ const extendedIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: canonicalWorkingDir,
+ canonicalWorkingDir,
+ canonicalRepoRoot,
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ };
+ const result = evaluatePiProjectTrust({
+ identity: extendedIdentity,
+ approval: approval({ scopeKey }),
+ discovered: extendedResources,
+ capabilities: { explicitSkills: true, ...provenSettingsCapabilities },
+ settingsProjection: { sourcePath: settingsPath, values: { compaction: { reserveTokens: 1 } } },
+ });
+ expect(result.resources.skills).toBe('eligible');
+ expect(result.eligibleSkillPaths).toEqual([skillPath]);
+ expect(result.resources.settings).toBe('eligible');
+ expect(result.settingsProjection?.sourcePath).toBe(settingsPath);
+ expect(result.eligibleSettingsPaths).toEqual([settingsPath]);
+ });
+
+ it('preserves literal POSIX canonical path bytes', () => {
+ const literalIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: '/repo/packages/app ',
+ canonicalWorkingDir: '/repo/packages/app \\',
+ canonicalRepoRoot: '/repo',
+ };
+ const literalApproval = approval({ scopeKey: '/repo\0/repo/packages/app \\' });
+ expect(evaluatePiProjectTrust({ identity: literalIdentity, approval: literalApproval, discovered }).status).toBe('approved');
+ expect(evaluatePiProjectTrust({
+ identity: { ...literalIdentity, canonicalWorkingDir: '/repo/packages/app' },
+ approval: literalApproval,
+ discovered,
+ }).status).toBe('unapproved');
+ });
+
+ const projection: PiProjectSettingsProjection = {
+ sourcePath: '/repo/.pi/settings.json',
+ values: { compaction: { reserveTokens: 16_384, keepRecentTokens: 8_192 } },
+ revision: 'settings-rev-1',
+ };
+
+ it('keeps settings discovered until every hard gate is explicitly proven', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: { projectedSettings: true },
+ settingsProjection: projection,
+ });
+ expectSettingsDiscovered(result);
+ });
+
+ it('keeps settings discovered when canonical realpath evidence is missing', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: { ...discovered, canonicalSettings: undefined },
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: projection,
+ });
+ expectSettingsDiscovered(result);
+ });
+
+ it.each([
+ ['outside the repo root', ['/outside/settings.json']],
+ ['non-canonical', ['/repo/../outside/settings.json']],
+ ])('keeps settings discovered when canonical settings evidence is %s', (_label, canonicalSettings) => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ canonicalSettings: canonicalSettings.map((canonicalPath) => ({
+ discoveredPath: '/repo/.pi/settings.json',
+ canonicalPath,
+ })),
+ },
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: projection,
+ });
+ expectSettingsDiscovered(result);
+ });
+
+ it('rejects settings evidence whose discovered path does not match by position', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ canonicalSettings: [{ discoveredPath: '/outside/settings.json', canonicalPath: '/repo/.pi/settings.json' }],
+ },
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: projection,
+ });
+ expectSettingsDiscovered(result);
+ });
+
+ it('emits the canonical settings path for a reviewed in-repo symlink target', () => {
+ const sourcePath = '/repo/.pi/settings-link.json';
+ const canonicalPath = '/repo/.pi/settings.json';
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: {
+ ...discovered,
+ settings: [sourcePath],
+ canonicalSettings: [{ discoveredPath: sourcePath, canonicalPath }],
+ },
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: { ...projection, sourcePath },
+ });
+ expect(result.resources.settings).toBe('eligible');
+ expect(result.settingsProjection?.sourcePath).toBe(canonicalPath);
+ expect(result.eligibleSettingsPaths).toEqual([canonicalPath]);
+ });
+
+ it('exposes a non-empty reviewed settings projection after every hard gate is proven', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: projection,
+ });
+ expect(result.resources.settings).toBe('eligible');
+ expect(result.settingsProjection).toEqual(projection);
+ expect(result.eligibleSettingsPaths).toEqual([projection.sourcePath]);
+ });
+
+ it.each([
+ ['undefined-only values', { compaction: { reserveTokens: undefined } }],
+ ['empty values', {}],
+ ['packages key', { packages: [] }],
+ ['extensions key', { extensions: [] }],
+ ['defaultProjectTrust key', { defaultProjectTrust: 'always' }],
+ [
+ 'non-plain values',
+ Object.assign(
+ Object.create({ inherited: true }) as Record<string, unknown>,
+ { compaction: { reserveTokens: 16_384 } },
+ ),
+ ],
+ ['null values', null],
+ ['negative threshold', { compaction: { reserveTokens: -1 } }],
+ ])('rejects %s after settings hard gates are proven', (_label, values) => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: {
+ sourcePath: '/repo/.pi/settings.json',
+ values: values as PiProjectSettingsProjection['values'],
+ },
+ });
+ expectSettingsDiscovered(result);
+ });
+
+ it('rejects a reviewed projection whose source was not discovered', () => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: { sourcePath: '/repo/.pi/other-settings.json', values: { compaction: { reserveTokens: 16_384 } } },
+ });
+ expectSettingsDiscovered(result);
+ });
+
+ it.each([
+ ['NUL', '/repo/.pi/settings\0.json'],
+ ['replacement character', '/repo/.pi/settings\uFFFD.json'],
+ ['empty path', ''],
+ ])('rejects a discovered settings source containing %s', (_label, sourcePath) => {
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered: { ...discovered, settings: [sourcePath] },
+ capabilities: provenSettingsCapabilities,
+ settingsProjection: {
+ sourcePath,
+ values: { compaction: { reserveTokens: 16_384 } },
+ },
+ });
+ expectSettingsDiscovered(result);
+ });
+
+ it('returns a detached frozen settings snapshot', () => {
+ const mutableValues = { compaction: { reserveTokens: 16_384 } };
+ const mutableProjection = {
+ sourcePath: '/repo/.pi/settings.json',
+ values: mutableValues,
+ revision: 'settings-rev-1',
+ };
+ const result = evaluatePiProjectTrust({
+ identity,
+ approval: approval(),
+ discovered,
+ capabilities: { projectedSettings: true, packagesDisabled: true, extensionsDisabled: true },
+ settingsProjection: mutableProjection,
+ });
+ mutableProjection.sourcePath = '/repo/.pi/other-settings.json';
+ mutableValues.compaction.reserveTokens = 1;
+ Object.assign(mutableValues, { defaultProjectTrust: 'always' });
+
+ expect(result.settingsProjection).toEqual({
+ sourcePath: '/repo/.pi/settings.json',
+ values: { compaction: { reserveTokens: 16_384 } },
+ revision: 'settings-rev-1',
+ });
+ expect(Object.isFrozen(result.settingsProjection)).toBe(true);
+ expect(Object.isFrozen(result.settingsProjection?.values)).toBe(true);
+ expect(Object.isFrozen(result.settingsProjection?.values.compaction)).toBe(true);
+ expect(result.eligibleSettingsPaths).toEqual(['/repo/.pi/settings.json']);
+ });
+
+ it('rejects path NULs and ambiguous working-dir scope separators', () => {
+ expect(evaluatePiProjectTrust({
+ identity: { ...identity, canonicalWorkingDir: '/repo/app\0other' },
+ approval: approval(),
+ discovered,
+ }).status).toBe('unavailable');
+ expect(evaluatePiProjectTrust({
+ identity,
+ approval: approval({ scopeKey: '/repo\0/repo/packages/app\0other' }),
+ discovered,
+ }).status).toBe('unapproved');
+ });
+
+ it('fails closed when host platform semantics are missing', () => {
+ const identityWithoutPlatform = { ...identity, platform: undefined } as unknown as PiProjectIdentityResolution;
+ expect(evaluatePiProjectTrust({
+ identity: identityWithoutPlatform as PiProjectIdentityResolution,
+ approval: approval(),
+ discovered,
+ }).status).toBe('unavailable');
+ });
+
+ it('fails closed when POSIX canonical bytes are not lossless UTF-8', () => {
+ expect(evaluatePiProjectTrust({
+ identity: { ...identity, canonicalPathEncoding: 'unavailable' },
+ approval: approval(),
+ discovered,
+ }).status).toBe('unavailable');
+ expect(evaluatePiProjectTrust({
+ identity: { ...identity, canonicalWorkingDir: '/repo/bad\uFFFDname' },
+ approval: approval(),
+ discovered,
+ }).status).toBe('unavailable');
+ expect(evaluatePiProjectTrust({
+ identity: { ...identity, canonicalPathEncoding: 'utf16-lossless' },
+ approval: approval(),
+ discovered,
+ }).status).toBe('unavailable');
+ });
+
+ it('preserves trailing whitespace in Windows canonical paths', () => {
+ const trailingIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: 'C:\\repo\\app ',
+ canonicalWorkingDir: 'C:/repo/app ',
+ canonicalRepoRoot: 'C:/repo',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ };
+ expect(evaluatePiProjectTrust({
+ identity: trailingIdentity,
+ approval: approval({ scopeKey: 'c:/repo\0c:/repo/app ' }),
+ discovered,
+ }).status).toBe('approved');
+ expect(evaluatePiProjectTrust({
+ identity: { ...trailingIdentity, canonicalWorkingDir: 'C:/repo/app' },
+ approval: approval({ scopeKey: 'c:/repo\0c:/repo/app ' }),
+ discovered,
+ }).status).toBe('unapproved');
+ });
+
+ it('fails closed for non-ASCII Windows paths without a Win32 comparison identity', () => {
+ const nonAsciiIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: 'C:\\repo\\İ',
+ canonicalWorkingDir: 'C:/repo/İ',
+ canonicalRepoRoot: 'C:/repo',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ };
+ const result = evaluatePiProjectTrust({
+ identity: nonAsciiIdentity,
+ approval: approval({ scopeKey: 'c:/repo\0c:/repo/i̇' }),
+ discovered,
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.status).toBe('unavailable');
+ expect(result.resources.skills).toBe('discovered');
+ expect(result.eligibleSkillPaths).toEqual([]);
+ });
+
+ it('preserves non-ASCII POSIX paths when the host proves UTF-8 losslessness', () => {
+ const posixIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: '/repo/café',
+ canonicalWorkingDir: '/repo/café',
+ canonicalRepoRoot: '/repo',
+ platform: 'posix',
+ canonicalPathEncoding: 'utf8-lossless',
+ };
+ const result = evaluatePiProjectTrust({
+ identity: posixIdentity,
+ approval: approval({ scopeKey: '/repo\0/repo/café' }),
+ discovered,
+ capabilities: { explicitSkills: true },
+ });
+ expect(result.status).toBe('approved');
+ expect(result.eligibleSkillPaths).toEqual(discovered.skills);
+ });
+
+ it('preserves Windows UNC canonical roots while matching approval scope', () => {
+ const uncIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: '\\\\Server\\Share\\Repo\\App',
+ canonicalWorkingDir: '//server/share/repo/app',
+ canonicalRepoRoot: '//server/share/repo',
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ };
+ const result = evaluatePiProjectTrust({
+ identity: uncIdentity,
+ approval: approval({ scopeKey: '//SERVER\\SHARE\\REPO\0//server/share/repo/app' }),
+ discovered,
+ });
+ expect(result.status).toBe('approved');
+ expect(result.projectKey).toBe('//server/share/repo\0//server/share/repo/app');
+ });
+
+ it.each(['//', '//server', '///server/share'])('fails closed for incomplete Windows UNC path %s', (invalidRoot) => {
+ const invalidIdentity: PiProjectIdentityResolution = {
+ ...identity,
+ workingDir: invalidRoot,
+ canonicalWorkingDir: invalidRoot,
+ canonicalRepoRoot: invalidRoot,
+ platform: 'win32',
+ canonicalPathEncoding: 'utf16-lossless',
+ windowsCaseComparison: 'ordinal-insensitive',
+ };
+ expect(evaluatePiProjectTrust({
+ identity: invalidIdentity,
+ approval: approval({ scope: 'repo-root', scopeKey: invalidRoot }),
+ discovered,
+ }).status).toBe('unavailable');
+ });
+
+ it('does not let concurrent session inputs leak into one another', () => {
+ const first = evaluatePiProjectTrust({
+ identity,
+ approval: approval({ revision: 'a' }),
+ discovered,
+ capabilities: { explicitSkills: true },
+ });
+ const second = evaluatePiProjectTrust({
+ identity: { ...identity, canonicalWorkingDir: '/repo/other' },
+ approval: approval({ scopeKey: '/repo\0/repo/other', revision: 'b' }),
+ discovered: {
+ ...discovered,
+ skills: ['/repo/other/.pi/skills/c'],
+ canonicalSkillEvidence: [{ discoveredPath: '/repo/other/.pi/skills/c', canonicalPath: '/repo/other/.pi/skills/c' }],
+ },
+ capabilities: { explicitSkills: true },
+ });
+ expect(first.approvalRevision).toBe('a');
+ expect(first.eligibleSkillPaths).toEqual(discovered.skills);
+ expect(second.approvalRevision).toBe('b');
+ expect(second.eligibleSkillPaths).toEqual(['/repo/other/.pi/skills/c']);
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/project-trust.ts b/packages/maker-core/src/agents/pi/project-trust.ts
new file mode 100644
index 0000000000..be1ea4e585
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/project-trust.ts
@@ -0,0 +1,334 @@
+import type {
+ PiProjectApprovalSnapshot,
+ PiProjectCanonicalPathEvidence,
+ PiProjectDiscoveredResources,
+ PiProjectIdentityResolution,
+ PiProjectSettingsProjection,
+ PiProjectSettingsValues,
+ PiProjectTrustCapabilities,
+ PiProjectTrustDecision,
+ PiProjectWindowsCaseComparison,
+} from '../../types/pi-project-trust.js';
+
+function normalizePath(
+ value: string,
+ platform: 'posix' | 'win32',
+ windowsCaseComparison?: PiProjectWindowsCaseComparison,
+): string | null {
+ if (value.includes('\0') || value.includes('\uFFFD')) return null;
+ if (platform === 'posix') {
+ // Canonical POSIX paths come from the host resolver. Preserve their literal
+ // bytes so a valid path containing spaces or backslashes cannot alias another.
+ return value.startsWith('/') && !hasDotSegments(value) ? value : null;
+ }
+
+ if (!value) return null;
+ if (windowsCaseComparison !== 'ordinal-insensitive' && windowsCaseComparison !== 'case-sensitive') return null;
+ let withForwardSlashes = value.replaceAll('\\', '/');
+ // JavaScript Unicode case folding is not the Win32 ordinal comparison used
+ // by the filesystem. Until the host supplies a Win32 comparison identity,
+ // reject non-ASCII paths rather than allowing approval-key collisions.
+ if (
+ windowsCaseComparison === 'ordinal-insensitive' &&
+ Array.from(withForwardSlashes).some((character) => (character.codePointAt(0) ?? 0) > 0x7f)
+ ) {
+ return null;
+ }
+ if (withForwardSlashes.toLowerCase().startsWith('//?/unc/')) {
+ withForwardSlashes = `//${withForwardSlashes.slice(8)}`;
+ } else if (/^\/\/\?\/[A-Za-z]:\//.test(withForwardSlashes)) {
+ withForwardSlashes = withForwardSlashes.slice(4);
+ } else if (withForwardSlashes.startsWith('//?/') || withForwardSlashes.startsWith('//./')) {
+ return null;
+ }
+ const slash = withForwardSlashes.startsWith('//')
+ ? `//${withForwardSlashes.slice(2).replace(/\/+/g, '/')}`
+ : withForwardSlashes.replace(/\/+/g, '/');
+ if (hasDotSegments(slash)) return null;
+ if (platform === 'win32') {
+ if (!/^(?:[A-Za-z]:\/|\/\/)/.test(slash)) return null;
+ if (slash.startsWith('//') && !/^\/\/[^/]+\/[^/]+(?:\/|$)/.test(slash)) return null;
+ if (/^[A-Za-z]:\/$/.test(slash)) {
+ return windowsCaseComparison === 'ordinal-insensitive' ? slash.toLowerCase() : slash;
+ }
+ const withoutTrailingSlash = slash.replace(/\/$/, '');
+ return windowsCaseComparison === 'ordinal-insensitive'
+ ? withoutTrailingSlash.toLowerCase()
+ : withoutTrailingSlash;
+ }
+ return null;
+}
+
+function hasLosslessCanonicalEncoding(
+ identity: Pick<PiProjectIdentityResolution, 'platform' | 'canonicalPathEncoding' | 'windowsCaseComparison'>,
+): boolean {
+ return identity.platform === 'posix'
+ ? identity.canonicalPathEncoding === 'utf8-lossless'
+ : identity.platform === 'win32' &&
+ identity.canonicalPathEncoding === 'utf16-lossless' &&
+ (identity.windowsCaseComparison === 'ordinal-insensitive' || identity.windowsCaseComparison === 'case-sensitive');
+}
+
+function isPathWithinRoot(root: string, candidate: string): boolean {
+ const rootPrefix = root.endsWith('/') ? root : `${root}/`;
+ return candidate === root || candidate.startsWith(rootPrefix);
+}
+
+function hasDotSegments(value: string): boolean {
+ return value.split('/').some((segment) => segment === '.' || segment === '..');
+}
+
+function isCanonicalPathEvidence(value: unknown): value is PiProjectCanonicalPathEvidence {
+ if (typeof value !== 'object' || value === null) return false;
+ const evidence = value as Record<string, unknown>;
+ return typeof evidence.discoveredPath === 'string' && typeof evidence.canonicalPath === 'string';
+}
+
+export function piProjectKey(
+ identity: Pick<PiProjectIdentityResolution, 'canonicalWorkingDir' | 'canonicalRepoRoot' | 'platform' | 'canonicalPathEncoding' | 'windowsCaseComparison'>,
+): string | null {
+ const platform = identity.platform;
+ if (!platform || !hasLosslessCanonicalEncoding(identity)) return null;
+ const repoRoot = identity.canonicalRepoRoot && normalizePath(identity.canonicalRepoRoot, platform, identity.windowsCaseComparison);
+ const workingDir = identity.canonicalWorkingDir && normalizePath(identity.canonicalWorkingDir, platform, identity.windowsCaseComparison);
+ if (!repoRoot || !workingDir) return null;
+ return `${repoRoot}\0${workingDir}`;
+}
+
+function approvalScopeKey(
+ identity: Pick<PiProjectIdentityResolution, 'canonicalWorkingDir' | 'canonicalRepoRoot' | 'platform' | 'canonicalPathEncoding' | 'windowsCaseComparison'>,
+ scope: 'working-dir' | 'repo-root',
+): string | null {
+ const platform = identity.platform;
+ if (!platform || !hasLosslessCanonicalEncoding(identity)) return null;
+ const repoRoot = identity.canonicalRepoRoot && normalizePath(identity.canonicalRepoRoot, platform, identity.windowsCaseComparison);
+ if (!repoRoot) return null;
+ if (scope === 'repo-root') return repoRoot;
+ const workingDir = identity.canonicalWorkingDir && normalizePath(identity.canonicalWorkingDir, platform, identity.windowsCaseComparison);
+ return workingDir ? `${repoRoot}\0${workingDir}` : null;
+}
+
+function normalizeApprovalScopeKey(
+ value: string,
+ platform: 'posix' | 'win32',
+ scope: 'working-dir' | 'repo-root',
+ windowsCaseComparison?: PiProjectWindowsCaseComparison,
+): string | null {
+ if (scope === 'repo-root') return normalizePath(value, platform, windowsCaseComparison);
+ const separator = value.indexOf('\0');
+ if (separator < 0 || value.lastIndexOf('\0') !== separator) return null;
+ const repoRoot = normalizePath(value.slice(0, separator), platform, windowsCaseComparison);
+ const workingDir = normalizePath(value.slice(separator + 1), platform, windowsCaseComparison);
+ return repoRoot && workingDir ? `${repoRoot}\0${workingDir}` : null;
+}
+
+function canonicalEligibleSkillPaths(
+ identity: PiProjectIdentityResolution,
+ discovered: PiProjectDiscoveredResources,
+): readonly string[] {
+ const skillsEvidence = discovered.canonicalSkillEvidence;
+ if (!skillsEvidence || skillsEvidence.length !== discovered.skills.length || skillsEvidence.length === 0) return [];
+ if (skillsEvidence.some((evidence, index) => !isCanonicalPathEvidence(evidence) || evidence.discoveredPath !== discovered.skills[index])) return [];
+ const repoRoot = identity.canonicalRepoRoot &&
+ normalizePath(identity.canonicalRepoRoot, identity.platform, identity.windowsCaseComparison);
+ if (!repoRoot) return [];
+ const normalizedSkills = skillsEvidence.map((evidence) =>
+ normalizePath(evidence.canonicalPath, identity.platform, identity.windowsCaseComparison),
+ );
+ const validSkills = normalizedSkills.filter((skillPath): skillPath is string => skillPath !== null);
+ if (validSkills.length !== normalizedSkills.length || new Set(validSkills).size !== validSkills.length) return [];
+ return validSkills.every((skillPath) => isPathWithinRoot(repoRoot, skillPath))
+ ? skillsEvidence.map((evidence) => evidence.canonicalPath)
+ : [];
+}
+
+function canonicalEligibleSettingsPaths(
+ identity: PiProjectIdentityResolution,
+ discovered: PiProjectDiscoveredResources,
+): readonly string[] {
+ const settingsEvidence = discovered.canonicalSettings;
+ if (!settingsEvidence || settingsEvidence.length !== discovered.settings.length || settingsEvidence.length === 0) return [];
+ if (settingsEvidence.some((evidence, index) => !isCanonicalPathEvidence(evidence) || evidence.discoveredPath !== discovered.settings[index])) return [];
+ const repoRoot = identity.canonicalRepoRoot &&
+ normalizePath(identity.canonicalRepoRoot, identity.platform, identity.windowsCaseComparison);
+ if (!repoRoot) return [];
+ const normalizedSettings = settingsEvidence.map((evidence) =>
+ normalizePath(evidence.canonicalPath, identity.platform, identity.windowsCaseComparison),
+ );
+ const validSettings = normalizedSettings.filter((settingsPath): settingsPath is string => settingsPath !== null);
+ if (validSettings.length !== normalizedSettings.length || new Set(validSettings).size !== validSettings.length) return [];
+ return validSettings.every((settingsPath) => isPathWithinRoot(repoRoot, settingsPath))
+ ? settingsEvidence.map((evidence) => evidence.canonicalPath)
+ : [];
+}
+
+function isPlainObject(values: unknown): values is Record<string, unknown> {
+ if (typeof values !== 'object' || values === null || Array.isArray(values)) return false;
+ const prototype = Object.getPrototypeOf(values);
+ return prototype === Object.prototype || prototype === null;
+}
+
+function cloneAllowedSettings(values: unknown): Readonly<PiProjectSettingsValues> | null {
+ if (!isPlainObject(values) || Object.keys(values).length !== 1 || !('compaction' in values)) return null;
+ const compaction = values.compaction;
+ if (!isPlainObject(compaction)) return null;
+ const keys = Object.keys(compaction);
+ if (
+ keys.length === 0 ||
+ keys.some((key) => key !== 'reserveTokens' && key !== 'keepRecentTokens')
+ ) return null;
+
+ const reserveTokens = compaction.reserveTokens;
+ const keepRecentTokens = compaction.keepRecentTokens;
+ if (
+ (reserveTokens !== undefined &&
+ (typeof reserveTokens !== 'number' || !Number.isSafeInteger(reserveTokens) || reserveTokens < 0)) ||
+ (keepRecentTokens !== undefined &&
+ (typeof keepRecentTokens !== 'number' || !Number.isSafeInteger(keepRecentTokens) || keepRecentTokens < 0))
+ ) return null;
+ const clone = {
+ ...(reserveTokens === undefined ? {} : { reserveTokens }),
+ ...(keepRecentTokens === undefined ? {} : { keepRecentTokens }),
+ };
+ if (Object.keys(clone).length === 0) return null;
+ return Object.freeze({ compaction: Object.freeze(clone) });
+}
+
+function snapshotSettingsProjection(projection: PiProjectSettingsProjection): PiProjectSettingsProjection | null {
+ if (
+ typeof projection.sourcePath !== 'string' ||
+ !projection.sourcePath ||
+ projection.sourcePath.includes('\0') ||
+ projection.sourcePath.includes('\uFFFD')
+ ) {
+ return null;
+ }
+ const values = cloneAllowedSettings(projection.values);
+ if (!values) return null;
+ return Object.freeze({
+ sourcePath: projection.sourcePath,
+ values,
+ ...(projection.revision === undefined ? {} : { revision: projection.revision }),
+ });
+}
+
+function emptyDecision(
+ identity: PiProjectIdentityResolution,
+ status: PiProjectTrustDecision['status'],
+ reason: string,
+ approvalRevision: string | null,
+ discovered: PiProjectDiscoveredResources,
+ settingsProjection: PiProjectSettingsProjection | null = null,
+): PiProjectTrustDecision {
+ return {
+ status,
+ projectKey: status === 'unavailable' ? null : piProjectKey(identity),
+ canonicalWorkingDir: identity.canonicalWorkingDir,
+ canonicalRepoRoot: identity.canonicalRepoRoot,
+ approvalRevision,
+ reason,
+ eligibleSkillPaths: [],
+ eligibleSettingsPaths: [],
+ settingsProjection,
+ resources: {
+ skills: discovered.skills.length ? 'discovered' : 'blocked',
+ settings: discovered.settings.length ? 'discovered' : 'blocked',
+ packages: discovered.packages.length ? 'discovered' : 'blocked',
+ extensions: discovered.extensions.length ? 'discovered' : 'blocked',
+ },
+ launch: {
+ approve: false,
+ writeTrustJson: false,
+ inheritUserPiHome: false,
+ allowPackages: false,
+ allowExtensions: false,
+ },
+ requiresNewSession: true,
+ };
+}
+
+/**
+ * Decide which discovered project resources PR4 may assemble for one session.
+ * This function is intentionally fail-closed and does not claim runtime
+ * `loaded`; only Pi's runtime capability manifest can make that claim.
+ */
+export function evaluatePiProjectTrust(input: {
+ identity: PiProjectIdentityResolution;
+ approval: PiProjectApprovalSnapshot | null;
+ discovered: PiProjectDiscoveredResources;
+ capabilities?: Partial<PiProjectTrustCapabilities>;
+ settingsProjection?: PiProjectSettingsProjection | null;
+}): PiProjectTrustDecision {
+ const { identity, approval, discovered } = input;
+ if (
+ identity.repoRootStatus !== 'resolved' ||
+ !hasLosslessCanonicalEncoding(identity) ||
+ !identity.canonicalWorkingDir ||
+ !identity.canonicalRepoRoot ||
+ !piProjectKey(identity)
+ ) {
+ return emptyDecision(identity, 'unavailable', 'project-identity-unavailable', null, discovered);
+ }
+ const normalizedRepoRoot = normalizePath(identity.canonicalRepoRoot, identity.platform, identity.windowsCaseComparison);
+ const normalizedWorkingDir = normalizePath(identity.canonicalWorkingDir, identity.platform, identity.windowsCaseComparison);
+ if (!normalizedRepoRoot || !normalizedWorkingDir || !isPathWithinRoot(normalizedRepoRoot, normalizedWorkingDir)) {
+ return emptyDecision(identity, 'unavailable', 'working-dir-outside-repo-root', null, discovered);
+ }
+ if (!approval) return emptyDecision(identity, 'unapproved', 'approval-missing', null, discovered);
+ if (approval.status !== 'approved') {
+ return emptyDecision(
+ identity,
+ approval.status,
+ approval.reason ?? `approval-${approval.status}`,
+ approval.revision ?? null,
+ discovered,
+ );
+ }
+
+ const expectedKey = approvalScopeKey(identity, approval.scope);
+ const suppliedKey = normalizeApprovalScopeKey(
+ approval.scopeKey,
+ identity.platform,
+ approval.scope,
+ identity.windowsCaseComparison,
+ );
+ if (!expectedKey || suppliedKey !== expectedKey) {
+ return emptyDecision(identity, 'unapproved', 'approval-scope-mismatch', approval.revision, discovered);
+ }
+
+ const capabilities: PiProjectTrustCapabilities = {
+ explicitSkills: input.capabilities?.explicitSkills === true,
+ projectedSettings: input.capabilities?.projectedSettings === true,
+ packagesDisabled: input.capabilities?.packagesDisabled === true,
+ extensionsDisabled: input.capabilities?.extensionsDisabled === true,
+ };
+ const suppliedProjection = input.settingsProjection;
+ const projectionSnapshot = suppliedProjection ? snapshotSettingsProjection(suppliedProjection) : null;
+ const eligibleCanonicalSettings = canonicalEligibleSettingsPaths(identity, discovered);
+ const settingsSourceIndex = projectionSnapshot ? discovered.settings.indexOf(projectionSnapshot.sourcePath) : -1;
+ const canonicalSettingsSource = settingsSourceIndex >= 0 ? eligibleCanonicalSettings[settingsSourceIndex] : undefined;
+ const settingsProjection =
+ capabilities.projectedSettings &&
+ capabilities.packagesDisabled &&
+ capabilities.extensionsDisabled &&
+ projectionSnapshot &&
+ settingsSourceIndex >= 0 &&
+ eligibleCanonicalSettings.length === discovered.settings.length &&
+ canonicalSettingsSource !== undefined &&
+ projectionSnapshot.sourcePath.length > 0
+ ? snapshotSettingsProjection({ ...projectionSnapshot, sourcePath: canonicalSettingsSource })
+ : null;
+ const settingsEligible = settingsProjection !== null;
+ const eligibleSkillPaths = capabilities.explicitSkills ? canonicalEligibleSkillPaths(identity, discovered) : [];
+ return {
+ ...emptyDecision(identity, 'approved', 'approval-matched', approval.revision, discovered, settingsProjection),
+ eligibleSkillPaths,
+ eligibleSettingsPaths: settingsProjection ? [settingsProjection.sourcePath] : [],
+ resources: {
+ skills: eligibleSkillPaths.length ? 'eligible' : discovered.skills.length ? 'discovered' : 'blocked',
+ settings: settingsEligible && discovered.settings.length ? 'eligible' : discovered.settings.length ? 'discovered' : 'blocked',
+ packages: discovered.packages.length ? 'discovered' : 'blocked',
+ extensions: discovered.extensions.length ? 'discovered' : 'blocked',
+ },
+ };
+}
diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.ts
index 4008c597ba..4cc73b86f9 100644
--- a/packages/maker-core/src/index.ts
+++ b/packages/maker-core/src/index.ts
@@ -15,6 +15,7 @@ export * from './interfaces/index.js';
// agents
export * from './agents/index.js';
+export { evaluatePiProjectTrust, piProjectKey } from './agents/pi/project-trust.js';
// codex app-server transport interface — host 实现自定义 transport (e.g. SSH-bridged
// for remote codex) 时需要这个接口形状。
diff --git a/packages/maker-core/src/types/index.ts b/packages/maker-core/src/types/index.ts
index 3b8ce2ff06..2a0d31a1b7 100644
--- a/packages/maker-core/src/types/index.ts
+++ b/packages/maker-core/src/types/index.ts
@@ -8,3 +8,4 @@ export * from './customizations.js';
export * from './pi-runtime-capabilities.js';
export * from './memory.js';
export * from './account-rate-limits.js';
+export * from './pi-project-trust.js';
diff --git a/packages/maker-core/src/types/pi-project-trust.ts b/packages/maker-core/src/types/pi-project-trust.ts
new file mode 100644
index 0000000000..c996351b6b
--- /dev/null
+++ b/packages/maker-core/src/types/pi-project-trust.ts
@@ -0,0 +1,145 @@
+/**
+ * Cindy-managed Pi project trust contract.
+ *
+ * This is deliberately a host-facing contract, not a Pi runtime manifest. It
+ * contains no filesystem access and never writes trust.json or starts Pi.
+ */
+
+export type PiProjectTrustStatus =
+ | 'approved'
+ | 'unapproved'
+ | 'revoked'
+ | 'stale'
+ | 'unavailable';
+
+export type PiProjectTrustScope = 'working-dir' | 'repo-root';
+
+export type PiProjectWindowsCaseComparison = 'ordinal-insensitive' | 'case-sensitive' | 'unavailable';
+
+export type PiProjectResourceKind = 'skills' | 'settings' | 'packages' | 'extensions';
+
+export type PiProjectResourceDisposition = 'eligible' | 'discovered' | 'blocked';
+
+/** Canonical paths are supplied by the host's audited resolver. */
+export interface PiProjectIdentityResolution {
+ workingDir: string;
+ /** realpath(workingDir), or null when it cannot be resolved. */
+ canonicalWorkingDir: string | null;
+ /** realpath(git repository root), or null when resolution failed. */
+ canonicalRepoRoot: string | null;
+ /** A resolved root is required; raw git output is not sufficient. */
+ repoRootStatus: 'resolved' | 'unavailable';
+ /** Trusted host platform semantics; callers must not infer this from a path string. */
+ platform: 'posix' | 'win32';
+ /** Must match the platform and round-trip without replacement; otherwise fail closed. */
+ canonicalPathEncoding: 'utf8-lossless' | 'utf16-lossless' | 'unavailable';
+ /** Host-provided filesystem comparison identity; required for usable win32 keys. */
+ windowsCaseComparison?: PiProjectWindowsCaseComparison;
+}
+/**
+ * Result returned by Cindy's existing project-approval authority. The
+ * authority owns persistence, audit history and revocation; this package only
+ * consumes its immutable snapshot.
+ */
+export type PiProjectApprovalSnapshot =
+ | {
+ status: 'approved';
+ scope: PiProjectTrustScope;
+ scopeKey: string;
+ revision: string;
+ approvedAt?: string;
+ }
+ | {
+ status: 'revoked' | 'stale';
+ scope?: PiProjectTrustScope;
+ scopeKey?: string;
+ revision?: string;
+ reason?: string;
+ }
+ | {
+ status: 'unapproved';
+ revision?: string;
+ reason?: string;
+ }
+ | {
+ status: 'unavailable';
+ revision?: string;
+ reason: string;
+ };
+
+export interface PiProjectDiscoveredResources {
+ skills: readonly string[];
+ /** Legacy canonical skill paths are retained for additive compatibility but are not eligible evidence. */
+ canonicalSkills?: readonly string[];
+ /** Host evidence pairing each discovered skill path with its realpath. */
+ canonicalSkillEvidence?: readonly PiProjectCanonicalPathEvidence[];
+ settings: readonly string[];
+ /** Host evidence pairing each discovered settings path with its realpath. */
+ canonicalSettings?: readonly PiProjectCanonicalPathEvidence[];
+ packages: readonly string[];
+ extensions: readonly string[];
+}
+
+export interface PiProjectCanonicalPathEvidence {
+ /** Exact lexical path present in the corresponding discovered array entry. */
+ readonly discoveredPath: string;
+ /** Host-resolved realpath used for repo-boundary checks and assembly. */
+ readonly canonicalPath: string;
+}
+
+/** Capabilities proven by the pinned Pi fixture and the PR4 assembler. */
+export interface PiProjectTrustCapabilities {
+ /** PR4 can pass individual skill paths without enabling project trust; omitted/false is fail-closed. */
+ explicitSkills: boolean;
+ /** PR4 has a reviewed projection for safe project settings fields; omitted/false is fail-closed. */
+ projectedSettings: boolean;
+ /** Explicit hard-gate proof: project package installation is prevented. */
+ packagesDisabled: boolean;
+ /** Explicit hard-gate proof: project extensions are not loaded or executed. */
+ extensionsDisabled: boolean;
+}
+
+export interface PiProjectSettingsValues {
+ /** Pinned Pi v0.83.0 compaction thresholds; no resource-loading fields are permitted. */
+ readonly compaction?: {
+ readonly reserveTokens?: number;
+ readonly keepRecentTokens?: number;
+ };
+}
+
+/** Reviewed settings fields that PR4 may pass to Pi. Raw settings files are never eligible. */
+export interface PiProjectSettingsProjection {
+ /** The discovered settings source represented by this projection. */
+ readonly sourcePath: string;
+ /** Exact field allowlist; unknown and future Pi settings fail closed. */
+ readonly values: Readonly<PiProjectSettingsValues>;
+ /** Approval/discovery revision used to audit the projection, when available. */
+ readonly revision?: string;
+}
+
+export interface PiProjectTrustDecision {
+ status: PiProjectTrustStatus;
+ /** `${canonicalRepoRoot}\0${canonicalWorkingDir}`; null when unavailable. */
+ projectKey: string | null;
+ canonicalWorkingDir: string | null;
+ canonicalRepoRoot: string | null;
+ approvalRevision: string | null;
+ reason: string;
+ /** Eligible inputs for PR4. None of these means Pi reported "loaded". */
+ eligibleSkillPaths: readonly string[];
+ /** Deprecated compatibility field; contains only the reviewed projection source path. */
+ eligibleSettingsPaths: readonly string[];
+ /** Reviewed settings data for PR4; null means no settings may be assembled. */
+ settingsProjection: PiProjectSettingsProjection | null;
+ resources: Record<PiProjectResourceKind, PiProjectResourceDisposition>;
+ /** Required launch policy; assembly details remain owned by PR4. */
+ launch: {
+ approve: false;
+ writeTrustJson: false;
+ inheritUserPiHome: false;
+ allowPackages: false;
+ allowExtensions: false;
+ };
+ /** Trust inputs are startup-only; this contract conservatively requires a fresh Pi session for every decision. */
+ requiresNewSession: boolean;
+}