Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): recover corrupt run status from verified terminal receipts
Chris4acf3e48cad9
diff --git a/docs/research/pi-subagent-delegation.md b/docs/research/pi-subagent-delegation.mdindex a7f64f4024..442e1ca06d 100644--- a/docs/research/pi-subagent-delegation.md+++ b/docs/research/pi-subagent-delegation.md@@ -14,6 +14,16 @@子代理详情的可选 `resultReady` 透传到本机与设备互联控制卡:显式 `false` 时中间输出不阻止插话,`true` 时改为排队;旧宿主或 runner 缺少该字段时,界面保留按输出判断的回退。+### 损坏状态的账号边界恢复++`status.json` 仍是展示和控制的主记录。账号边界读取不到状态时,可以使用同目录的+完整终态 `result.json` 作为独立结束回执:必须匹配 `config.json` 的 runId、taskId、+parentSessionId、runDir 和全部 child/session/agent 身份,并确认所有子任务均为终态。+该回执由 runner 在终止子进程、解除定时器后写出;续跑使用新 UUID,不复用旧 generation。+可读的运行态不被结果附件覆盖。缺少、损坏、超限、链接文件、身份不符或不完整的回执仍+保持未知并阻止账号交接,不能仅凭宿主退出、文件陈旧或 stop 无回执放行。恢复只读取证据,+不修改或删除原状态、结果和对话文件,也不宣称验证了 OS 进程退出。+## 对标与取舍对照社区 [pi-subagents 工具契约](https://github.com/nicobailon/pi-subagents/blob/main/docs/tool-reference.md)、diff --git a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.tsindex f7758f6ebd..586091e612 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindySubagentRunner.test.ts@@ -470,7 +470,7 @@ process.stdin.on('end', () => {version: 1,runId,taskId: 'tool-fixture',- parentSessionId: 'parent-fixture',+ parentSessionId: path.basename(root),...(options.runtimeOwnerId ? { runtimeOwnerId: options.runtimeOwnerId } : {}),...(options.guestIsolation ? { guestIsolation: true } : {}),runDir,@@ -557,8 +557,8 @@ afterEach(async () => {describe('Cindy durable PI Subagent runner', () => {/**- * result.json is an attachment, not the verdict. Nothing in the product reads- * it back; status.json is what the Host converges on. So a failure to write it+ * result.json is a best-effort attachment; status.json is the primary record.+ * Account-boundary recovery may read a valid receipt, but a failure to write it* must not be able to change what the run reports — the old code let the throw* from the success path land in the failure handler, which rewrote the state* to `failed` and republished, and a throw from the failure handler escaped it@@ -600,6 +600,20 @@ describe('Cindy durable PI Subagent runner', () => {});});+ // #6694 integration: use the actual runner's persisted receipt, after its+ // child and runner have exited. A hand-built JSON fixture alone cannot prove+ // that the independent artifact has the identity required by recovery.+ it('recovers account teardown from a real terminal receipt after status corruption', async () => {+ const fixture = await makeFixture();+ await waitForClose(fixture.child, fixture.stderr);+ const files = ['result.json', 'transcript.jsonl', 'config.json'];+ const before = await Promise.all(files.map(file => readFile(path.join(fixture.runDir, file))));+ await writeFile(path.join(fixture.runDir, 'status.json'), Buffer.alloc(72_506));+ await expect(stopForAccountBoundary(fixture.root, { timeoutMs: 0 })).resolves.toBe(true);+ expect(await Promise.all(files.map(file => readFile(path.join(fixture.runDir, file)))))+ .toEqual(before);+ });+// A profile prompt long enough to blow the platform spawn command line budget// must fail closed as a readable task error. Without the guard the spawn// itself throws (ENAMETOOLONG / EINVAL on Windows) and the run ends with andiff --git a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.tsindex 7cbf676ff5..dced2e3b96 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-subagent-runs.test.ts@@ -1420,6 +1420,100 @@ describe('PI durable subagent run store', () => {.resolves.toBe(false);});+ // #6694 unit boundary regression: a real runner writes this separate+ // terminal artifact before status. Existing unreadable-status cases have+ // no receipt and must keep refusing the account handover.+ async function terminalReceiptHome(write: (dir: string) => Promise<void>) {+ const agentHome = await homeWithUnreadableRun(write);+ const root = piSubagentRunRoot(agentHome, 'session-1');+ const dir = path.join(root, runId);+ const task = { childId: 'child-1', sessionId: 'native-1', agent: 'scout' };+ const config = {+ version: 1, runId, runDir: dir, taskId: 'tool-1', parentSessionId: 'session-1',+ cwd: dir, binary: 'pi', tasks: [task],+ };+ const result = {+ version: 1, runId, taskId: 'tool-1', state: 'completed', completedAt: 100,+ tasks: [{ ...task, status: 'completed', output: 'original result' }],+ };+ await writeFile(path.join(dir, 'config.json'), JSON.stringify(config));+ await writeFile(path.join(dir, 'result.json'), JSON.stringify(result));+ await writeFile(path.join(dir, 'transcript.jsonl'), 'original transcript\n');+ return { agentHome, root, dir, config, result };+ }++ it.each([+ ...cases,+ ['contains zero bytes', async (dir: string) => writeFile(path.join(dir, 'status.json'), Buffer.alloc(72_506))],+ ] satisfies typeof cases)('accepts a matching terminal receipt when status %s, without changing history', async (_label, write) => {+ const { agentHome, root, dir } = await terminalReceiptHome(write);+ const files = ['config.json', 'status.json', 'result.json', 'transcript.jsonl'];+ const before = await Promise.all(files.map(file => readFile(path.join(dir, file)).catch(() => null)));+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0, { hostPid: process.pid, killUnresponsiveRunners: true }))+ .resolves.toBe(true);+ await expect(stopPiSubagentRunsForAccountBoundary(root, { timeoutMs: 0 }))+ .resolves.toBe(true);+ expect(await Promise.all(files.map(file => readFile(path.join(dir, file)).catch(() => null))))+ .toEqual(before);+ expect(existsSync(path.join(dir, 'controls'))).toBe(false);+ });++ it.each(['failed', 'stopped'])('also recognizes a complete %s receipt', async state => {+ const { agentHome, dir, result } = await terminalReceiptHome(async () => {});+ result.state = state;+ result.tasks[0]!.status = state;+ await writeFile(path.join(dir, 'result.json'), JSON.stringify(result));+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0)).resolves.toBe(true);+ });++ it.each([+ ['another generation', { runId: '123e4567-e89b-42d3-a456-426614174099' }],+ ['another task', { taskId: 'other-tool' }],+ ['unfinished run', { state: 'running' }],+ ['missing child', { tasks: [] }],+ ['unfinished child', { tasks: [{ childId: 'child-1', sessionId: 'native-1', agent: 'scout', status: 'running' }] }],+ ['different child identity', { tasks: [{ childId: 'child-1', sessionId: 'other-native', agent: 'scout', status: 'completed' }] }],+ ])('refuses a receipt for %s', async (_label, patch) => {+ const { agentHome, dir, result } = await terminalReceiptHome(async () => {});+ await writeFile(path.join(dir, 'result.json'), JSON.stringify({ ...result, ...patch }));+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0, { killUnresponsiveRunners: true }))+ .resolves.toBe(false);+ });++ it('refuses a receipt detached from its original run directory', async () => {+ const { agentHome, dir, config } = await terminalReceiptHome(async () => {});+ await writeFile(path.join(dir, 'config.json'), JSON.stringify({ ...config, runDir: path.dirname(dir) }));+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0)).resolves.toBe(false);+ });++ it.skipIf(process.platform === 'win32')('does not follow a linked terminal result', async () => {+ const { agentHome, dir } = await terminalReceiptHome(async () => {});+ const resultFile = path.join(dir, 'result.json');+ const outside = path.join(agentHome, 'outside-result.json');+ await writeFile(outside, await readFile(resultFile));+ await rm(resultFile);+ await symlink(outside, resultFile);+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0)).resolves.toBe(false);+ });++ it('does not replace a readable live status with the result artifact', async () => {+ const { agentHome, root } = await terminalReceiptHome(async () => {});+ await writeStatus(root, status(runId, { updatedAt: Date.now() }));+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0)).resolves.toBe(false);+ });++ it.each(cases)('keeps refusing when the result artifact %s', async (_label, write) => {+ const { agentHome, dir } = await terminalReceiptHome(async () => {});+ await rm(path.join(dir, 'result.json'));+ // The malformed artifacts share the same bounded reader. Move the+ // fixture's malformed status bytes to the independent result file.+ await write(dir);+ const bytes = await readFile(path.join(dir, 'status.json')).catch(() => null);+ if (bytes) await writeFile(path.join(dir, 'result.json'), bytes);+ await expect(stopAllPiSubagentRunsForExit(agentHome, 0, { killUnresponsiveRunners: true }))+ .resolves.toBe(false);+ });+it('still reports success once every run is readable and reclaimed', async () => {usePlatform('linux');// Verifiable once, then reaped by the kill: a confirmed reclaim.diff --git a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.tsindex c737457530..a7525f32ad 100644--- a/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-subagent-runner-source.ts@@ -411,8 +411,8 @@ function main() {// The terminal status is the opposite case and must not reuse the path above:// scheduleStatus() refuses to re-arm once terminal, so a swallowed failure- // there is a permanent loss, and status.json is the only record the product- // reads back (nothing consumes result.json today) — the run would keep reading+ // there is a permanent loss: product views still read status.json (only+ // account-boundary recovery can use result.json), so the run keeps reading// as running until it aged into a stale diagnostic. Retry on a wider budget// instead; the runner is on its way out, so blocking here costs nothing.function flushTerminalStatus() {@@ -434,9 +434,10 @@ function main() {}}- // result.json is a best-effort *attachment*, not the terminal record: nothing- // in the product reads it back, while status.json is what the Host converges- // on. So its write must never decide the run's outcome — letting it throw once+ // result.json is a best-effort attachment; status.json remains the primary+ // record. Account-boundary recovery can validate this independent terminal+ // receipt if status is unreadable. Its write must never decide the outcome:+ // letting it throw once// turned a completed run into a published failure (the throw from the success// path landed in the failure handler, which rewrote state and republished),// and letting it throw from the failure path skipped the terminal statusdiff --git a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts b/packages/maker-core/src/agents/pi/pi-subagent-runs.tsindex 758e5265e2..0cbe1f0e98 100644--- a/packages/maker-core/src/agents/pi/pi-subagent-runs.ts+++ b/packages/maker-core/src/agents/pi/pi-subagent-runs.ts@@ -3005,8 +3005,8 @@ const DEFAULT_KILL_BUDGET_MS = 8_000;* Runs under `root` that this sweep still owns, as one universe.** `status` is undefined when status.json is missing, corrupt, oversized or- * unreadable. Those runs stay in the set deliberately, and every pass of the- * sweep derives its work from *this* function: when the stop pass and the kill+ * unreadable. Without a matching independent terminal receipt those runs stay+ * in the set deliberately. Every sweep pass derives work from *this* function: when the stop pass and the kill* pass disagree about which runs exist, a record we cannot read drops out of the* escalation and the boundary reports itself clean.*@@ -3038,6 +3038,7 @@ async function sweepableRunsUnderRoot(for (const runId of runIds) {const status = statuses.get(runId);if ((status && isPiSubagentTerminal(status.state)) || staleRunIds.has(runId)) continue;+ if (!status && await hasTerminalResultReceipt(root, runId)) continue;if (scope.runtimeOwnerId !== undefined&& status?.runtimeOwnerId !== undefined@@ -3051,6 +3052,50 @@ async function sweepableRunsUnderRoot(return sweepable;}+/**+ * The runner publishes result.json after killing/disarming its children, just+ * before the terminal status. That independent receipt survives a damaged+ * status file (#6694). Resume always creates a new UUID, never reuses this run.+ * Only a complete receipt for this exact config can retire an unreadable run;+ * age, a dead host, and an unanswered stop request are not completion evidence.+ * Keep both files untouched, including the corrupt status, for diagnosis.+ */+async function hasTerminalResultReceipt(root: string, runId: string): Promise<boolean> {+ try {+ const runDir = path.join(root, runId);+ const [config, value] = await Promise.all([+ readSmallJson(path.join(runDir, 'config.json')),+ readSmallJson(path.join(runDir, 'result.json')),+ ]);+ if (!isResumeConfig(config, runId)+ || config.parentSessionId !== path.basename(root)+ || typeof config.runDir !== 'string'+ || path.resolve(config.runDir) !== path.resolve(runDir)+ || !value || typeof value !== 'object' || Array.isArray(value)) return false;+ const result = value as Record<string, unknown>;+ if (result.version !== 1 || result.runId !== runId || result.taskId !== config.taskId+ || !isState(result.state) || !isPiSubagentTerminal(result.state)+ || !finiteNonNegative(result.completedAt)+ || !Array.isArray(result.tasks) || result.tasks.length !== config.tasks.length) return false;+ const seen = new Set<string>();+ return result.tasks.every((value: unknown) => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const task = value as Record<string, unknown>;+ if (typeof task.childId !== 'string' || !task.childId || seen.has(task.childId)) return false;+ seen.add(task.childId);+ const expected = config.tasks.find((candidate) => candidate?.childId === task.childId);+ return expected !== undefined+ && typeof expected.sessionId === 'string' && expected.sessionId.length > 0+ && typeof expected.agent === 'string' && expected.agent.length > 0+ && task.sessionId === expected.sessionId && task.agent === expected.agent+ && isState(task.status) && isPiSubagentTerminal(task.status);+ });+ } catch {+ // Bounded reads reject missing, corrupt, oversized and linked artifacts.+ return false;+ }+}+/** Resolve false if `work` has not settled within `ms`, without leaking a timer. */async function raceWithDeadline(work: Promise<boolean>, ms: number): Promise<boolean> {let timer: NodeJS.Timeout | undefined;@@ -3066,8 +3111,8 @@ async function raceWithDeadline(work: Promise<boolean>, ms: number): Promise<boo/*** Request stop for every non-terminal run under `roots` and wait until they are- * all terminal (or the deadline passes). An unreadable status stays in scope so- * a corrupt record can never keep a child alive past its boundary.+ * all terminal (or the deadline passes). An unreadable status without a validated+ * terminal result receipt stays in scope so a corrupt record can never keep a child alive past its boundary.*/async function stopPiSubagentRunsUnderRoots(roots: readonly string[],