Files
deepseek-harness/packages/compaction/compaction/README.md
T
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00

14 KiB
Raw Blame History

description, kind
description kind
Shared compaction contract for backend implementers and deployers: what conversation condensation does, when to use it, and how to build a backend. package-reference

@deepseek-ai/dsh-compaction

English | 中文

Summary

dsh-compaction lets a long session condense its older history into a single summary message, keep the recent conversation intact, and continue as if the summary had always been there — with a backend such as dsh-compaction-basic and the optional /compact command. The shadowed content stays in the session log, so replaying the session deterministically reproduces the same condensed conversation. Reach for this package when you implement a condensation backend, build something that triggers condensation, or need to recognize condensed messages — it performs no condensation itself. Choose the shipped backend when you want the feature working out of the box.

Table of Contents


Use this package

Decide first what you need. The shipped backend plus the /compact command give you automatic and on-demand condensation with no code; this package only matters when you extend or reimplement the feature. The sections below describe what condensation does, how to turn it on, and how to write a backend.

When to choose it

Choose dsh-compaction-basic when a model-written summary fits your needs: you get condensation automatically as the conversation grows, and on demand through dsh-command-compact. Choose this package when you write a backend with a different summarizer — a fixed template or a remote service — or when you build something that triggers condensation programmatically. Do not mount it alone: without a backend nothing condenses.

What condensation looks like

When condensation runs, the selected older span of the conversation is replaced by one summary message; recent history is untouched and the conversation continues from the summary. Condensation can be triggered automatically as token pressure builds, on demand, or over an explicit span; the result reports which history was condensed and the estimated tokens freed.

Turning condensation on

Mount the shipped backend to register the condensation service, and add dsh-command-compact for the on-demand command:

- name: '@deepseek-ai/dsh-compaction-basic'
- name: '@deepseek-ai/dsh-command-compact'

With these two rows the feature is on: the conversation condenses automatically as it grows, and /compact condenses immediately on request and reports how many history items were replaced. If no backend is mounted, nothing condenses and /compact fails; the full dependency chain for the shipped backend is in its own README.

Implementing a backend

Extend the provided base class and implement three operations: one that decides and performs condensation for an automatic trigger, one that condenses on demand, and one that condenses an explicit range of the conversation. Load your class as a plugin and it becomes the condensation service for the composition. The exact signatures, the failure rules, and the checkpoint marker every backend must produce are in the implementation section below and in the compaction subsystem reference.

Recognizing condensed history

Messages a backend wrote as summaries carry a stable marker, so any consumer can recognize condensed history after persistence or cloning without knowing which backend produced it. The marker is exported from the package root and from a Cordis-free subpath that client and wire programs can import.


Understand the implementation

Implementation internals — click to expand

This section explains the contract in API terms and the design decisions behind it; the feature-level behavior is covered in Use this package.

Design philosophy

