Skip to content

refactor(core): run loop turns on an independent state machine - #5236

Merged
7Sageer merged 1 commit into
mainfrom
loop-421-stack/03-turn-state-machine
Nov 23, 2026
Merged

7Sageer merged 1 commit into
mainfrom
loop-421-stack/03-turn-state-machine

Conversation

@sailist

@sailist sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

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 和工具实例管理。
  • 整理 Loop/Turn 内部契约:复用状态字段来源、分离公开状态与 live 状态、删除重复映射,以及未接入生产的 step.starting 返回消息重写路径。
  • 宿主 hook 在 Loop 初始化时注册一次;四个 TurnHooks 全部 Promise 化,blocking 顺序与短路保持,业务同步 hook 仍可由 await 兼容。
  • abort 统一进入 Actor 专用结算,保留来源阶段;晚到 tool calls 仅生成 aborted 结果,不进入正常 batch/continue;进行中的 Step ending 会被复用而不是重复执行。
  • 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。
  • 对 3 组有意保留的相似实现使用 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 普通消息」的入队顺序。
  • force abort 有界结算:粘滞 forceCloseRequested 与 closeStep() 解除对未 settle 的 step.stopping/owner.ending 的等待;active 工具批次仅为未完成 call 合成 aborted 结果、封闭晚到响应,保留真实与 detached 结果。
  • v2 适配层 turnProjection.stepStopping 对 aborted draft 提前返回:aborted Step 不再触发 onDidFinishStep 链,goal/plan/toolDedupe/externalHooks 的 after-step 行为与 main 一致。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
core 内部 TurnHooks 可链式注册、同步值或 Promise 均可,ending 必须同步 单次完整注册,四个组合 hook 均为 Promise,blocking 顺序不变 仅 LoopActor 与直接 Turn 测试等内部调用方 无可发布公共 API 变化;业务 hook 仍可同步返回
外部事件时序 部分 hook 与 Step/Turn 收尾同步相邻 允许外部事件在 Promise 恢复点和收尾之间交错 依赖同步相邻而非因果顺序的消费者 保持 owner.ending 最后提交、turn.ended 先于 done、active 清理后再调度下一 Turn
活跃 Step 的 abort 部分路径缺少完整 Step ending,晚到结果可能继续正常执行 step.stopping → step.ended → owner.ending → turn.ended → done,outcome 保持 aborted;onDidFinishStep 链与 main 一样不为 aborted Step 执行 Loop/v2 的取消、中断、hook 与 late callback 路径 这是明确的生命周期行为变化,无配置迁移
force/重复 abort 等待 grace 后结算 只缩短等待,不跳过工具结果或终态事件;hook 不 settle 时 force 可放弃等待完成结算 取消路径 N/A
step.starting 通用消息重写 可返回 Message[] 并触发 context.settled 通用返回路径删除,生产仅保留 undefined/blocked 全仓检索没有生产消费者 replaceHistory()/setContext() 与 compaction/splice 通道保留
通知消费时序 前一 Turn result 可能等待通知 Turn 的 append/onConsume 通知 Turn 可晚于前一 Turn result 启动,随后仍按序消费 用前一 Turn result 推断通知已消费的调用方 等待实际通知结果/onConsume,而不是偶然调度顺序
Loop/v2 消息与持久化形状 现有载荷和单条 user prompt 契约 不改变,hook parts 仍合入同一条 prompt 客户端、SDK、旧会话恢复与回放 N/A

验证:

  • 本地相关测试 3 个文件、93/93;Actor 独立套件 18/18,Statements / Branches / Functions / Lines 均 100%。
  • core 与 agent-core-v2 tsc --noEmit 通过。
  • Linux 远程环境相关回归 53 个文件、633/633。
  • 后续修复轮:core 全套 36 文件 384/384;agent-core-v2 全套 370 文件中 368 通过,3 个失败均为 tool.test.ts 无关 subagent 无 deadline 30s 超时(单独复验同现,路径不经本 PR 文件);coreLoopService 21/21,相关 7 文件 393/393,test/agent/loop 148/148。
  • 新增回归均为「修复前失败、修复后通过」:force-abort 两用例修复前 30s 超时;onDidFinishStep abort 用例修复前断言失败;recordNotification 用例修复前观察到通知越过 normal。
  • 仓库完整 lint 通过;目标文件 jscpd 扫描为 0 克隆;diff 检查通过。
  • 未运行全 monorepo;无 Windows 专属路径,未做 Windows 验证。

