Skip to content

fix(agent-core-v2): preserve tool result notes on fork - #4867

Merged
sailist merged 5 commits into
release/2026-11-12from
bug-357-11-12-fork-tool-result-notes
Nov 12, 2026
Merged

sailist merged 5 commits into
release/2026-11-12from
bug-357-11-12-fork-tool-result-notes

Conversation

@sailist

@sailist sailist commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Side-channel agents created by forking the main conversation can lose tool result notes from their model-visible history. Besides dropping information available to the parent agent, this changes the shared request prefix and can cause severe prompt-cache misses. This PR preserves those notes in forked histories.

Bug Reproduction Steps

  1. Let the main agent execute a tool such as Write, whose result includes a system note.
  2. Start a btw side-channel agent and compare the parent and child model requests.
  3. The parent request contains the note, while the forked request omits it from the inherited tool result.

The existing fork parity test was extended with this scenario. Before the fix, it failed with the system note missing from the child request; after the fix, the complete parent request prefix is preserved.

Root Cause

The context projection moves a trailing note out of the tool result content so the normal request renderer can add it back exactly once. agentLifecycle.fork() converts that projected history into core HistoryMessage entries, but the conversion stores the note only in metadata. The core request path does not render that metadata note, so the forked request loses it.

This is a fundamental fix at the history-conversion boundary rather than a serializer workaround.

Code Changes

  • Add a dedicated historyFromContextPreservingToolNotes() used only by agentLifecycle.fork(), restoring a non-empty note to model-facing tool result content when it is not already present. The existing historyEntryFromContext() and historyFromContext() retain their original single-parameter signatures, and ordinary resume and compaction keep the default conversion behavior.
  • Avoid duplicating notes that already appear as the final text part or as a newline-suffixed part of the content. When converting back to ContextMessage, retain the structured note while removing its duplicate from display content.
  • Extend the existing fork parity regression with a real Write result, final request-prefix assertions, and projected-history assertions without increasing the test count.
  • Add a patch changeset.

Verification:

  • Local test/session/subagent/forkParity.test.ts: 19/19 passed.
  • Remote m0-dev test/session/subagent/forkParity.test.ts, test/features/plan/plan.test.ts, and test/boot.test.ts: 66/66 passed, including the three live/resume cases that failed on the initial broad conversion; the CI boot cleanup error did not reproduce.
  • Full typecheck across every package and apps/kimi-code, matching the CI command, passed.
  • Type-aware oxlint on the changed files: 0 errors; only warnings on unchanged lines.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Tool results with notes inherited by btw and other agent forks Notes are omitted from the model request Notes are preserved, matching the parent request and keeping the shared prefix stable Forked agents and users relying on complete inherited context and prompt-cache reuse No opt-out; this restores the intended parent-history semantics
Tool results whose content already ends with the note Could be duplicated if note restoration were unconditional Existing content remains unchanged and the note is not duplicated Existing main and restored histories Covered by the final request-prefix assertion
Tool results without a note Existing rendering No behavior change All existing agents The conversion only adds content for a non-empty note; the existing 19 fork parity tests pass
Ordinary resume and compaction Existing default history conversion Unchanged; note restoration is opt-in only for fork initialization Existing sessions restored from disk All 32 plan tests pass, including the three live/resume cases that failed on the initial broad conversion
Forked projected/display history A restored note could appear both in content and in the structured note field Content retains the raw tool output while the structured note remains available Transcript and other context-projection consumers The child projected-history assertion checks that no duplicate system note appears in content

No wire, persistence, public API, or configuration shape changes are introduced.

Checklist

  • I have read the CONTRIBUTING document.
  • No related issue; the reproduction and root cause are documented above.
  • I have updated an existing regression test to cover this fix.
  • The behavior-change table above is complete; no behavior is removed and no default is flipped.
  • Added a patch changeset.
  • No documentation update is needed for this internal history-conversion fix.

@changeset-bot

changeset-bot Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7fda990

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

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code 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 12, 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-12T07:53:55.349856Z 7fda990 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 12, 2026 •

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

commit: 7fda990

@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: 0803e3111c

ℹ️ 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".

const last = content.at(-1);
const rendered = last?.type === 'text' &&
(last.text === entry.note || last.text.endsWith(`\n${entry.note}`));
if (!rendered) content = [...content, { type: 'text', text: entry.note }];

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 Keep internal notes out of forked display content

When a fork inherits a noted tool result such as Write or Edit, this line adds the internal <system>…</system> note to message.content while retaining the same value in meta.note. The fork journal then round-trips that entry into a durable context.append_message, and the conversation fold treats message.content as the displayed tool output, so BTW/forked sessions expose the internal model instruction as user-visible result text while also carrying it separately as the note. Preserve the note in model-facing history, but strip it when converting back to ContextMessage, and assert that the child's projected history still contains only the raw tool output.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

@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: 2c7a91d8eb

ℹ️ 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".

Comment on lines +46 to +48
const rendered = last?.type === 'text' &&
(last.text === entry.note || last.text.endsWith(`\n${entry.note}`));
if (!rendered) content = [...content, { type: 'text', text: entry.note }];

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 Append notes even when raw output shares their suffix

When a tool's genuine last text part equals the note or ends in \n${note}—possible with arbitrary file or tool output—rendered becomes true even though sourceLoop.history() stores the raw output separately from entry.note. The fork therefore does not append a note marker, and contextFromHistoryEntry subsequently mistakes the genuine suffix for that marker and removes it, leaving the child with empty or truncated tool output and breaking parent/child request-prefix parity. Append an unambiguous copy here, or otherwise track whether the note was injected, rather than deduplicating by text alone.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

