Files
deepseek-harness/docs/subsystems/compaction.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

20 KiB

Compaction

English | 中文

The compaction seam — a capability seam split like bash: Service Definition (dsh-compaction, ctx.compaction), Service Provider (a backend such as dsh-compaction-basic), and human Consumer (dsh-command-compact). Compaction is one optional capability, not part of the agent-loop spine — so its vocabulary lives here, not in core.md. A tokenizer- or template-based backend is a sibling package implementing the same interface. Unlike bash, the interface necessarily depends on dsh-session and dsh-llm: its verbs act on an agent-owned Session, and its durable summary event uses the ContentBlock vocabulary (see the compaction capability-seam reference).

Source: packages/compaction/compaction/src/types.ts

The compaction/* session events

Compaction extends SessionEventMap with three event types via declaration merging. All three are log-only — they record the lock, summary, selected range, shadowed event seqs, token count, and model call without joining the surface. SurfaceEventType is deliberately NOT extended (only message-producing events reach the model), so the summary itself rides on a separate user/message with surfaceOp: { op: 'replace', startSeq, endSeq }. The next model attempt consolidates current system instructions through ordinary system/message replacements. The historical Agent Note records the rationale for reusing user/message.

Event Payload Role
compaction/start { turn } acquires the log-recorded lock; a number identifies the open automatic turn, while null identifies a standalone manual attempt
compaction/summary { summary, rawOutput?, llmStreamCall?, shadowedRange, shadowedSeqs, shadowedTokenCount, provider, model, maxTokens?, usage? } the safe summary projection, optional complete provider output and usage, an llmStreamCall: true marker when producing the result consumed exactly one call through this context's ctx.llm.stream() (which requires complete rawOutput), the shadowed surface-boundary pair (start/end seqs — a position span, not a numeric interval), the shadowed seqs in surface order, the estimated token count, and the summarize call's envelope (provider, model, plus its generation cap when one applied) — logged so the one-shot request is reconstructable from log + code (the reconstructability Agent Note); unmarked rawOutput does not identify the call path
compaction/end { turn, error? } releases the lock with the same numeric-or-null owner (error records an unsuccessful attempt)

The lock brackets the whole operation: compaction/start is appended first, then summarization, the compaction/summary record, and the user/message replacement all land, and only then compaction/end. Releasing the lock last turns a crash mid-operation into a detectable orphaned lock (a compaction/start with no matching compaction/end) rather than a compaction/end that falsely claims compaction finished.

The markers are lock time points, not an exclusive container. An unrelated idle injection can appear between a standalone manual start and end while summarization is pending. The manual path revalidates only its selected positional span, so that injected context survives after the replacement checkpoint. A live unmatched start blocks every entry point; an unmatched start before a newer session/end-seed is stale evidence from a prior lifecycle and is ignored.

These variants are merged inside a declare module '@deepseek-ai/dsh-session/types' block, so — unlike the top-level types on the other subsystem pages — they are not pasted as a drift-checked ```ts type-equiv block (the verify-type-equiv extractor matches only top-level declarations by name). The payload table above is the catalog entry; follow the source link for the authoritative fields.

Image offload

compaction-image-offload owns the image/offload declaration and its pure message projection. Each target identifies a current input node and exact depth-first image occurrences. The event preserves node and message identities and carries no surfaceOp. The package README owns recovery policy, registration, and detached replay.

/** Exact input-image occurrences selected by one durable offload decision. */
interface ImageOffloadTarget {
  /** Current message-producing event containing these occurrences. */
  seq: SessionSeq
  /** Zero-based depth-first image indexes within the immutable message. */
  imageIndexes: number[]
}

CompactionResult

What a successful compaction returns to its caller: the bookkeeping-event seqs, safe summary projection, shadowed range and seqs, and estimated token count.

