Contextdoc/{zh,en}/design/runtime/context/engineering.md

Context Engineering: Overview

Status: proposed 2026-11-15, for review. This is the entry to the context-engineering design: how a session is stored, how a model request is built from it, how it is compacted, an

Status: proposed 2026-11-15, for review. This is the entry to the context-engineering design: how a session is stored, how a model request is built from it, how it is compacted, and where plugins can change each step. Each part has its own document; this one lists the decisions, the IM scenarios they must survive, and the build order.

The design review records scenarios, impact, recommended changes and confirmation criteria for C01–C08.

PartDocumentProposal
Session storage, one log, projectionsSessionsP49
Partitions, run-order cuts, commit, result references, deletion (review C01–C05)Session contractsP49
Session compactionSession compactionP50
Request assembly and cachingAssemblyP51
Plugin points for context and compactionExtensionsP52
Run-level compaction (built)CompactionP5
Retrieval of memory and wiki (built)RetrievalP46
Chat window, session keysChannel contextP29
Research at pinned commitsSessions and compaction, agents—

1. The Problem

Today the model's view of a conversation is put together from six stores: runs.input and runs.result for past runs, tool_calls for past tool activity, interactions for questions, the checkpoint for the current run, events for the chat window and conversation_resets for /new. Each answers one question; none holds the conversation. The consequences seen in Feishu testing (P48): past tool results reached the model as text it imitated, a repeated request was answered by copying an earlier reply, and fixes had to be patched per store (AnsweredAsks for ask_user only). Compaction exists only inside one run (P5); a long direct chat or a busy group has no compaction at all, only the 10-turn and 2-hour cuts.

2. Decisions

  1. One append-only log per session is the source of truth (session_entries). The UI timeline, the model's view, history for other runtimes, the audit trail and channel rendering are projections of it. The old stores stay for their own jobs (the ledger for idempotency, interactions for answers), and the log refers to them.
  2. Compaction is an entry, not a rewrite. A compaction entry holds the summary, the group digest, a deterministic appendix and the id of the first kept entry; the log under it is untouched, so the UI and the audit still see everything.
  3. The view is rebuilt, not accumulated. Each run's request is assembled from the latest compaction entry, the kept entries and fresh run context; instructions, memory and wiki are re-read from their sources, never carried inside summaries.
  4. Cache order is a rule. Stable material (tools, system prompt, instructions, summary, history) comes first; per-run material (time, sender, chat window, recall) after; per-call material last. Breakpoints and cache keys are hints the model plugin maps.
  5. Cheap levels first. Shaping and clearing run before any summary; summaries run with the agent's own model by default, because it reads the cached prefix.
  6. Plugins decide, the agent commits. Compaction strategies, context processors and memory flush are plugin roles with validated outputs; the agent checks them, writes the entry and owns the fallback.

3. IM Scenarios

ScenarioPressureHandled by
A direct chat over monthsHundreds of runs, one session keyEpisodes (history_idle), session compaction T2/T4, retention (sessions, section 7)
A busy group, bot mentioned rarelyThousands of ambient lines between runsAmbient entries outside the view; chat window by token budget; digest (T6)
A group where many members use the botMany short runs, changing sendersCache order keeps senders out of the prefix; per-run lock; attribution by id
A group threadThread-scoped key (/t:)Its own session; parent group digest optional as a context item
Private answer inside a groupOne member's approval or questionuser: visibility, per-person notes in compaction
A long tool-heavy task in chatResults of hundreds of KBShaping (L1), clearing (L2), tool_result
Images and files in historyLarge partsEntries hold references; images re-attached only from the kept tail
/new and topic changesUser wants a clean start/new closes the session and opens the next; idle rollover (10 days direct, 2 days group) does the same

4. End-to-End Trace

A Feishu group, member B mentions the bot after 400 ambient lines since the last run.

  1. The channel plugin delivers the event; the Host appends one ambient_message entry per unmentioned line as it arrives and a user_message entry for the mention, routed to session feishu:oc_1.
  2. The Host takes the session's run lock, creates the run, appends run_start, and builds RunInput.Session: latest compaction entry, entries since its cut, the chat window (newest lines up to 2,000 tokens) and ambient tokens since the last digest (6,500).
  3. The agent sees ambient tokens over ambient_digest_at; it asks the digest strategy for an updated digest and appends it in a compaction entry (digest only, summary unchanged).
  4. It assembles the request: A–C unchanged (cache hit), D with the new digest (cache miss from here on), E, F with the chat window and recall, I.
  5. Steps run; each response and shaped result is appended through RuntimeHost.Append with key (run, step); a crash resumes from the checkpoint, and repeated appends are ignored by key.
  6. The final reply is appended as final, delivered, and run_end closes the run. The next run in this group shares A–E.

5. Build Order

PhaseContentExit test
1session_entries written by the Host for user, ambient, final, reset, run markers; dual write next to today's storesTimeline projection equals today's history for 50 recorded Feishu sessions
2RuntimeHost.Append for steps and shaped results; RunInput.Session replaces []Turn; P48 closedHistory pollution cases pass (history_repeat, Feishu cases 6–8)
3Assembly order of P51, cache hints, per-zone budgets, audit recordPrefix identical across runs; cache rate logged
4Session compaction P50 with the built summarizer, T1–T5Compaction cases on Kimi and GLM, 30-run session under target
5Group digest (T6), per-person notes2,000-line group case
6Extension roles of P52 (compactor, context_processor, flush observer) with one sample pluginSample strategy swapped by config without Host or agent change

The Host contract changes (RuntimeHost.Append, RunInput.Session, ChatRequest.CacheHints/CacheKey/Purpose) are kernel decisions and get one ADR before phase 2.

6. What Is Not Planned

  • ◆Editing or deleting individual past messages by the model (Claude Code and Codex do not offer it either).
  • ◆Branching sessions (parent is kept in the entry so a fork can be added later; no UI is planned).
  • ◆Vector search over the session log; session_search is text search, and semantic recall is a Memory plugin's job (P12).
  • ◆Cross-session summaries; long-term facts go to Memory.

7. Acceptance

The acceptance tests of each part are listed in its document; this design is accepted when phases 1–4 pass their exit tests and the real-suite cases history_repeat, compaction and a new group_flood (400 ambient lines, then a request that needs one of them) pass on Kimi and GLM.