Repository navigation
refactor(core): run loop turns on an independent state machine - #5236
Conversation
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4951ed4080
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| for (const message of continuing.appended) this.commit(message); | ||
| }); | ||
| if (!this.accepts(step)) return; | ||
| this.finalizeStep(proc, step); |
There was a problem hiding this comment.
Recheck notifications before finalizing continuation
When notify() or a detached-task completion queues a notification after ownerContinuing() checks mailbox.hasNotify but before this async continuation resumes, the actor processes that command first and this unconditional finalization preserves the continue outcome. The turn then starts another LLM step—and may execute additional tools—instead of yielding to the queued notification as documented. The parent implementation closed this race by rechecking mailbox.hasNotify in finalizeStep; restore an equivalent check at the finalization boundary.
AGENTS.md reference: AGENTS.md:L112-L115
Useful? React with 👍 / 👎.
| this.state, | ||
| step.scope.signal, | ||
| )); | ||
| if (!this.accepts(step) || this.finishSteeredStep(proc, step)) return; |
There was a problem hiding this comment.
Preserve drained reminders when interrupting the step
If abort() or sendNow() is processed after ownerRequesting() drains reminders into requesting.appended but before this suspended process resumes, this early return discards that transient buffer. The turn-ending path can only restore entries in uncommitted, so those reminders disappear from both history and the mailbox; the parent implementation committed reminders before entering the asynchronous request boundary. Move the returned entries into uncommitted before honoring the abort or steer so cancellation cannot silently lose queued reminders.
AGENTS.md reference: AGENTS.md:L114-L115
Useful? React with 👍 / 👎.
7Sageer
left a comment
There was a problem hiding this comment.
我用最小 Turn 用例稳定复现了一个取消窗口中的提醒丢失;continuation 的通知判定也需要在最终提交点再核对一次。
| this.state, | ||
| step.scope.signal, | ||
| )); | ||
| if (!this.accepts(step) || this.finishSteeredStep(proc, step)) return; |
There was a problem hiding this comment.
[P1] ownerRequesting() 已把 mailbox 中的 reminder 移入 requesting.appended,此时尚未写入 durable history。若 abort() 或 sendNow() 在 Promise 恢复前到达,这个 early return 会让 finishTurn() 把 reminder 转入 uncommitted;而 ownerEnding() 在 at === 'requesting' 又只恢复 reminder 到 mailbox,之后会再次 drain 并 append,导致它们永久留在 mailbox,后续 prompt 也不会消费。最小用例:requesting hook append 一条 reminder 后同步 turn.abort(),最终没有任何 message.appended(source='remind')。请在该边界保留已 drain 的消息,确保它们最终落账,并补回归。
| for (const message of continuing.appended) this.commit(message); | ||
| }); | ||
| if (!this.accepts(step)) return; | ||
| this.finalizeStep(proc, step); |
There was a problem hiding this comment.
[P1] ownerContinuing() 的 mailbox.hasNotify 检查发生在异步恢复之前。step.ended listener 或后台任务可在这之后、调用这里之前加入 notify;此函数随后仍按 continue 收尾,下一 step 会先做一次模型请求,用户/任务通知要等更晚才被消费。旧实现会在 finalizeStep 将带 notify 的 continue 改写为 done。请把同样的检查放回最终 continuation 边界,并覆盖在 step.ended listener 中 notify 的时序。
|
补充基线对照: |
7f1e472 to
f3e6531
Compare
* refactor(core): run loop turns on an independent state machine - add an actor runtime for loop and turn execution - unify turn hooks and asynchronous lifecycle settlement - simplify loop contracts and cover turn lifecycle behavior * fix(core): park recorded notifications until intake * fix(core): settle forced aborts past stuck hooks and tools * docs(core): document loop emitted events and public API * fix(agent-core-v2): skip onDidFinishStep hooks for aborted steps
The merge-base changed after approval.
4951ed4 to
02b2ebe
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 02b2ebe170
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } | ||
|
|
||
| // 6. Settle a late request through the abort-only path without normal batch hooks. | ||
| const outcome = await this.executeRequest(proc, step, requester, profile); |
There was a problem hiding this comment.
Recheck detached completions before launching the request
When a detached-tool completion is delivered after ownerRequesting() checks completionHandoff but before this suspended turn resumes, execution reaches this request launch with the notification already queued. Detached completions do not set steerRequested, so the new LLM step—and potentially its tools—runs before the completion is consumed; the previous deferForRequest path rechecked completionHandoff immediately before starting the request. Restore an equivalent check at this boundary.
AGENTS.md reference: AGENTS.md:L111-L115
Useful? React with 👍 / 👎.
| * Queues messages in the remind inbox and emits `prompt.reminded` for each. | ||
| * Does not release the intake hold and never wakes the scheduler: queued | ||
| * reminders are merged into the initial pending of the next turn that is | ||
| * not `promptOnly`, or flushed straight into history by | ||
| * {@link Loop.flushReminders}. |
There was a problem hiding this comment.
Document that idle reminders flush immediately
This new API contract says remind() never wakes the scheduler and leaves messages queued until another turn or flushReminders(), but an idle loop with held === false does the opposite: remind() enters actor.act(), canSchedule() treats hasReminders as schedulable work, and schedule() immediately flushes them into history. This state occurs normally after a completed turn, so callers following the documentation cannot rely on reminders remaining parked; update the contract to describe the conditional immediate flush.
AGENTS.md reference: AGENTS.md:L9-L10
Useful? React with 👍 / 👎.
…st syncs as not-applicable MoonshotAI#5019 is the fork's check:no-comments gate, already in check:lint; MoonshotAI#5236 is the core loop state machine now exported from @moonshot-ai/core/loop and covered by test/agent/loop/core. The two web-dist sync rows replace hashed upstream bundles the fork builds itself.
Part 3/7 of the loop stack onto
main. Identical diff to #5211, previously reviewed and merged into the loop integration branch. Stacked on #5235; the shown diff contains only this PR's own changes.Requirement or Bug
LoopActor同时承担 MailBox、history 投影、Turn/Step 推进、LLM 请求、前台工具、abort 与恢复调度,Turn 生命周期散落在大量内部消息处理中,createTurn原本只是数据工厂。本 PR 将 405 的全部工作整合为单个提交:独立 Turn 状态机与通用 Actor 运行时,并统一内部契约、hook、abort 和关闭路径。本 PR 替代此前的 stacked PR #5195、#5208、#5209、#5210。
Bug Reproduction Steps
N/A
Root Cause
Turn 缺少独立且封闭的状态迁移边界,Loop 同时负责调度与执行细节,导致 hook 返回形态、abort 来源阶段和终局处理都依赖多条 continuation 路径,难以保证一致的生命周期语义。
Code Changes
packages/core/src/actor:同步原子act、受控串行协程(spawn/step/checkpoint/waitUntil)、非重入事件派发、取消、idle 和幂等 close;Loop 与 Turn 各持独立实例。createTurn:Turn 独占自身 phase/state、前台请求、工具批次、Step/Turn ending 和 done;Loop 保留 MailBox、history、active 调度、requester template 和工具实例管理。step.starting返回消息重写路径。await兼容。executeStep使用单函数线性async/await和 guard clause,所有等待统一经过proc.step;finishTurn启动唯一 close process,异步owner.ending后才发一次turn.ended并 resolve 一次done。step.ended重入 abort 的 outcome,避免局部 done 覆盖;append buffer 在 hook settle 后失效,晚到结果不能重新进入 Turn。jscpd:ignore-start/end,并在.commentignore中豁免create-turn.ts与loop-actor.ts;另应用户要求为 loop 模块公共面(create-loop.ts、contract/emitted.ts)补充 API 文档并加入豁免;这些注释不改变执行逻辑。recordNotification落账后置held驻留,由后续submit/notify/start经既有releaseIntake()释放,恢复「通知不越过 parked 普通消息」的入队顺序。forceCloseRequested与closeStep()解除对未 settle 的step.stopping/owner.ending的等待;active 工具批次仅为未完成 call 合成 aborted 结果、封闭晚到响应,保留真实与 detached 结果。turnProjection.stepStopping对 aborted draft 提前返回:aborted Step 不再触发onDidFinishStep链,goal/plan/toolDedupe/externalHooks 的 after-step 行为与 main 一致。Behavior Changes and Affected Users
owner.ending最后提交、turn.ended先于done、active 清理后再调度下一 Turnstep.stopping → step.ended → owner.ending → turn.ended → done,outcome 保持 aborted;onDidFinishStep链与 main 一样不为 aborted Step 执行step.starting通用消息重写Message[]并触发context.settledundefined/blockedreplaceHistory()/setContext()与 compaction/splice 通道保留验证:
tsc --noEmit通过。tool.test.ts无关 subagent 无 deadline 30s 超时(单独复验同现,路径不经本 PR 文件);coreLoopService21/21,相关 7 文件 393/393,test/agent/loop148/148。onDidFinishStepabort 用例修复前断言失败;recordNotification用例修复前观察到通知越过 normal。评审处理进展:
fullCompactionService通过ctx.signal.aborted识别并跳过,回归覆盖 aborted 不调用shouldCompact/begin、正常 Step 仍调用一次自动 compaction,完整 compaction 套件 118/118。onDidFinishStep链(goal/plan/toolDedupe/externalHooks)与 main 一样不为 aborted Step 执行;core 仍保留step.stopping事件面,signal.aborted守卫继续覆盖「abort 到达时 Step ending 已在飞」的竞态窗口。finishing/finished不再屏蔽 force;hook 不 settle 时 force 可放弃等待并正常发出 Step/Turn 终态事件与done;active 工具批次的未完成 call 合成 aborted 结果且晚到结果被封存。recordNotification提前调度——通知落账后held驻留,直到submit/notify/start释放 intake,保持 normal 优先于 prompt-only 通知。Checklist
/approve).