/** Result of a successful compaction operation. */
interface CompactionResult {
  /** Stable identity shared by this compaction's complete durable lifecycle. */
  compactionId: CompactionId
  /** Human command that initiated this compaction, when it was manual. */
  sourceCommandId?: CommandId
  /** The seq of the appended `compaction/start` event. */
  startSeq: SessionSeq
  /** The seq of the appended `compaction/summary` event. */
  summarySeq: SessionSeq
  /** The seq of the appended `compaction/end` event. */
  endSeq: SessionSeq
  /** The summary content blocks produced by the backend. */
  summary: ContentBlock[]
  /**
   * The surface-boundary pair that was shadowed: the seqs of the first
   * (`start`) and last (`end`) surface nodes of the replaced range. A
   * surface-POSITION span, not a numeric seq interval — after a prior replace
   * lands a fresh high-seq summary node at an older range's position, `start`
   * can be GREATER than `end`. {@link CompactionResult.shadowedSeqs} is the
   * authoritative set of shadowed nodes, in surface order.
   */
  shadowedRange: { start: SessionSeq; end: SessionSeq }
  /** The seqs of all shadowed surface nodes, in surface order. */
  shadowedSeqs: SessionSeq[]
  /** Estimated token count of the shadowed content. */
  shadowedTokenCount: number
}

The service

Automatic callers state why policy is running; implementations may treat confirmed overflow more aggressively than ordinary pressure.

/** Why automatic policy is asking a backend to consider compaction. */
type CompactionTrigger = 'pressure' | 'context-overflow'

CompactionEngine exposes compactIfNeeded(agent, trigger, signal) for automatic pressure or context-overflow policy, compactNow(agent, signal) for one useful idle-session reduction even below pressure, and compactRegion(...) for an explicit inclusive balanced range that excludes the initial system message. compactNow() runs as agent maintenance between turns, returns null without writing when no useful range exists, records a standalone turn: null bracket before summarization, and flushes a closed attempt before later queued prompts may derive from the new surface. Every backend creates its replacement user/message source with compactCheckpointSource(compactionId, sourceCommandId?); client and wire consumers import that constructor, CompactionCheckpointSource, and isCompactCheckpointSource() from the cordis-free @deepseek-ai/dsh-compaction/checkpoint subpath, while the package root re-exports them for host consumers. The required transaction identity correlates the replacement checkpoint, while the predicate keeps recognition independent of any one backend. Implementations must forward the supplied signal to summarization. The seam owns no pricing API: the singleton ctx.tokenMeter directly owns estimation and replay, while dsh-compaction-basic owns retention, event sequencing, routed summarization calls, and their configuration.

Expected manual failures use ManualCompactionErrorCode:

/** Expected failure classes for an explicit idle-session compaction request. */
type ManualCompactionErrorCode =
  | 'busy'
  | 'cancelled'
  | 'changed'
  | 'summary'
  | 'commit'
  | 'persistence'

changed and summary close and persist the failed attempt without a summary replacement; image omissions recorded during recovery remain effective. commit may follow partial mutation; persistence means the in-memory bracket closed but its flush failed. Cancellation remains separate and throws the exact abort reason after required cleanup.

Pressure compaction runs at agent/pre-step against the committed request header and at agent/request against a changed destination before its header is logged. Unless an explicit summary target is configured, every summary in a session that holds an assistant message uses the route that produced the latest one, so a destination whose first request overflowed does not summarize its own overflow; a failed switch preserves that header and any completed reductions. Once pressure or canonical overflow qualifies, compaction-basic invokes optional ctx.toolResultPruner before range selection, remeasures through ctx.tokenMeter, and can advance the surface without a summary. Failed-request recovery runs through agent/request-error after the failed step closes and returns a retry action only when the surface replacement generation advances, even if later summary work throws after pruning; cancellation still wins. Region boundaries preserve tool-call/result pairing but not whole turns, allowing early closed steps of one oversized turn to compact. dsh-compaction-basic owns thresholds, retained-tail policy, overflow caps, and failure handling.