评审处理进展:

  • 已处理:aborted Step 的自动 compaction——fullCompactionService 通过 ctx.signal.aborted 识别并跳过,回归覆盖 aborted 不调用 shouldCompact/begin、正常 Step 仍调用一次自动 compaction,完整 compaction 套件 118/118。
  • 已处理:aborted Step 的 after-step 回调——v2 适配层对 aborted draft 提前返回,onDidFinishStep 链(goal/plan/toolDedupe/externalHooks)与 main 一样不为 aborted Step 执行;core 仍保留 step.stopping 事件面,signal.aborted 守卫继续覆盖「abort 到达时 Step ending 已在飞」的竞态窗口。
  • 已处理:force abort 结算——finishing/finished 不再屏蔽 force;hook 不 settle 时 force 可放弃等待并正常发出 Step/Turn 终态事件与 done;active 工具批次的未完成 call 合成 aborted 结果且晚到结果被封存。
  • 已处理:recordNotification 提前调度——通知落账后 held 驻留,直到 submit/notify/start 释放 intake,保持 normal 优先于 prompt-only 通知。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete; changes are limited to private internal packages, so no release changeset is required.
  • No user documentation update is required for these internal execution changes.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 02b2ebe

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T04:58:38.609031Z 02b2ebe New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@02b2ebe
npx https://pkg.pr.new/@moonshot-ai/kimi-code@02b2ebe

commit: 02b2ebe

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 7Sageer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我用最小 Turn 用例稳定复现了一个取消窗口中的提醒丢失;continuation 的通知判定也需要在最终提交点再核对一次。

this.state,
step.scope.signal,
));
if (!this.accepts(step) || this.finishSteeredStep(proc, step)) return;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] ownerContinuing() 的 mailbox.hasNotify 检查发生在异步恢复之前。step.ended listener 或后台任务可在这之后、调用这里之前加入 notify;此函数随后仍按 continue 收尾,下一 step 会先做一次模型请求,用户/任务通知要等更晚才被消费。旧实现会在 finalizeStep 将带 notify 的 continue 改写为 done。请把同样的检查放回最终 continuation 边界,并覆盖在 step.ended listener 中 notify 的时序。

@7Sageer

7Sageer commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

补充基线对照:tests/scenarios/conversation.test.ts 的 approval 场景在本 PR 与 #5235 上均出现两次 item.ended,属于既有问题,未作为本次 request changes 的依据。上面两项分别来自 Turn 最小复现和旧实现的提交顺序对照。

7Sageer
7Sageer previously approved these changes Nov 23, 2026
@sailist
sailist force-pushed the loop-421-stack/02-remove-reminder-reconciliation branch from 7f1e472 to f3e6531 Compare November 23, 2026 04:02
@sailist
sailist changed the base branch from loop-421-stack/02-remove-reminder-reconciliation to main November 23, 2026 04:38
@sailist
sailist dismissed 7Sageer’s stale review November 23, 2026 04:38

The base branch was changed.

7Sageer
7Sageer previously approved these changes Nov 23, 2026
* 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
@sailist
sailist dismissed 7Sageer’s stale review November 23, 2026 04:46

The merge-base changed after approval.

@sailist
sailist force-pushed the loop-421-stack/03-turn-state-machine branch from 4951ed4 to 02b2ebe Compare November 23, 2026 04:46

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +77 to +81
* 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}.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@7Sageer
7Sageer merged commit 1761319 into main Nov 23, 2026
24 checks passed
@7Sageer
7Sageer deleted the loop-421-stack/03-turn-state-machine branch November 23, 2026 05:23
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants