Skip to content

fix(agent-core-v2): preserve legacy steer pairing after undo - #5599

Merged
sailist merged 6 commits into
mainfrom
bug-474-11-26-legacy-steer-undo-fork
Nov 27, 2026
Merged

sailist merged 6 commits into
mainfrom
bug-474-11-26-legacy-steer-undo-fork

Conversation

@sailist

@sailist sailist commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

旧版本写出的会话在同时包含撤回分支和 legacy turn.steer 时,按轮 fork 会把已撤回的提问重新带入副本,并把后续追加内容归到错误的回合。这个 PR 让这类历史在 fork、replay 和 JSON 往返后的冷恢复路径模拟中都保留有效分支的输入及正确回合归属,同时保持源会话原始 wire 不变。

No external issue was provided; the reproduction and root cause are included below.

Bug Reproduction Steps

  1. 构造提问 A、B,撤回 B,再提问 C,并依次追加 C1、C2;旧 steer 的记录顺序为正文在前、steer 在后,且缺少关联 ID。
  2. 分别 fork 到 C、C1、C2,并对副本做 JSON 序列化往返,再走归一化、恢复与 replay。
  3. 修复前,副本会多出 B,C1 被归到 B 的回合,C2 又被归到 C1 的回合;源会话恢复后的模型上下文则不包含 B。重复文案、部分或完全缺 ID 时也会出现同类错配。
  4. 修复后,三个截点及 JSON 往返后的冷恢复路径模拟都只保留有效输入,回合依次为 A=0、C=2、C1=3、C2=4。

Root Cause

restorableChain 为恢复回合时钟重新纳入撤回分支的 turn.prompt,但这些 prompt 的有效正文已不在 active chain 中。旧 steer 归一化为 turn.ended + turn.prompt 后,匹配器仍按记录位置和内容重新猜测输入与正文的对应关系:普通 prompt 只能匹配其前方正文,缺 ID 时还会退到 relaxed match,于是孤立 prompt 抢走后续 steer 的正文,并被 fork 当成有效输入保留。

This is a fundamental fix at the shared normalization and matching boundary, not a workaround.

Code Changes

核心思路是先使用原始有效分支确定 steer 与正文的关联,再生成可稳定重放的回合顺序;撤回 prompt 只保留时钟用途,不再参与正文匹配。

active records ───────────────> pre-match legacy steer to its append
                                       │
withdrawn prompts ─> clock-only ───────┤
                                       v
                         normalize adjacent append-first records
                                       │
                                       v
                         shared turn-input matching
                          │          │          │
                        fork       replay    cold restore
  • wire/turnInput.ts:集中维护共享的输入匹配器及 clock-only 标记,replayBuilder 继续导出原函数和类型,避免恢复与 fork 各自维护平行匹配逻辑。
  • wire/human.ts:在转换旧 steer 前取得 steerIndex → appendIndex 关联;只在 steer 与前方相邻 user append 预匹配成功的 append-first 形态中,把生成的回合记录放到对应正文之前。其他记录顺序、ID 和 loop event 归属不变。
  • wire/tree/fork.ts:重新纳入的撤回 prompt 使用进程内 Symbol 标记;它仍推进 nextTurnId,但不进入正文候选,也不会因误配被写入 fork。
  • replayBuilder/fold.ts:复用同一匹配器,保留原公开导出及 append object identity,覆盖完整和窗口化 replay。

阅读顺序建议:先看 wire/turnInput.ts 的共享约束,再看 wire/human.ts 的预匹配与归一化,随后看 wire/tree/fork.ts 的 clock-only 来源;replayBuilder/fold.ts 主要是接线与导出。测试集中在 forkTurnSlice.test.ts 和 fold.test.ts。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
撤回分支 prompt 的用途 可能被后续正文误配并写入 fork 仅推进回合时钟,不参与正文匹配 使用旧版本会话,在 Desktop/Web、VS Code 中撤回回合后按轮 fork 的用户,以及通过 KAP :fork 或公共 SDK forkSession 指定 turnIndex 的调用方 无;changeset 明确撤回 prompt 不再错误重现
相邻 append-first 的 legacy steer 转换后可能从孤立或相邻 prompt 重新猜配,fork 截点和 replay 回合错误 使用原始关联生成 prompt → append 顺序,三个截点与 JSON 往返后的恢复路径一致 经 Desktop/Web、CLI、VS Code、KAP :fork 或公共 SDK forkSession 使用旧 steer 历史的调用方 无;源 wire 不改写
现代 normal / notify 历史 prompt 只能匹配前方正文 不变;无 steer 时直接跳过 legacy 预匹配 当前版本产生的 normal/notify 会话 无行为变化,有强 ID 与无 ID 防回归测试
system reminder / injection user-role injection 可能被 relaxed pre-match 冒领后续 steer 并被移出前一个 fork 截点 relocation 只接受 visible turn append,injection 保持原位置且不冒领回合 带 system reminder 的旧会话,在 Desktop/Web、VS Code、KAP 或 SDK 中恢复和按轮 fork 无;新增 steer-first injection 防回归
steer-first 及其他现有匹配路径 按原规则匹配 不变 现有恢复、undo、fork 与 SDK replay 调用方 无行为变化,由既有套件覆盖
全量 fork(含 ACP session/fork) 不经过按轮切片 不变 使用全量 fork 的 ACP 及其他客户端 无行为变化,本 PR 不修改该路径
公开 wire / TypeScript 契约 既有记录字段和 matcher 导出 不新增字段,WireTurnInputMatch 与 matchWireTurnInputRecords 继续导出 读取旧 wire 的客户端及 TypeScript 使用方 无行为变化