The Service Definition exports toolPairingBalancedBefore(session, seq) and toolPairingBalancedAfter(session, seq) for the tool-call/result pairing checks before and after a seq. Both validate current surface membership and reject missing seqs and orphan results; the package contract defines their cache behavior.

Tool-result pruning outcomes

The optional tool-result pruning service reports each durable content replacement and the aggregate Unicode-code-point reduction. Its public result types live in compaction-tool-result-pruner/src/types.ts.

/** Cited source event and size accounting for one landed surface replacement. */
interface PrunedEntry {
  /** Full-fidelity tool-result event shadowed by the replacement. */
  readonly originalSeq: SessionSeq
  /** Newly appended pruned tool-result event. */
  readonly replacementSeq: SessionSeq
  /** Tool call shared by the original and replacement. */
  readonly callId: ToolCallId
  /** Original text size in Unicode code points. */
  readonly charsBefore: number
  /** Replacement text size in Unicode code points. */
  readonly charsAfter: number
}
/** Aggregate outcome of one stable-surface pruning pass. */
interface PruneResult {
  /** Replacements in the snapshotted surface order. */
  readonly pruned: readonly PrunedEntry[]
  /** Total Unicode code points removed across replacements. */
  readonly charsRemoved: number
}

Cordis API

Generated from source by scripts/gen-cordis-catalog.ts (verified fresh by pnpm run verify-cordis-catalog in doc-sync; regenerate with pnpm run gen-cordis-catalog) — the language sides differ only in locale-specific paired document paths. Signature blocks use a ts cordis-catalog fence and keep the original source JSDoc; dispatch modes are defined in the primer, and the framework-inherited ctx API lives in cordis-api/inherited.md.

ctx.compaction — CompactionEngine (abstract seam)

Abstract compaction service. Implementations own trigger policy, retention, and summarization, and may consume a separate measurement service. A successful run replaces the selected surface span with one summary node and prevents concurrent compaction of the same session. The replacement user message uses compactCheckpointSource with the transaction identity so consumers recognize and correlate it independently of the backend. Load one implementation per context as ctx.compaction.

/**
 * Consider automatic compaction for one explicit trigger. Pressure policy
 * uses the latest durable routed request, while context-overflow policy may
 * force a useful balanced reduction even below the normal threshold. Return
 * `null` when no safe range can be compacted. A single oversized retained
 * unit or request envelope cannot be repaired through surface compaction.
 *
 * @param agent - agent context owning the session surface and routing options.
 * @param trigger - normal pressure or provider-confirmed context overflow.
 * @param signal - cancellation signal; model-backed implementations must forward it.
 * @returns the compaction result, or `null` if no compaction was needed.
 */
abstract compactIfNeeded( agent: CompactionAgentContext, trigger: CompactionTrigger, signal: AbortSignal, ): Promise<CompactionResult | null>

/**
 * Explicitly compact useful history even below automatic pressure thresholds.
 * Implementations synchronously start an idle task before any asynchronous
 * work, select a useful range without writing on a no-op, then
 * append a standalone `compaction/start` before summarization. That durable
 * marker is the compaction lock until one `compaction/end` attempt. Later waking
 * prompts remain accepted in FIFO order and start only after the optional
 * durability checkpoint and idle-task settlement. Context injected while the
 * summary runs may sit between the marker pair; only the selected span must
 * remain stable.
 *
 * @param agent - idle agent whose durable history should be compacted.
 * @param signal - cancellation scoped to this compaction request.
 * @param sourceCommandId - initiating command identity for a manual compaction.
 * @returns the compaction result, or `null` when no safe useful range exists.
 * @throws {@link ManualCompactionError} for expected busy, agent-cancellation,
 * changed-span, summarization/shrink, commit-stage, or persistence failures;
 * an aborted request preserves its exact abort reason. Failed attempts remain
 * visible in the log.
 */
abstract compactNow( agent: ManualCompactAgentContext, signal: AbortSignal, sourceCommandId?: CommandId, ): Promise<CompactionResult | null>