Comment on lines +55 to +59
export function historyFromContext(
messages: readonly ContextMessage[],
preserveToolNotes = false,
): HistoryMessage[] {
return messages.map((entry) => historyEntryFromContext(entry, preserveToolNotes));

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 Restore tool notes when reloading fork journals

When a forked agent is resumed after a process or session restart, its inherited messages have been persisted through contextFromHistoryEntry, which removes the rendered note from content and retains only ContextMessage.note. restoreLoopJournal() then calls historyFromContext(...) at journal.ts:195-197 without enabling preserveToolNotes, recreating the exact metadata-only HistoryMessage that the core request path does not render. The fix therefore lasts only until restart: resumed BTW and background forks silently lose the inherited model instruction and cache prefix again. Restore notes while rebuilding persisted fork histories, or persist an explicit representation that the core request path renders.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

@sailist
sailist merged commit 8aacf88 into release/2026-11-12 Nov 12, 2026
25 of 27 checks passed
@sailist
sailist deleted the bug-357-11-12-fork-tool-result-notes branch November 12, 2026 08:25
@github-actions github-actions Bot mentioned this pull request Nov 12, 2026
Grapedge added a commit that referenced this pull request Nov 12, 2026
* fix(agent-core-v2): truncate oversized skill content (#4834)

* fix(kap-server): bind the main agent when a session is created (#4839)

* fix(kap-server): bind the main agent when a session is created

* fix(kap-server): reject a profile on prompt submissions

* fix(kap-server): reject a profile change through the session profile

* fix(kap-server): wait for model configuration before binding a new session

* fix(agent-core-v2): deduplicate restored task notifications (#4836)

* fix(agent-core-v2): deduplicate restored task notifications

* chore: add notification replay fix changeset

* fix(agent-core-v2): preserve task notifications after prompt-only crashes

* fix(agent-core-v2): complete prompts before ending turns

* test: align lifecycle snapshots with prompt completion order

* fix(agent-core-v2): settle all prompts during turn finalization

* fix(kap-server): drop reserved metadata keys from session profile updates (#4842)

* fix(kap-server): drop reserved metadata keys from session profile updates

* fix(kap-server): keep stored reserved metadata keys on profile updates

* docs: split and rewrite the server API reference (#4841)

* docs: split and rewrite the server API reference

* docs: redirect old server API anchors to the split pages

* docs: describe profile metadata as a replacement

* docs: mark question responses as answered-only

* fix(kap-server): avoid heartbeat timeout after scheduling stalls (#4823)

* fix(kap-server): avoid heartbeat timeout reaping after stalls or clock jumps

* fix(kap-server): grace heartbeat window for short scheduling stalls

* fix(kap-server): treat only clearly late heartbeats as scheduling stalls

* fix(kap-server): time heartbeats on a monotonic clock and drain queued input before reaping

---------

Co-authored-by: Kimi Code (Grok Bot) <[email protected]>

* fix(kap-server): undo a turn only once when requests race (#4846)

* docs: describe heartbeat stall handling (#4849)

* docs: describe heartbeat stall handling

* docs: explain the monotonic clock in the heartbeat notes

* fix(agent-core-v2): acquire session lock before loop restoration (#4848)

* fix(agent-core-v2): acquire session lock before loop restoration

* chore: add session lock lifecycle changeset

* fix(agent-core-v2): hold session lock through loop restoration

- add an operation-scoped lease to the session run gate
- hold it across loop initialization, reset, and pending drains
- cover idle timeout and release ordering

* fix(agent-core-v2): keep the output of stopped tool calls (#4854)

* fix(kap-server): drop the partial reply of a retried step (#4855)

* fix(agent-core-v2): dedupe historical tool schemas (#4862)

* fix(agent-core-v2): dedupe historical tool schemas

* chore: add duplicate tool schema changeset

* fix(agent-core-v2): preserve first tool schema declaration

* fix(agent-core-v2): remind on changed tool schemas

* fix(agent-core-v2): block stale tool schema calls

* fix(agent-core-v2): normalize registry schemas in pending checks

* fix(agent-core-v2): import registry tool metadata type

* fix(agent-core-v2): preserve abort handling during validation

* fix(agent-core-v2): refine validation hook preparation

* fix(agent-core-v2): make validation hooks synchronous

* fix(agent-core-v2): preserve tool result notes on fork (#4867)

* fix(agent-core-v2): preserve tool result notes on fork

* chore: add fork tool result note changeset

* fix(agent-core-v2): scope tool result note restoration to forks

* fix(agent-core-v2): normalize inherited tool result notes

* fix(agent-core-v2): isolate fork note restoration

* feat(tui): sweep running titles toward text and add KIMI_CODE_TUI_ANIMATION_FPS (#4843) (#4870)

* chore: sync web dist from code-app (#4871)

code-app: 8ab17294e031323186d357d121c5360b8353900e

Co-authored-by: kimi-agent-bot <[email protected]>

* ci: release packages (#4835)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* chore: sync web dist from code-app

code-app: 5835391dac3a2b9e0c65ffbd418f0d6042a7adb2

---------

Co-authored-by: Haozhe <[email protected]>
Co-authored-by: qer <[email protected]>
Co-authored-by: Kimi Code (Grok Bot) <[email protected]>
Co-authored-by: grapedge <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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.

1 participant