覆盖情况:新增回归覆盖 C/C1/C2 三个 fork 截点及各自 JSON 往返后的冷恢复路径模拟、撤回文案与 C1 重复、连续 C1=C2、仅 prompt 或 message 有 ID、steer 缺 ID、完全无 ID、relaxed/promptIds、两种 steer 顺序、现代 normal/notify 强 ID 防回归、steer-first injection,以及连续同文案下的窗口化 replay。VS Code 与 KAP/SDK 共用同一 Core 修复路径,KAP 和 SDK 套件已直接验证;没有单独运行 VS Code 或 ACP 专项测试。没有 UI 变化,也不需要文档更新。

验证记录与未验证边界
  • 目标回归:22/22。
  • 相关 Core 五文件:107/107。
  • KAP sessions.test.ts:163/163。
  • Node SDK sdk-rpc-client-v2.test.ts:173/173。
  • 自定义 fork / JSON 冷恢复路径场景:8/8。
  • agent-core-v2 本机及远程 Linux 类型检查通过。
  • 完整 pnpm lint 与 check:duplication 通过。
  • 独立累计代码复审:P0/P1/P2 均为零。
  • 远程 Linux 全量 agent-core-v2:8423 passed / 3 failed / 19 skipped。首轮实现与最终累计 diff 均出现相同三项失败:两项 git sparse-checkout config.worktree 失败和一项 sessionExport 默认路径 zip ENOENT。未运行纯 base,因此尚不能确认这些失败为 base 既有问题;失败测试文件不在本次 diff 中,对应两个测试文件在本机复跑为 95/95。
  • Windows 未验证:测试机 SSH 连接被重置。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve). No external issue was provided; this PR contains a self-contained reproduction.
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR. The changesets explicitly describe the corrected legacy behavior; no maintainer approval is claimed here.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2edf7bd

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 6 packages
Name Type
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
kimi-code Patch
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/kimi-code-sdk Patch
@moonshot-ai/kap-server Patch

Not sure what this means? Click here to learn what changesets are.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 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-27T02:58:38.733677Z 8e3b40f PR opened
ℹ️ 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 27, 2026 •

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

commit: 2edf7bd

@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: 8e3b40f408

ℹ️ 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 record of records) {
const moveLegacySteerBeforeAppend = (index: number, generatedCount: number): void => {
if (appendIndexBySteer.get(index) !== index - 1) 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.

P2 Badge Exclude injected messages from steer pre-matching

When a steer-first history contains a user-role injection immediately before the steer (append(injection), turn.steer(S), append(S)), the all-user matcher's relaxed fallback consumes S for the injection regardless of content. This condition then moves the synthesized turn boundary ahead of the injection, so sliceMainRecordsAtTurn drops that reminder from a fork of the preceding turn and replay assigns the wrong turn to it. System reminders are persisted as user messages with origin.kind === 'injection', so restored older sessions where a reminder arrived just before a steer need these appends excluded from relocation or matched only after the actual steer append.

AGENTS.md reference: AGENTS.md:L111-L115

Useful? React with 👍 / 👎.


export function normalizeLegacyTurnSteerRecords(records: readonly WireRecord[]): WireRecord[] {
const appendIndexBySteer = new Map<number, number>();
for (const match of matchWireTurnInputRecords(records, true)) {

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 Skip legacy matching when no steer records exist

For large current-format sessions that contain turn.prompt and user appends but no legacy turn.steer, this unconditional call still runs the quadratic matcher: each append searches unused and then splices an element from it. Normalization is used by ordinary wire reads and restoration, and foldWireRecords now invokes it twice before running the matcher again, so long modern histories pay this legacy migration cost repeatedly even though appendIndexBySteer must remain empty. Return early from the pre-match when there are no steer records, or use a linear matching structure, to avoid slowing cold restore, replay, and forks as histories grow.

Useful? React with 👍 / 👎.

@sailist
sailist merged commit a271189 into main Nov 27, 2026
21 checks passed
@sailist
sailist deleted the bug-474-11-26-legacy-steer-undo-fork branch November 27, 2026 04:46
RealKai42 added a commit that referenced this pull request Nov 27, 2026
main moved the wireRecordObject helper out of replayBuilder/fold.ts into
wire/turnInput.ts (#5599). readErrorPayload in fold.ts still calls it, so
export it from turnInput.ts and import it in fold.ts.
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