/**
 * Compact a balanced range of conversation nodes into a single summary node.
 * The initial system node, when present, lies outside the selected range.
 * `start` and `end` name an inclusive span by surface position, not numeric seq
 * order; replacements can make visible seqs non-monotonic. Both edges must be
 * balanced so assistant tool calls remain paired with their results. A model-
 * backed implementation forwards cancellation and rejects active, missing,
 * reversed, or unbalanced ranges. The target session is `agent.session`.
 * Its replacement user message must use {@link compactCheckpointSource} with
 * the transaction's `CompactionId`.
 * Use {@link toolPairingBalancedBefore} and {@link toolPairingBalancedAfter}
 * for the edge checks.
 *
 * @param start - first surface seq, inclusive.
 * @param end - last surface seq, inclusive.
 * @param agent - context whose session is mutated and whose routing options guide summarization.
 * @param signal - optional cancellation; model-backed implementations must forward it.
 * @throws when compaction is active or the range is missing, reversed, or unbalanced.
 * @returns the appended event seqs, summary, replaced range, and token accounting.
 */
abstract compactRegion( start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal, ): Promise<CompactionResult>

Types: CommandId · SessionSeq

Source: packages/compaction/compaction/src/index.ts

ctx.toolResultPruner — ToolResultPruner

Deterministic head/middle/tail pruning for current tool-result surface nodes.

/**
 * Measure text content in Unicode code points; non-text blocks cost zero.
 * @param blocks - tool-result content to measure.
 * @returns total Unicode code points across text blocks.
 */
measureContent(blocks: readonly ContentBlock[]): number

/**
 * Replace an over-budget text middle while retaining rich-block order.
 * Text slicing is by Unicode code point, not UTF-16 code unit, so a retained
 * boundary cannot split a surrogate pair. Grapheme clusters may still split.
 * @param blocks - original tool-result content.
 * @returns pruned content, or `null` when the text is within budget.
 */
pruneContent(blocks: readonly ContentBlock[]): ContentBlock[] | null

/**
 * Prune every over-budget tool result from one stable current-surface snapshot.
 * Each replacement preserves the complete event data except for `content`,
 * cites the shadowed node so replay can recover the replacement input, and is
 * immediately preceded by a `compaction/prune` shadow-price event pricing the
 * shadowed node through the injected token meter, so pure consumers can
 * subtract it without per-node state.
 * @param session - session whose current surface is rewritten.
 * @returns landed replacements and aggregate Unicode-code-point savings.
 * @throws when the session rejects a replacement; replacements committed
 * earlier in the pass remain durable.
 */
pruneSession(session: Session): PruneResult

Types: ContentBlock · Session

Source: packages/compaction/compaction-tool-result-pruner/src/index.ts

compaction/* events

compaction/summary-error — waterfall

Recover a failed summary request by synchronously recording a durable change to its selected input. Return true only after making progress; the provider re-derives and re-prices the selection before retrying. Call next() when the failure cannot be recovered. Decisions survive a later summary failure or cancellation.

/**
 * Recover a failed summary request by synchronously recording a durable
 * change to its selected input. Return true only after making progress;
 * the provider re-derives and re-prices the selection before retrying.
 * Call next() when the failure cannot be recovered. Decisions survive a
 * later summary failure or cancellation.
 * @param payload.session - session containing the selected input.
 * @param payload.sourceEventSeqs - selected message events in request order.
 * @param payload.error - failure thrown by the summarizer.
 * @param payload.signal - optional compaction cancellation signal.
 * @param next - delegate to the next recovery listener.
 * @mode waterfall
 */
'compaction/summary-error'(payload: { session: Session; sourceEventSeqs: readonly SessionSeq[]; error: unknown; signal?: AbortSignal }, next: () => boolean): boolean

Types: Session · SessionSeq

Source: packages/compaction/compaction/src/index.ts