Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 继承用户全局约定到隔离运行目录 (#4126)
Chris Zhangafa8a51b221c
diff --git a/apps/desktop/src/main/maker-host/__tests__/piRemoteFileOps.integration.test.ts b/apps/desktop/src/main/maker-host/__tests__/piRemoteFileOps.integration.test.tsnew file mode 100644index 0000000000..5db273ecf1--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/piRemoteFileOps.integration.test.ts@@ -0,0 +1,79 @@+import { execFile } from 'node:child_process';+import { promises as fs } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';+import type { RemoteHost } from '@cindy/maker-remote-ssh';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { readPiGlobalContext } from '../../../../../../packages/maker-core/src/agents/pi/global-context.js';+import { createRemotePiFileOps } from '../pi-remote-transport.js';++vi.mock('../pi-manager-client.js', () => ({ piManagerEnsure: vi.fn(), piManagerKill: vi.fn() }));++const execFileAsync = promisify(execFile);++// SSH execution targets POSIX hosts. Exercise the real generated shell/stat+// command locally with a synthetic remote HOME, without opening an SSH account.+// symlink-platform-skip: Windows cannot enforce POSIX directory search permissions or run the target host's native bash/stat filesystem semantics.+describe.skipIf(process.platform === 'win32')('remote Pi context filesystem errors (real shell)', () => {+ let root: string;+ let ops: ReturnType<typeof createRemotePiFileOps>;+ beforeEach(async () => {+ root = await fs.mkdtemp(path.join(tmpdir(), 'pi-remote-stat-'));+ const host = {+ exec: async (command: string) => {+ try {+ const result = await execFileAsync('bash', ['-c', command], {+ env: { ...process.env, HOME: root }, timeout: 10_000,+ });+ return { ...result, exitCode: 0 };+ } catch (error) {+ const result = error as { code: number; stdout: string; stderr: string };+ if (typeof result.code !== 'number') throw error;+ return { exitCode: result.code, stdout: result.stdout, stderr: result.stderr };+ }+ },+ } as unknown as RemoteHost;+ ops = createRemotePiFileOps(host);+ });+ afterEach(async () => {+ await fs.chmod(path.join(root, 'denied'), 0o700).catch(() => {});+ await fs.rm(root, { recursive: true, force: true });+ });++ it('distinguishes missing files, directories and symlinks without interpreting path syntax', async () => {+ await expect(ops.stat('$HOME/absent/AGENTS.md')).resolves.toBeNull();+ await expect(ops.stat('$HOME/.')).resolves.toEqual({ isFile: false });+ const name = "rules '$() `literal` .md";+ await fs.writeFile(path.join(root, name), 'rules');+ await fs.symlink(path.join(root, name), path.join(root, 'AGENTS.md'));+ await expect(ops.stat(`$HOME/${name}`)).resolves.toEqual({ isFile: true });+ await expect(readPiGlobalContext('$HOME', ops)).resolves.toEqual([{ name: 'AGENTS.md', content: 'rules' }]);+ await fs.unlink(path.join(root, name));+ await expect(ops.stat('$HOME/AGENTS.md')).resolves.toBeNull();+ await fs.symlink(path.join(root, 'loop'), path.join(root, 'loop'));+ await expect(ops.stat('$HOME/loop')).rejects.toThrow('remote stat failed');+ });++ it('propagates an unsearchable directory as EACCES, including through a symlink', async (ctx) => {+ const denied = path.join(root, 'denied');+ await fs.mkdir(denied);+ await fs.writeFile(path.join(denied, 'AGENTS.md'), 'must not disappear');+ await fs.symlink(path.join(denied, 'AGENTS.md'), path.join(root, 'AGENTS.md'));+ await fs.chmod(denied, 0);+ // Root/ACL-capable environments may bypass mode bits; unit tests still+ // verify errno propagation independently of the runner's identity.+ if (await fs.stat(path.join(denied, 'AGENTS.md')).then(() => true, () => false)) ctx.skip();+ await expect(readPiGlobalContext('$HOME/denied', ops)).rejects.toThrow('EACCES');+ await expect(readPiGlobalContext('$HOME', ops)).rejects.toThrow('EACCES');+ });++ it('propagates read denial for a file that can still be statted', async (ctx) => {+ const file = path.join(root, 'AGENTS.md');+ await fs.writeFile(file, 'private rules');+ await fs.chmod(file, 0);+ if (await fs.readFile(file).then(() => true, () => false)) ctx.skip();+ await expect(ops.stat('$HOME/AGENTS.md')).resolves.toEqual({ isFile: true });+ await expect(readPiGlobalContext('$HOME', ops)).rejects.toThrow('remote read failed');+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts b/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.tsindex 9764117af4..88c3c6cb81 100644--- a/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piRemoteTransport.test.ts@@ -170,6 +170,18 @@ describe('pi remote file ops command hygiene', () => {expect(await ops.stat('/nope')).toBeNull();});+ it.each(['EACCES', 'EPERM', 'EIO'])('stat rejects %s instead of reporting a missing file', async (code) => {+ const { host } = makeHostExec('MISSING\n', 1, code);+ await expect(createRemotePiFileOps(host).stat('/private/AGENTS.md'))+ .rejects.toThrow(`remote stat failed (exit 1): ${code}`);+ });++ it('stat rejects malformed successful responses without exposing command output', async () => {+ const { host } = fakeHost('unexpected remote output');+ await expect(createRemotePiFileOps(host).stat('/private/AGENTS.md'))+ .rejects.toThrow('remote stat returned an invalid response');+ });+it('hashes the complete remote file in place without transferring its contents', async () => {const digest = 'a'.repeat(64);const { calls, host } = makeHostExec(`${digest}\n`);diff --git a/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts b/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.tsindex ce57fe0132..4f8cec36cc 100644--- a/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts@@ -1,11 +1,12 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import os, { tmpdir } from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const state = vi.hoisted(() => ({args: [] as string[],+ env: {} as Record<string, string | undefined>,binaryPath: '',ripgrepPath: '',userDataPath: '',@@ -91,8 +92,9 @@ vi.mock('../../logger.js', () => ({// args 经 createTransport → createPiStdioTransport 传递(不在 PiRpcProcess 构造// 参数里, 自轮 22 起); 测试从 stdio transport 的 opts 捕获 spawn args。vi.mock('../../../../../../packages/maker-core/src/agents/pi/transport.js', () => ({- createPiStdioTransport: (opts: { args: string[] }) => {+ createPiStdioTransport: (opts: { args: string[]; env: Record<string, string | undefined> }) => {state.args = opts.args;+ state.env = opts.env;return {} as never;},}));@@ -143,6 +145,10 @@ describe('buildPiAgent roster prompt assembly', () => {beforeEach(() => {state.args = [];root = mkdtempSync(path.join(tmpdir(), 'pi-roster-assembly-'));+ vi.spyOn(os, 'homedir').mockReturnValue(root);+ vi.stubEnv('PI_CODING_AGENT_DIR', path.join(root, 'native-pi-home'));+ mkdirSync(process.env.PI_CODING_AGENT_DIR!);+ writeFileSync(path.join(process.env.PI_CODING_AGENT_DIR!, 'AGENTS.md'), 'host global context canary');workingDir = path.join(root, 'workspace');state.userDataPath = path.join(root, 'user-data');state.binaryPath = path.join(root, 'pi');@@ -160,11 +166,19 @@ describe('buildPiAgent roster prompt assembly', () => {});afterEach(() => {+ vi.unstubAllEnvs();+ vi.restoreAllMocks();setXdGatewayModels([]);rmSync(root, { recursive: true, force: true });});- it('forwards the host roster callback through real PiAgent startSession spawn args', async () => {+ it.each(['default', 'override', 'tilde'])('forwards roster and %s user context through real PiAgent startup', async (source) => {+ if (source !== 'override') {+ const defaultHome = path.join(root, '.pi', 'agent');+ mkdirSync(defaultHome, { recursive: true });+ writeFileSync(path.join(defaultHome, 'AGENTS.md'), 'host global context canary');+ vi.stubEnv('PI_CODING_AGENT_DIR', source === 'tilde' ? '~/.pi/agent' : undefined);+ }const getGhostRosterPrompt = vi.fn(({ workingDir: cwd }: { workingDir?: string }) =>cwd ? '<ghost-roster>\n{"id":"art"}\n</ghost-roster>' : '',);@@ -198,6 +212,8 @@ describe('buildPiAgent roster prompt assembly', () => {'<ghost-roster>\n{"id":"art"}\n</ghost-roster>',);expect(getGhostRosterPrompt).toHaveBeenCalledWith({ workingDir });+ expect(readFileSync(path.join(state.env.PI_CODING_AGENT_DIR!, 'AGENTS.md'), 'utf8'))+ .toBe('host global context canary');await handle.close();});});diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex c115d1918d..5bf3b142a4 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -1853,6 +1853,13 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {if (remoteHostId) return '$HOME/.xdt-server/v1/pi-agent-home';return path.join(app.getPath('userData'), 'pi-agent-home');},+ resolvePiGlobalContextHome: (remoteHostId) => {+ if (remoteHostId) return '$HOME/.pi/agent';+ const override = process.env.PI_CODING_AGENT_DIR;+ return override+ ? path.resolve(override.replace(/^~(?=$|[\\/])/, () => os.homedir()))+ : path.join(os.homedir(), '.pi', 'agent');+ },resolvePiManagedPackageResources: resolveManagedPiPackageResources,resolvePiNativePackagePaths: resolveManagedPiNativePackagePaths,mutatePiManagedPackage: (request) => mutateAuthorizedPiManagedPackage(diff --git a/apps/desktop/src/main/maker-host/pi-remote-transport.ts b/apps/desktop/src/main/maker-host/pi-remote-transport.tsindex 478bbfdb7f..d09fa6490f 100644--- a/apps/desktop/src/main/maker-host/pi-remote-transport.ts+++ b/apps/desktop/src/main/maker-host/pi-remote-transport.ts@@ -175,26 +175,49 @@ export function createRemotePiFileOps(remoteHost: RemoteHost): PiRemoteFileOps {},async stat(file: string): Promise<{ isFile: boolean } | null> {+ // Shell -f/-e cannot distinguish ENOENT from an unsearchable parent.+ // Bootstrap can reach this before bundled Node is installed. Use the+ // platform stat utility (GNU/Linux or BSD/macOS), with C-locale errno+ // suffixes, and only treat an explicit ENOENT diagnostic as missing.// 轮 43 P1(codex-connector):eval 换 H=$(printf) + 参数替换, 无注入风险。const script = `P=${shellQuote(file)}case "$P" in '$HOME'/*) H=$(printf '%s' "$HOME"); [ "\${P#\\\$HOME}" != "$P" ] && P="\${H}\${P#\\\$HOME}";; esac-if [ -f "$P" ]; then- printf 'FILE\\n'-elif [ -e "$P" ]; then- printf 'DIR\\n'+if stat -c '%F' / >/dev/null 2>&1; then+ RESULT=$(LC_ALL=C stat -L -c '%F' -- "$P" 2>&1)else- printf 'MISSING\\n'+ RESULT=$(LC_ALL=C stat -L -f '%HT' -- "$P" 2>&1)+fi+STATUS=$?+if [ "$STATUS" -ne 0 ]; then+ case "$RESULT" in+ *': No such file or directory') printf 'MISSING\\n' ;;+ *': Permission denied') printf 'EACCES' >&2; exit 1 ;;+ *) exit 1 ;;+ esac+else+ case "$RESULT" in+ 'regular file'|'regular empty file'|'Regular File') printf 'FILE\\n' ;;+ # BSD stat -L falls back to lstat only when the link target is missing.+ 'Symbolic Link') printf 'MISSING\\n' ;;+ *) printf 'DIR\\n' ;;+ esacfi`;const result = await remoteHost.exec(`bash -c ${shellQuote(script)}`, {timeoutMs: 10_000,label: 'pi-remote-stat',});- const kind = result.stdout.trim().split(/\r?\n/).pop() ?? 'MISSING';+ if (result.exitCode !== 0) {+ const code = result.stderr.trim();+ const reason = /^E[A-Z0-9]+$/.test(code) ? `: ${code}` : '';+ throw new Error(`remote stat failed (exit ${result.exitCode})${reason}`);+ }+ const kind = result.stdout.trim();if (kind === 'FILE') return { isFile: true };if (kind === 'DIR') return { isFile: false };- return null;+ if (kind === 'MISSING') return null;+ throw new Error('remote stat returned an invalid response');},async readFile(file: string, maxBytes = 1_048_576): Promise<string> {diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 3ec5a3d70d..e4ecc8771c 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -87,6 +87,25 @@ SSH 不套用本机限核值。沿用现有默认值与 override 存储,不新未配置 Pi 百分比时不写 `reserveTokens`,沿用 Pi 默认 16384。+### 全局约定入口++普通 Pi 任务从执行设备用户的 `~/.pi/agent` 继承约定,按 Pi 原生顺序选择首个文件:+`AGENTS.override.md` → `AGENTS.md` → `AGENTS.MD` → `CLAUDE.md` → `CLAUDE.MD`。+本机尊重启动 Cindy 时的 `PI_CODING_AGENT_DIR`+覆写(支持 `~`)。SSH 使用远端 `$HOME/.pi/agent`,不读取控制端个人文件;手机/设备互联+控制本机任务复用桌面链路。Bot 保持 `--no-context-files`,不读取或复制这些全局约定。++每次启动读取软链目标并复制内容到独立 `configHome`,不建立指向用户文件的可写链接。+用户更新约定后,新启动的任务读取新版;运行中的任务保留启动快照。SSH 的配置目录身份+包含约定内容哈希,内容不变可以 attach,变化或删除不能覆盖仍存活的旧运行时快照。+只继承上述约定文件,不整目录复制 settings、auth、extensions,也不复制会替换 Pi 默认+系统提示词的 `SYSTEM.md`。远端沿用文件读取通道的 4 MiB 上限,触及上限明确报错,不能+静默截断。文件不存在允许正常启动,读取/写入失败须报错,不能假称约定已加载。+远端探测使用系统 `stat`(GNU/BSD,固定 C locale)区分明确缺失与权限/探测失败,+不能用 shell `-f`/`-e` 的 false 推断文件不存在,也不能依赖首次启动尚未安装的 Node。+内建 Pi 子代理从父任务 `configHome` 复制选中的约定快照到自己的持久运行目录;+不重读用户原文件,父任务卸载后子代理仍保留同一份约定。+## 3. 设计原则(Chris 2026-07-30 裁决)- PI 是 Cindy 未来的基座 harness。diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex eac4f419d9..aa315db92d 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -621,6 +621,8 @@ export interface AgentDeps {* 其它 agent 不消费此字段。*/resolvePiAgentHome?: (remoteHostId?: string | null) => string | undefined;+ /** Native user context root, separate from Cindy's models/auth runtime home. */+ resolvePiGlobalContextHome?: (remoteHostId?: string | null) => string | undefined;/*** Pi-only: advisory metadata for Cindy UI/command projection. This resolverdiff --git a/packages/maker-core/src/agents/pi/__tests__/global-context.test.ts b/packages/maker-core/src/agents/pi/__tests__/global-context.test.tsnew file mode 100644index 0000000000..85fcf68c0e--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/global-context.test.ts@@ -0,0 +1,63 @@+import { promises as fs } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { PiRemoteFileOps } from '../../base-agent.js';+import { readPiGlobalContext } from '../global-context.js';++describe('Pi global context snapshot', () => {+ let root: string;+ beforeEach(async () => { root = await fs.mkdtemp(path.join(tmpdir(), 'pi-global-context-')); });+ afterEach(async () => { await fs.rm(root, { recursive: true, force: true }); });++ it('reads only native context candidates and follows a user symlink outside Pi home', async () => {+ const home = path.join(root, 'pi');+ await fs.mkdir(home);+ const target = path.join(root, 'shared-global.md');+ await fs.writeFile(target, 'shared rules');+ try {+ await fs.symlink(target, path.join(home, 'AGENTS.md'));+ } catch (error) {+ // Windows runners without symlink privilege still exercise ordinary files.+ if (process.platform !== 'win32' || (error as NodeJS.ErrnoException).code !== 'EPERM') throw error;+ await fs.copyFile(target, path.join(home, 'AGENTS.md'));+ }+ for (const name of ['CLAUDE.md', 'SYSTEM.md', 'APPEND_SYSTEM.md', 'settings.json', 'auth.json']) {+ await fs.writeFile(path.join(home, name), name);+ }+ expect(await readPiGlobalContext(home)).toEqual([+ { name: 'AGENTS.md', content: 'shared rules' },+ ]);+ await fs.writeFile(path.join(home, 'AGENTS.override.md'), 'override');+ expect(await readPiGlobalContext(home)).toEqual([{ name: 'AGENTS.override.md', content: 'override' }]);+ });++ it('allows missing context and skips non-files like native Pi', async () => {+ expect(await readPiGlobalContext(undefined)).toEqual([]);+ expect(await readPiGlobalContext(root)).toEqual([]);+ await fs.mkdir(path.join(root, 'AGENTS.md'));+ await fs.writeFile(path.join(root, 'CLAUDE.MD'), 'uppercase fallback');+ const files = await readPiGlobalContext(root);+ expect(files).toMatchObject([{ content: 'uppercase fallback' }]);+ expect(files[0].name.toLowerCase()).toBe('claude.md');+ });++ it('uses only remote file operations and rejects truncated remote reads', async () => {+ const remote = {+ stat: vi.fn(async (file: string) => ({ isFile: file.endsWith('/AGENTS.md') })),+ readFile: vi.fn(async () => 'remote rules'),+ } as unknown as PiRemoteFileOps;+ expect(await readPiGlobalContext('$HOME/.pi/agent', remote)).toEqual([+ { name: 'AGENTS.md', content: 'remote rules' },+ ]);+ expect(remote.readFile).toHaveBeenCalledWith('$HOME/.pi/agent/AGENTS.md', 4_194_304);+ vi.mocked(remote.readFile).mockResolvedValue('x'.repeat(4_194_304));+ await expect(readPiGlobalContext('$HOME/.pi/agent', remote)).rejects.toThrow('remote read limit');+ vi.mocked(remote.readFile).mockRejectedValue(new Error('SSH unavailable'));+ await expect(readPiGlobalContext('$HOME/.pi/agent', remote)).rejects.toThrow('SSH unavailable');+ vi.mocked(remote.readFile).mockClear();+ vi.mocked(remote.stat).mockRejectedValue(new Error('remote stat failed (exit 1): EACCES'));+ await expect(readPiGlobalContext('$HOME/.pi/agent', remote)).rejects.toThrow('EACCES');+ expect(remote.readFile).not.toHaveBeenCalled();+ });+});diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.tsindex 961c10e969..533cdcc167 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts@@ -431,6 +431,59 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa};}+ it.each(['CLAUDE.md', 'AGENTS.md', 'AGENTS.override.md'])(+ 'loads global %s with native precedence and keeps the prompt stable across turns',+ { timeout: 60_000 },+ async (winner) => {+ const root = mkdtempSync(path.join(tmpdir(), 'pi-global-int-'));+ const userHome = path.join(root, 'native-user');+ const workingDir = path.join(root, 'workspace');+ mkdirSync(userHome);+ mkdirSync(workingDir);+ const candidates = ['CLAUDE.md', 'AGENTS.md', 'AGENTS.override.md'];+ for (const name of candidates.slice(0, candidates.indexOf(winner) + 1)) {+ writeFileSync(path.join(userHome, name), `GLOBAL_CANARY_${name}`);+ }+ writeFileSync(path.join(userHome, 'SYSTEM.md'), 'MUST_NOT_REPLACE_PI_SYSTEM');+ writeFileSync(path.join(workingDir, 'AGENTS.md'), 'PROJECT_CONTEXT_CANARY');+ const agent = new PiAgent({ ...buildDeps(), resolvePiGlobalContextHome: () => userHome });+ let handle: AgentSessionHandle | undefined;+ try {+ handle = await agent.startSession({ sessionId: `global-${winner}`, workingDir, model: 'pi-test-model' });+ const systems: unknown[] = [];+ for (let turn = 0; turn < 2; turn++) {+ const requestStart = seenRequests.length;+ const events: AgentEvent[] = [];+ const done = (async () => {+ for await (const event of handle!.events()) {+ events.push(event);+ if (event.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: `ping ${turn}` });+ await done;+ expect(events.filter((event) => event.type === 'error')).toEqual([]);+ const request = seenRequests.slice(requestStart).find((entry) => entry.url.includes('/messages'))!;+ expect(request, JSON.stringify(events)).toBeDefined();+ const system = JSON.parse(request.body).system;+ const text = JSON.stringify(system);+ expect(text).toContain(`GLOBAL_CANARY_${winner}`);+ for (const loser of candidates.filter((name) => name !== winner)) {+ expect(text).not.toContain(`GLOBAL_CANARY_${loser}`);+ }+ expect(text).toContain('PROJECT_CONTEXT_CANARY');+ expect(text).not.toContain('MUST_NOT_REPLACE_PI_SYSTEM');+ systems.push(system);+ writeFileSync(path.join(userHome, winner), 'CHANGED_AFTER_START');+ }+ expect(systems[1]).toEqual(systems[0]);+ } finally {+ await handle?.close();+ rmSync(root, { recursive: true, force: true });+ }+ },+ );+it('startSession → send → streams text and settles → usage/cost tracked → close',{ timeout: 60_000 },@@ -2920,6 +2973,11 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa// 端到端:父会话调 subagent → Cindy 自有扩展 spawn 真 pi 子进程 → 子进程走同一// fake gateway → 结论回父模型;进度经工具原生 onUpdate 翻成 agent_task_update。const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-subagent-'));+ const nativeHome = path.join(workingDir, 'native-pi-home');+ mkdirSync(nativeHome);+ const globalFile = path.join(nativeHome, 'AGENTS.override.md');+ writeFileSync(globalFile, 'SUBAGENT_GLOBAL_CONTEXT_SNAPSHOT');+ const requestStart = seenRequests.length;try {scriptedResponses.length = 0;scriptedResponses.push(@@ -2929,7 +2987,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewaanthropicStreamBody('parent turn finished'),);- const agent = new PiAgent(buildDeps());+ const agent = new PiAgent({ ...buildDeps(), resolvePiGlobalContextHome: () => nativeHome });const resolverTools: string[] = [];let handle: AgentSessionHandle | null = null;const events: AgentEvent[] = [];@@ -2940,6 +2998,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewamodel: 'pi-test-model',permissionMode: 'ask',});+ writeFileSync(globalFile, 'GLOBAL_CHANGED_AFTER_PARENT_START');handle.setInteractionResolver?.(async (req) => {resolverTools.push((req as { toolName?: string }).toolName ?? '?');return {@@ -2962,6 +3021,17 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa// Ask 档仍逐次由用户确认 spawn;Auto 档另有回归证明 spawn 本身静默放行。expect(resolverTools).toEqual(['subagent']);+ const requests = seenRequests.slice(requestStart);+ // Gateway attribution deliberately retains the parent session id.+ const childRequests = requests.filter((request) =>+ JSON.stringify(JSON.parse(request.body).system).includes('You are a scout subagent.'),+ );+ expect(childRequests.length).toBeGreaterThan(0);+ for (const request of requests) {+ const system = JSON.stringify(JSON.parse(request.body).system);+ expect(system).toContain('SUBAGENT_GLOBAL_CONTEXT_SNAPSHOT');+ expect(system).not.toContain('GLOBAL_CHANGED_AFTER_PARENT_START');+ }// 卡片走的是与 Claude / Codex 同一条 agent_task_update 通道。const cardUpdates = eventsdiff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex e505a3de42..499bebb334 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -2610,6 +2610,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {it('keeps Bot tools and memory independent of global memory while honoring task permissions', async () => {const deps = buildDeps(undefined, false, { serverNames: ['cindy_memory', 'cindy_helper'] });+ deps.resolvePiGlobalContextHome = vi.fn(() => { throw new Error('Bot must not read user context'); });deps.getGhostRosterPrompt = vi.fn(() => 'BOT ROSTER');deps.runtimeConfig.memoryEnabled = false;const handle = await new PiAgent(deps).startSession({@@ -2646,6 +2647,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {path.posix.join(captured.env.PI_CODING_AGENT_DIR!, 'internal-extensions', 'cindy-subagent.ts'),]));expect(captured.args).toContain('--no-context-files');+ expect(deps.resolvePiGlobalContextHome).not.toHaveBeenCalled();const promptIndex = captured.args.indexOf('--append-system-prompt');expect(captured.args[promptIndex + 1]).toContain('BOT SOUL');expect(captured.args[promptIndex + 1]).not.toContain('BOT ROSTER');diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex b9a6390b80..472da415c5 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts@@ -5441,13 +5441,22 @@ describe("Pi provider-aware model routing", () => {killRemoteSession: async () => {},};const capturedRemoteEnvs: Array<Record<string, string | undefined>> = [];+ let globalRules: string | undefined = 'remote global v1';+ const contextWrites: Array<[string, string]> = [];const remoteFileOps = {mkdirp: async () => {},- writeFile: async () => {},- stat: async () => ({ isFile: true }),+ writeFile: async (file: string, content: string) => {+ if (file.endsWith('/AGENTS.md')) contextWrites.push([file, content]);+ },+ stat: async (file: string) => file.startsWith('$HOME/.pi/agent/')+ ? { isFile: file.endsWith('/AGENTS.md') && globalRules !== undefined }+ : { isFile: true },rm: async () => {},listDir: async () => [],- readFile: async () => { throw new Error("Unexpected remote file read in empty directory fixture"); },+ readFile: async (file: string) => {+ expect(file).toBe('$HOME/.pi/agent/AGENTS.md');+ return globalRules!;+ },sha256File: async () => { throw new Error("Unexpected remote file hash in empty directory fixture"); },};const startRemote = async (permissionMode: "ask" | "bypassPermissions") => {@@ -5464,6 +5473,10 @@ describe("Pi provider-aware model routing", () => {return remoteStub;},getRemotePiFileOps: () => remoteFileOps,+ resolvePiGlobalContextHome: (hostId) => {+ expect(hostId).toBe('remote-host');+ return '$HOME/.pi/agent';+ },});const handle = await agent.startSession({sessionId: "remote-perm-hash",@@ -5496,6 +5509,19 @@ describe("Pi provider-aware model routing", () => {expect(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_FILE).toContain(capturedRemoteEnvs[1]!.CINDY_PI_PERMISSION_HASH,);+ const originalHome = capturedRemoteEnvs[1]!.PI_CODING_AGENT_DIR;+ await startRemote('bypassPermissions');+ expect(capturedRemoteEnvs[2]!.PI_CODING_AGENT_DIR).toBe(originalHome);+ globalRules = 'remote global v2';+ await startRemote('bypassPermissions');+ expect(capturedRemoteEnvs[3]!.PI_CODING_AGENT_DIR).not.toBe(originalHome);+ expect(contextWrites.at(-1)).toEqual([+ path.posix.join(capturedRemoteEnvs[3]!.PI_CODING_AGENT_DIR!, 'AGENTS.md'), 'remote global v2',+ ]);+ globalRules = undefined;+ await startRemote('bypassPermissions');+ expect(capturedRemoteEnvs[4]!.PI_CODING_AGENT_DIR).not.toBe(capturedRemoteEnvs[3]!.PI_CODING_AGENT_DIR);+ expect(contextWrites).toHaveLength(4);});it("puts a deterministic Cindy extension bundle hash into remote spawn env", async () => {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.tsindex 2cee4490af..88cebc9648 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@@ -2326,6 +2326,9 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {// (PI_CODING_AGENT_DIR = agentHome/run-tmp/<hex>)承载 models.json,close/退出时清理。it('isolates each session config home under run-tmp and keeps concurrent sessions independent', async () => {const { existsSync } = await import('node:fs');+ const nativeHome = path.join(agentHome, 'native-user-home');+ mkdirSync(nativeHome);+ writeFileSync(path.join(nativeHome, 'AGENTS.md'), 'global rules v1');const skillOne = path.join(cwd, '.pi', 'skills', 'one');const skillTwo = path.join(cwd, '.agents', 'skills', 'two');for (const skillPath of [skillOne, skillTwo]) {@@ -2333,6 +2336,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {writeFileSync(path.join(skillPath, 'SKILL.md'), '# isolated\n');}const agent = new PiAgent(buildDeps({+ resolvePiGlobalContextHome: () => nativeHome,resolvePiProjectTrustInput: async ({ sessionId, workingDir }) => approvedInput(workingDir,`rev-${sessionId}`,@@ -2360,6 +2364,16 @@ 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(readFileSync(path.join(home1, 'AGENTS.md'), 'utf8')).toBe('global rules v1');+ expect(readFileSync(path.join(home2, 'AGENTS.md'), 'utf8')).toBe('global rules v1');+ writeFileSync(path.join(nativeHome, 'AGENTS.md'), 'global rules v2');+ expect(readFileSync(path.join(home1, 'AGENTS.md'), 'utf8')).toBe('global rules v1');+ const h3 = await agent.startSession({ sessionId: 's3', workingDir: cwd, model: 'm' });+ const home3 = knobs.spawnedEnvs[indexForSession('s3')].PI_CODING_AGENT_DIR!;+ expect(readFileSync(path.join(home3, 'AGENTS.md'), 'utf8')).toBe('global rules v2');+ writeFileSync(path.join(home3, 'AGENTS.md'), 'runtime edit');+ expect(readFileSync(path.join(nativeHome, 'AGENTS.md'), 'utf8')).toBe('global rules v2');+ await h3.close();expect(repeatedArgValues(knobs.spawnedArgs[s1Index]!, '--skill')).toEqual([stagedSkillPath(home1, 0, skillOne),]);diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-source.tsindex 24610347bb..37f397a21a 100644--- a/packages/maker-core/src/agents/pi/cindy-subagent-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-subagent-source.ts@@ -33,6 +33,8 @@* 更新方式:PiAgent 每次 startSession 覆写该文件。*/+import { PI_GLOBAL_CONTEXT_FILE_NAMES } from './global-context.js';+/** 工具名 —— 与 `@cindy/maker-shared` 的 `PI_SUBAGENT_TOOL_NAME` 必须一致(卡片判据靠它)。 */export const CINDY_SUBAGENT_TOOL_NAME = 'subagent';@@ -896,6 +898,19 @@ async function launchDurableRun(binary, tasks, runtime, taskId, mode, context, dtry { chmodSync(permissionFile, 0o600); } catch (err) { /* best effort on Windows */ }mkdirSync(childConfigHome, { recursive: true, mode: 0o700 });copyFileSync(join(configHome, 'models.json'), join(childConfigHome, 'models.json'));+ // Inherit the parent's frozen rules, not the possibly edited native user+ // home. Child config outlives the parent when a durable run is detached.+ for (const name of ${JSON.stringify(PI_GLOBAL_CONTEXT_FILE_NAMES)}) {+ const childContextFile = join(childConfigHome, name);+ try {+ copyFileSync(join(configHome, name), childContextFile);+ } catch (error) {+ if (error && error.code === 'ENOENT') continue;+ throw error;+ }+ try { chmodSync(childContextFile, 0o600); } catch (err) { /* best effort on Windows */ }+ break;+ }copyFileSync(join(configHome, 'internal-extensions', 'cindy-bridge.ts'), bridgeExtension);try { chmodSync(join(childConfigHome, 'models.json'), 0o600); } catch (err) { /* best effort on Windows */ }try { chmodSync(bridgeExtension, 0o600); } catch (err) { /* best effort on Windows */ }diff --git a/packages/maker-core/src/agents/pi/global-context.ts b/packages/maker-core/src/agents/pi/global-context.tsnew file mode 100644index 0000000000..ec7477214d--- /dev/null+++ b/packages/maker-core/src/agents/pi/global-context.ts@@ -0,0 +1,42 @@+import { promises as fs } from 'node:fs';+import path from 'node:path';+import type { PiRemoteFileOps } from '../base-agent.js';++// Pi's native candidate order, including case-sensitive filesystem aliases.+// SYSTEM.md / APPEND_SYSTEM.md are different resources, not context files.+export const PI_GLOBAL_CONTEXT_FILE_NAMES = ['AGENTS.override.md', 'AGENTS.md', 'AGENTS.MD', 'CLAUDE.md', 'CLAUDE.MD'] as const;+const REMOTE_READ_LIMIT = 4_194_304;++/** A launch-time snapshot; never link the writable runtime back to user files. */+export interface PiGlobalContextFile {+ name: (typeof PI_GLOBAL_CONTEXT_FILE_NAMES)[number];+ content: string;+}++export async function readPiGlobalContext(+ home: string | undefined,+ remote?: PiRemoteFileOps,+): Promise<PiGlobalContextFile[]> {+ if (!home) return [];+ for (const name of PI_GLOBAL_CONTEXT_FILE_NAMES) {+ const source = (remote ? path.posix : path).join(home, name);+ if (remote) {+ if (!(await remote.stat(source))?.isFile) continue;+ const content = await remote.readFile(source, REMOTE_READ_LIMIT);+ // Remote reads are bounded. Never silently deliver truncated instructions.+ if (Buffer.byteLength(content, 'utf8') >= REMOTE_READ_LIMIT) {+ throw new Error(`Pi global context exceeds remote read limit: ${name}`);+ }+ return [{ name, content }];+ }+ try {+ // Follow user symlinks outside Pi home, then freeze the target's bytes.+ if (!(await fs.stat(source)).isFile()) continue;+ return [{ name, content: await fs.readFile(source, 'utf8') }];+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw error;+ }+ }+ return [];+}diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 82142869e1..778b0062ba 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -26,6 +26,7 @@ import path from 'node:path';import { promises as fs } from 'node:fs';import { createHash, createHmac, randomBytes } from 'node:crypto';import { piSupportedEfforts } from '@cindy/model-providers/pi-thinking-levels';+import { readPiGlobalContext } from './global-context.js';/*** 轮 40-w4-t5 CRITICAL:远端 agentHome 是 POSIX 路径($HOME/... 或展开后的@@ -2477,6 +2478,15 @@ export class PiAgent extends BaseAgent {// 远端再叠 models.json+settings.json hash:startSession 在 pi/ensure 之前就会写// 这两份快照。若只按 sessionId 分目录, 另一实例改路由或 retry 策略会先覆盖// 仍在跑的旧 Pi / 子代理热读快照。+ // Bot contexts remain profile-only. SSH tasks use the remote user's rules,+ // never the controlling desktop's personal instructions.+ const globalContextFiles = opts.botRuntimeProfile ? [] : await readPiGlobalContext(+ this.deps.resolvePiGlobalContextHome?.(opts.remoteHostId),+ fileOps,+ );+ const globalContextHash = globalContextFiles.length > 0+ ? createHash('sha256').update(JSON.stringify(globalContextFiles)).digest('hex').slice(0, 16)+ : '';let configHome = remote? joinRemotePosixPath(agentHome, 'run-tmp', stableSessionPathSegment(opts.sessionId)): joinRemotePosixPath(agentHome, 'run-tmp', randomBytes(8).toString('hex'));@@ -2518,7 +2528,7 @@ export class PiAgent extends BaseAgent {configHome = joinRemotePosixPath(agentHome,'run-tmp',- `${stableSessionPathSegment(opts.sessionId)}-${preview.modelsJsonHash.slice(0, 16)}`,+ `${stableSessionPathSegment(opts.sessionId)}-${preview.modelsJsonHash.slice(0, 16)}${globalContextHash ? `-${globalContextHash}` : ''}`,);}const { gatewayImageInputByModel, gatewayApiByModel, modelsJsonHash } = await this.writeModelsJson(@@ -4388,6 +4398,9 @@ export class PiAgent extends BaseAgent {};let durableSpawnEnv: NodeJS.ProcessEnv = {};try {+ for (const file of globalContextFiles) {+ await writeFile(joinRemotePosixPath(configHome, file.name), file.content);+ }// 远端不 stage 本地 rg(本机二进制远端无意义)—— 远端走 PATH 上的 rg(远端 POSIX// 系统常见),与 CC/Codex 远端一致(不注入受管工具路径)。const managedRipgrepPath = remote