Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): keep retirement recovery scoped to its dedicated channel

Chris116b0d6b2da9
diff --git a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts
index 943bd60513..3de5f7eddc 100644
--- a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts
@@ -687,19 +687,11 @@ describe('接管陈旧锁', () => {
return result;
}) as typeof fsp.rename);
try {
- // Count is the real bound: three successful takeovers must stop the loop.
- // The wall-clock check only proves we did not wait out waitMs. Each
- // takeover publishes a reclaim gate (fsync + hard-link); Windows CI has
- // been observed at ~1.6s for three takeovers, so a 1s ceiling races the
- // runner rather than the lock policy. Warm the current-process
- // identity first — production does not charge that probe to waitMs.
- await __testing.getProcessIdentity(process.pid);
- const waitMs = 8_000;
const started = performance.now();
await expect(
- withCrossProcessLock(lock, { label: 'churn', waitMs }, async (s) => s),
+ withCrossProcessLock(lock, { label: 'churn', waitMs: 2_000 }, async (s) => s),
).resolves.toEqual({ held: false, reason: 'busy' });
- expect(performance.now() - started).toBeLessThan(4_000);
+ expect(performance.now() - started).toBeLessThan(1_000);
expect(takeovers).toBe(3);
} finally {
spy.mockRestore();
diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
index 8e4a63632b..d5a81dfbe1 100644
--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
@@ -2101,38 +2101,6 @@ describe('GoalController', () => {
expect((await h.storage.get('s1'))?.tokensUsed).toBe(777);
});
- it('does not let a post-terminal runtimeRecovery receipt replace Goal verdict text', async () => {
- await startGoal(h);
- const active = await h.storage.get('s1');
- let releaseGet!: (state: GoalState | null) => void;
- const blockedGet = new Promise<GoalState | null>((resolve) => {
- releaseGet = resolve;
- });
- vi.spyOn(h.storage, 'get').mockReturnValueOnce(blockedGet);
-
- h.session.emit({ type: 'tool_use', data: { name: 'Bash' } } as never);
- h.session.emit({
- type: 'text',
- data: { text: '```json\n{"goal_status":"complete","reason":"green"}\n```', isFinal: true },
- } as never);
- h.session.emit({ type: 'done', data: {}, turnOrigin: { kind: 'goal' } } as never);
- h.session.emit({
- type: 'text',
- source: 'pi',
- runtimeRecovery: true,
- data: {
- isFinal: true,
- text: '[Cindy Pi package runtime convergence receipt]\n```json\n{"runtimeConvergence":"partial","recoveryAction":"restart-cindy-to-refresh-packages"}\n```',
- },
- } as never);
-
- releaseGet(active);
- await vi.waitFor(() => expect(h.completions).toHaveLength(1));
- expect(await h.storage.get('s1')).toBeNull();
- expect(h.completions[0]?.summary.reason).toBe('green');
- expect(h.session.sends).toHaveLength(1);
- });
-
it('on complete: persists a completion record, clears the row, emits null, no continuation', async () => {
await startGoal(h);
h.session.emitGoalTurn({ toolUse: true, verdictJson: '```json\n{"goal_status":"complete","reason":"green"}\n```', tokens: 42 });
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index 11ecf78266..d275b8fc98 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -1765,9 +1765,6 @@ export class GoalController {
private onEvent(sessionId: string, event: AgentEvent): void {
if (this.disposed) return;
- // Host-only recovery notice after deferred Pi retirement. Independent of the
- // product turn: never treat it as Goal assistant text / verdict input.
- if (event.runtimeRecovery) return;
let turn = this.turns.get(sessionId);
if (!turn) {
turn = freshTurn();
diff --git a/apps/desktop/src/main/hook-control/turnObserver.ts b/apps/desktop/src/main/hook-control/turnObserver.ts
index 8c6c7287af..7acf01b796 100644
--- a/apps/desktop/src/main/hook-control/turnObserver.ts
+++ b/apps/desktop/src/main/hook-control/turnObserver.ts
@@ -201,7 +201,6 @@ export function observeHookTurn(
failTurn(new Error(`hook turn session ended without a terminal event (${status})`));
});
const off = session.onEvent((ev: AgentEvent) => {
- if (ev.runtimeRecovery) return;
if (ev.type === 'text') {
// 正文累积(isFinal 逐条契约 / 定稿段按消息切开 / fallbackTail 自成段 /
// uuid 缺失退 requestId)都在 presenter 的 finalized-segments 策略里。
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 8d219c5875..25f7ed9b1e 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -2054,7 +2054,6 @@ export function createTurnRunner(
function handleEventFor(localSessionId: string, userId: string) {
return (event: AgentEvent) => {
- if (event.runtimeRecovery) return; // Independent channel notice, never next-turn prose.
const state = sessionStates.get(localSessionId);
if (!state) return;
const turn = state.queue[0];
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 245ffc63f1..273f78ab2d 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -254,6 +254,8 @@ Pi CLI 管理入口、内核自更新与旧工具兼容的执行边界见
挂起的 abort 不得阻止已结算工作的待退役 runtime 关闭,迟到返回不得复活旧实例。
延迟退役的实际关闭若失败,应在该实例的监听器清理前补发 `partial` 与
`restart-cindy-to-refresh-packages` 恢复回执;不改判此前成功结果,不自动重放工作。
+ 恢复回执只走 Session 的 `onRuntimeRecovery`,不得进入产品 `onEvent` 正文流;
+ Desktop 与 IM 显式订阅,Goal/Learn/Orca 等消费者不逐个追加过滤。
IM 已在 done 退订时,恢复回执须走独立渠道通知,不能把 post-terminal text fan-out
当作已交付。通知保留准确实例和包退役发起 generation,渠道发送与送达确认分开;
不借通知重开已完成 turn。官方 Telegram 复用协商后的 msg.op;旧 hook、Slack/X
diff --git a/docs/research/pi-long-tool-lifecycle-3916.md b/docs/research/pi-long-tool-lifecycle-3916.md
index 6808e89717..ee37f2497f 100644
--- a/docs/research/pi-long-tool-lifecycle-3916.md
+++ b/docs/research/pi-long-tool-lifecycle-3916.md
@@ -1,12 +1,5 @@
# Pi 长工具生命周期:#3916 受控取证
-本报告保留独立 transport 工作(初始提交 `d8bd012f1`、PR #4182 及后续审查)的
-取证与验证范围。#4182 已合入主干;统一 Pi 生命周期 P0 PR #4186 同步保留其
-退出确认加固,组合验证以 #4186 正文为准。P0 早期提交修复过下文记录的
-`maker.shutdown.test.ts` 泛型 resolver 类型错误;同步 #4178 后采用主干的
-`Promise<void>` 夹具,当前该文件相对主干无差异,不把基线类型错误归因于 transport。
-下文的「本单」及独立验证结果指该 transport 工作,不代表组合 P0 PR 的全部改动。
-
## 结论与范围
已在代码级复现并修复一条确定的退出通知缺陷:**Pi 已退出,但工具后代继承
@@ -44,11 +37,6 @@ fixture 不调用模型、不运行真实打包,不读取个人凭证;生成
失败路径:fixture 确认 prompt、发 `agent_start` 和 `tool_execution_start`,随后
启动继承输出管道的轻量后代并 `exit(23)`。测试直接检查 Pi PID 已不存在、后代 PID 仍存活。
-组合 PR 首轮 Windows CI 在后代存活断言处出现 `ESRCH`。fixture 因此显式设置
-`detached: true`,并等后代通过 IPC 报告就绪后才让 Pi 退出,仍保留 stdout/stderr
-继承、后代存活和无新 prompt 的断言。[Node 文档](https://nodejs.org/api/child_process.html#optionsdetached)
-说明 Windows 下 detached 可让子进程在父进程退出后继续运行;这项调整仅建立受控复现
-的前提,不改变生产进程配置,也不证明原 Windows 打包现场的根因。
修复前,最初 4 个用例中 3 个对照通过,继承管道用例在 2 秒内始终没有 terminal error,
断言失败。修复后同一路径约 0.3 秒收到包含退出码 23 的 terminal error,Session 自动
@@ -95,14 +83,10 @@ lizi-mcps、maker-core related 与 orca-workflow 的无模型单测均通过。
单 worker 复查 27/27 通过,第二轮完整门禁也未再出现。未放宽断言或改插件基座,
该偶发失败的根因尚未确定。
-独立 transport 取证时,额外 `tsc --noEmit` 发现 `maker.shutdown.test.ts:91` 的
-`TS2322`:泛型 resolve 的可选参数签名与 Promise resolver 不匹配。以 CompilerHost
-从当时 Git HEAD 读取所有已改文件、排除新增 fixture 后,原基线复现同一个错误;
-独立提交 `d8bd012f1` 未修改该文件。组合 P0 PR #4186 早期修复过 resolver 签名,
-后续同步 #4178 时采用主干的 `Promise<void>` 夹具,当前该文件不再属于 PR diff。早期修复
-通过 `pnpm --filter @cindy/maker-core run build`(`tsc --noEmit`)。该包没有
-`typecheck` script,规定的 `run --if-present typecheck` 跳过;类型通过的证据来自
-上述实际执行的 build,不来自跳过的命令。
+额外 `tsc --noEmit` 发现 `maker.shutdown.test.ts:91` 的 `TS2322`:泛型 resolve 的
+可选参数签名与 Promise resolver 不匹配。以 CompilerHost 从 Git HEAD 读取所有已改文件、
+排除新增 fixture 后,原基线复现同一个错误;本单没有改该文件。包当前没有 `typecheck`
+script,规定的 `run --if-present typecheck` 跳过,不把跳过称作类型检查通过。
缓存/模型指标:未修改 system 前缀、工具 schema、模型路由或 usage 计算。
正常 fixture 的 10 input / 3 output 在 done 中原样保留;热路径只增加一个 closed
@@ -143,7 +127,3 @@ Windows 后续运行 b1c442b4e 已通过后代存活等行为断言,但 afterE
再删除目录,文件系统残留锁采用有界异步重试,避免阻塞事件循环;不吞掉清理失败。
同轮 shard 1 的 Windows mutex 探测与飞书 Unicode 校验超时未改动相关源码,
前一提交的同 shard 曾通过,尚无基线复现证据;由新 CI 复查,不认定已确定为偶发。
-
-组合 P0 同步 #4182 后,保留自己已有的后代 IPC 就绪握手及无新 prompt 断言,
-并采用主干更严格的 ESRCH 退出确认与有界异步目录清理;后代 detached 的测试配置
-不影响生产 Pi spawn 配置。关闭失败的恢复回执由 P0 的 Session 生命周期处理。
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts
index 45b87528df..1576754724 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-long-tool-lifecycle.test.ts
@@ -40,14 +40,14 @@ vi.mock('../transport.js', async (importOriginal) => {
return process.stdout.end();
}
if (cmd.type === 'fixture_exit_with_descendant') {
- const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000); process.send("ready")'], {
- // Windows needs detached to establish this fixture's orphan
- // precondition. Keep inheriting both RPC pipes deliberately.
- detached: true, windowsHide: true,
- stdio: ['ignore', process.stdout, process.stderr, 'ipc'], env: process.env
+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], {
+ // libuv's Windows job kills non-detached children on parent exit.
+ // This fixture specifically needs a surviving pipe owner; production
+ // spawn options remain unchanged, and afterEach owns its cleanup.
+ detached: process.platform === 'win32',
+ stdio: ['ignore', process.stdout, process.stderr], env: process.env
});
- child.once('message', () => {
- child.disconnect();
+ child.once('spawn', () => {
output({ type: 'fixture_descendant', pid: child.pid });
// Drain the fixture metadata before exiting, leaving both pipes
// open in the descendant exactly as a shell/build child can.
@@ -177,7 +177,6 @@ describe('Pi long tool lifecycle through real stdio RPC', () => {
it('reports executor exit while a build descendant still holds the RPC pipes open', async () => {
const { events, transport } = await start();
- const write = vi.spyOn(transport, 'writeLine');
await transport.writeLine(JSON.stringify({ type: 'fixture_exit_with_descendant' }));
await vi.waitFor(() => expect(descendantPid).toBeTypeOf('number'));
await vi.waitFor(() => expect(() => process.kill(transport.pid!, 0)).toThrow());
@@ -189,7 +188,6 @@ describe('Pi long tool lifecycle through real stdio RPC', () => {
expect(() => process.kill(descendantPid!, 0)).not.toThrow();
expect(events.some(event => event.type === 'tool_result_full')).toBe(false);
await vi.waitFor(() => expect(session!.getStatus()).toBe('closed'));
- expect(write.mock.calls.some(([line]) => JSON.parse(line).type === 'prompt')).toBe(false);
});
it('reports ordinary RPC process exit during a tool', async () => {
diff --git a/packages/maker-core/src/session.close.test.ts b/packages/maker-core/src/session.close.test.ts
index 1d8e5401bf..933634f489 100644
--- a/packages/maker-core/src/session.close.test.ts
+++ b/packages/maker-core/src/session.close.test.ts
@@ -75,14 +75,18 @@ describe('Session close lifecycle', () => {
session.onRuntimeRecovery((event) => recovered.push(event));
const close = vi.mocked(handle.close);
close.mockRejectedValueOnce(new Error('process exit unconfirmed'));
- const recovery: AgentEvent = { type: 'text', source: 'pi', data: { text: 'partial: restart-cindy-to-refresh-packages' } };
+ const recovery: AgentEvent = { type: 'text', source: 'pi', data: {
+ text: 'partial: restart-cindy-to-refresh-packages', isFinal: true,
+ } };
await session.send('work');
await session.closeAfterCurrentTurn({ failureEvent: () => recovery });
idle();
+ queue.push({ type: 'text', source: 'pi', data: { text: 'saved result', isFinal: true } });
queue.push({ type: 'done', source: 'pi', data: { status: 'completed', result: 'saved result' } });
await vi.waitFor(() => expect(session.getStatus()).toBe('error'));
- expect(seen.map(event => event.type)).toEqual(['done']);
- expect(seen[0]?.data).toMatchObject({ status: 'completed', result: 'saved result' });
+ expect(seen.map(event => event.type)).toEqual(['text', 'done']);
+ expect(seen[0]?.data).toEqual({ text: 'saved result', isFinal: true });
+ expect(seen[1]?.data).toMatchObject({ status: 'completed', result: 'saved result' });
expect(recovered).toEqual([{ ...recovery, runtimeRecovery: true,
sessionInstanceId: session.instanceId, sessionTurnGeneration: session.getTurnGeneration() }]);
expect(handle.send).toHaveBeenCalledOnce();