The seam is built on one split and three commitments:

  • Abstract contract, concrete backends. The interface states what condensation does; providers own policy, retention, and summarization so each role evolves and swaps independently.
  • Session and LLM vocabulary are part of the contract. The operations act on a Session and the summary uses ContentBlock, so the Service Definition depends on dsh-session and dsh-llm despite the general Cordis-only guidance — a deliberate deviation recorded in the historical compaction capability-seam Agent Note.
  • The log-recorded bracket is the lock. compaction/start is appended before summarization yields and compaction/end releases; every failure makes exactly one close attempt, and a failed close leaves the unmatched start as the intentional busy signal.
  • The surface is mutated exactly once. The summary rides on a user/message replacement inside the bracket; all compaction/* events stay log-only.

Service API

The contract is three abstract operations a backend implements: compactIfNeeded for automatic pressure or context-overflow triggers, compactNow for one explicit on-demand reduction, and compactRegion for a caller-selected balanced range that excludes the initial system message. Reusable request measurement is a separate service, ctx.tokenMeter. The exhaustive per-operation semantics live in the compaction subsystem reference; the exact signatures are in src/index.ts.

A backend that summarizes through ctx.llm.stream() must forward the abort signal into the call's GenerateOptions.signal, so an abort or fiber dispose tears down the in-flight summarization. Automatic and explicit-region brackets recover their numeric owner from the open turn; manual brackets require no open turn and stamp turn: null.

Manual failure taxonomy

The synchronous compaction/summary-error waterfall lets a backend request durable input recovery for a failed summary and an explicit selection. A listener returns true only after recording progress, or calls next() to delegate. The backend checks cancellation and selection stability before dispatch, then re-derives and re-prices input before retrying. The event declaration documents its payload; image policy belongs to dsh-compaction-image-offload.

Expected manual failures throw ManualCompactionError with a stable code from a small closed set; only failures after the compaction/start marker are recorded — as a compaction/end carrying the error — while a busy rejection or pre-start cancellation leaves no record. The per-code semantics live in the compaction subsystem reference.

Tool-pairing boundaries

The Service Definition exports toolPairingBalancedBefore(session, seq) and toolPairingBalancedAfter(session, seq) for snapping and validating compaction edges. A safe edge has no unanswered assistant tool call crossing it. Each helper validates that the event sequence is in the current surface and answers from balances cached per cut in surface order, so repeated checks read no events; a replace generation rebuilds the cache, and missing seqs or an orphan tool/result reject as corrupt surface state.

The surface contract

A successful backend run records compaction/start, a log-only compaction/summary, the replacement user/message checkpoint, and compaction/end. The checkpoint replaces only the selected range. The agent loop rebuilds current system instructions before the next model attempt.

The replacement sits inside the lock bracket, so a crash between compaction/start and compaction/end leaves a detectable orphaned lock rather than a compaction/end that falsely claims success. deriveMessages() renders the summary as a user-role message at the selected range’s position; the shadowed events stay in the raw log, so replay is deterministic. The per-event payloads are enumerated in the compaction subsystem reference.

Source map

File Role
src/index.ts Plugin entry: abstract CompactionEngine, CompactionTrigger, ManualCompactionError, ctx.compaction merge
src/types.ts CompactionResult and the declaration-merged compaction/* session events
src/tool-pairing.ts Per-session cut-balance cache behind the two boundary helpers
src/checkpoint.ts Cordis-free checkpoint source constructor and predicate (./checkpoint leaf)
src/brand.ts CompactionId branded identity

Locking and serialization

One log-recorded lock is shared by all entry points. Tail inspection finds the latest unmatched compaction/start and the newest session/end-seed; an unmatched start after that boundary is live and reports busy, while an older one is stale evidence from a prior process lifecycle. A live bracket cannot cross a turn/start or turn/end. The markers are lock time points, not an exclusive container: an idle inject() may append unrelated context between a manual start and end, so the manual path revalidates its selected span rather than demanding whole-surface equality.

Events

The compaction/* events extend SessionEventMap (merge-extensible) via declaration merging — session events, not Cordis Events, and all log-only. The generated persistence log event catalog owns the per-event payloads; compaction/prune documents the shadow-price protocol shared with the tool-result pruner.


Further Exploration

Read these pages when the package-level contract is not enough; they move from the shared vocabulary to the shipped backend and the decision evidence.


Model Experience

Conversation history, when a backend is invoked

What the model sees

A successful backend replaces the selected conversation range with one user-role summary checkpoint — a user/message carrying surfaceOp: { op: 'replace', startSeq, endSeq }. The raw events stay logged but stop appearing in derived model messages; the seam itself performs no rewrite.

Token effect

Zero direct tokens from this Service Definition. A backend trades many retained history tokens for one summary and leaves the recent tail unchanged.

KV Cache effect

A successful backend replacement invalidates reuse from the first shadowed history token; the seam itself does not alter a request.

Known Limitations and Deferred Work

These limits describe what condensation cannot do, regardless of which backend is loaded; they are the current package constraints.

  • Human command, not a model tool — condensation is triggered by the /compact command and by automatic pressure; no model-facing compaction tool is registered.
  • Some single-unit overflow is out of contract — balanced summary compaction cannot split one indivisible unit. The optional pruning companion can still repair a closed tool pair when text-bearing tool-result bulk is removable; a large non-tool node or a tool unit whose non-prunable remainder is oversized cannot be compacted.
  • An envelope that alone approaches the window is not surface-compaction work — condensing conversation history cannot make required system instructions or tool schemas fit a smaller window.

Dev Note

Working context for maintainers — click to expand

This Dev Note is working context for maintainers and is explicitly non-authoritative; shipped behavior lives in the sections above, the package code, and the linked Agent Notes.

  • Model-facing tool, undecided — compaction is human-command only. A model-facing compaction tool remains an open question; it would need its own schema and interaction with the existing command path.
  • Template and remote backends, undecided — the SummaryResult contract already carries an unmarked rawOutput variant for summarizers that do not identify a call through ctx.llm.stream(), but no such backend ships.
  • Range arguments for /compact, undecided — the argument-free form keeps behavior stable across command adapters; explicit range endpoints stay the programmatic compactRegion() path.