compaction

package
v1.5.154 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

This file (US-003) ties the compaction pieces together: given a message list and settings, it finds the cut point, extracts file operations from the summarized range, generates the structured summary, and returns a CompactionResult ready to be persisted as a session compaction entry and used to rebuild the agent context. Mirrors pi's prepareCompaction + compact.

This file (US-003) covers summarization: the structured prompts, the conversation serializer, file-operation extraction, and GenerateSummary, which drives a provider stream to turn compacted history into a structured checkpoint summary. It mirrors pi's harness/compaction/compaction.ts prompts and utils.ts helpers, adapted to golder's flat message list and Provider stream.

Package compaction implements context-window token accounting and the decision of when a long session must be compacted, mirroring pi's harness/compaction/compaction.ts.

This file (US-001) covers the token side: estimating a message's token footprint from a character heuristic, deriving the current context-token usage (preferring provider-reported Usage over estimation), and the ShouldCompact threshold check. Cut-point finding (US-002) and summarization (US-003) live in sibling files.

Index

Constants

View Source
const SUMMARIZATION_SYSTEM_PROMPT = `` /* 310-byte string literal not displayed */

SUMMARIZATION_SYSTEM_PROMPT instructs the model to only emit the structured summary and never continue the conversation. Verbatim from pi.

Variables

View Source
var DefaultCompactionSettings = CompactionSettings{
	Enabled:          true,
	ReserveTokens:    16384,
	HeadroomPercent:  20,
	KeepRecentTokens: 65536,
}

DefaultCompactionSettings matches pi's DEFAULT_COMPACTION_SETTINGS (reserve 16k reserve) with two departures from it: a 20% headroom, and a 64k tail.

The reserve is a percentage rather than pi's fixed 16k because a fixed number cannot serve every window: 16k is most of a 32k window but a rounding error on a 1M one, where it let a conversation climb to 98.4% full — later than the point where a single fat turn can still overflow the window, and an overflow mid-turn is an API error rather than a graceful compaction. 20% means the trigger sits at 80%, which is earlier than the industry's 90% (Codex) and 90-95% (Claude Code) on purpose: the reserve has to absorb ONE turn, and a tool-heavy turn on a 200k window can add 20-40k tokens of file contents and command output in a single batch. Compacting at 90% left 20k of room for that turn, and left the model finishing its work in the dirtiest 10% of the window.

The tail went from pi's 20k to 64k because compaction is lossy in exactly the place continuity matters: the retained messages are the raw file reads, edits and decisions a summary flattens. 64k is a third of a 200k window — enough to keep the working set of a real task verbatim — and KeepTokens clamps it on smaller windows, where a fixed 64k would leave nothing to summarize.

Functions

func EstimateTokens

func EstimateTokens(msg agentcore.Message) int

EstimateTokens returns a conservative token estimate for one message using the same character heuristic as pi's estimateTokens (ceil(chars / 4)).

func GenerateSummary

func GenerateSummary(
	ctx context.Context,
	stream provider.StreamFn,
	model provider.Model,
	msgs []agentcore.Message,
	reserveTokens int,
	previousSummary string,
	cfg provider.StreamConfig,
) (string, error)

GenerateSummary drives a provider stream to summarize msgs into a structured checkpoint. When previousSummary is non-empty it uses the update template and embeds the prior summary in <previous-summary> tags; otherwise it uses the first-time template. maxTokens is bounded to min(0.8*reserveTokens, model.MaxOutputTokens) as in pi. The returned text is the concatenation of the assistant response's text blocks. A terminal error/aborted response is surfaced as an error.

func ShouldCompact

func ShouldCompact(contextTokens, contextWindow int, settings CompactionSettings) bool

ShouldCompact reports whether context usage has exceeded the usable window: contextTokens > settings.UsableTokens(contextWindow) — pi's contextTokens > contextWindow - reserveTokens, with the reserve widened to max(ReserveTokens, HeadroomPercent of the window). Disabled settings or a non-positive contextWindow (unknown) never trigger compaction.

Types

type CompactionDetails

type CompactionDetails struct {
	// ReadFiles are files read but not modified in the compacted range.
	ReadFiles []string `json:"readFiles"`
	// ModifiedFiles are files written or edited in the compacted range.
	ModifiedFiles []string `json:"modifiedFiles"`
}

CompactionDetails records the files touched in the compacted history, stored alongside a compaction entry so a later iterative compaction can seed its file lists. Mirrors pi's CompactionDetails.

type CompactionResult

type CompactionResult struct {
	// Summary is the structured summary that replaces the compacted history.
	Summary string
	// FirstKeptIndex is the index of the first retained message.
	FirstKeptIndex int
	// TokensBefore is the estimated context tokens before compaction.
	TokensBefore int
	// KeptCount is how many messages the cut retained verbatim
	// (len(msgs) - FirstKeptIndex). It is stamped onto the checkpoint so token
	// accounting knows the retained tail carries pre-compaction usage readings.
	KeptCount int
	// Details holds the file operations extracted from the compacted range.
	Details CompactionDetails
}

CompactionResult is the outcome of a compaction: the summary text (with file metadata appended), the index where retained history begins, the estimated tokens before compaction, and the extracted file details. Mirrors pi's CompactionResult, adapted to golder's flat message list (index vs entry id).

func Compact

func Compact(
	ctx context.Context,
	stream provider.StreamFn,
	model provider.Model,
	msgs []agentcore.Message,
	settings CompactionSettings,
	contextWindow int,
	prevCompactionIndex int,
	prevDetails *CompactionDetails,
	previousSummary string,
	cfg provider.StreamConfig,
) (*CompactionResult, error)

Compact prepares and generates a compaction over msgs. It cuts at FindCutPoint(msgs, settings.KeepTokens(contextWindow)), summarizes messages in [prevCompactionIndex+1, firstKeptIndex) (seeding file ops from a prior compaction's details when provided), and appends <read-files>/<modified-files> metadata to the summary. previousSummary, when non-empty, switches to the iterative update template.

contextWindow is the window the cut has to fit inside, which is what clamps the retained tail (see CompactionSettings.KeepTokens). A non-positive window means unknown: the tail is then taken as configured, and the caller is the one that decides whether compacting makes sense at all.

prevCompactionIndex is the index of the last already-applied compaction point (-1 when none); summarization starts just after it so each compaction only covers the newly accumulated history. prevDetails carries that compaction's file lists so long-lived reads/edits survive across successive compactions.

It returns (nil, nil) when there is nothing to compact (no valid cut point or an empty summarization range).

func (*CompactionResult) Message

Message builds the CompactionMessage to persist for this result: the summary text plus the estimated tokens-before and the file details (as raw JSON).

func (*CompactionResult) RebuildContext

func (r *CompactionResult) RebuildContext(msgs []agentcore.Message, now int64) agentcore.MessageList

RebuildContext returns the post-compaction message list: the compaction checkpoint followed by the retained recent messages (msgs[FirstKeptIndex:]). The summarized prefix is dropped and replaced by the single checkpoint, keeping context continuous while staying within the window. Mirrors pi's post-compact context reconstruction (summary entry + retained tail).

type CompactionSettings

type CompactionSettings struct {
	// Enabled gates automatic compaction decisions.
	Enabled bool
	// ReserveTokens is reserved for the summary prompt and its output, and is
	// also the floor under HeadroomPercent: the usable window is
	// contextWindow - max(ReserveTokens, HeadroomPercent of the window).
	ReserveTokens int
	// HeadroomPercent keeps a slice of the window free beyond ReserveTokens, as
	// a percentage (10 = full at 90%). A fixed reserve cannot serve every
	// window: 16k is most of a 32k window but a rounding error on a 1M one,
	// where it let a conversation climb to 98% before compacting. 0 keeps the
	// fixed reserve only (pi's behavior).
	HeadroomPercent int
	// MaxContextTokens, when > 0, lowers the window the trigger is computed
	// from (the [compaction] max_context key): a user on a metered or
	// quality-sensitive setup can compact earlier than the model's hard
	// ceiling. It never raises the window — a value at or above the provider
	// limit is clamped to it, so the knob can only make compaction earlier.
	MaxContextTokens int
	// KeepRecentTokens is the approximate recent-context token budget to retain
	// after compaction (consumed by FindCutPoint in US-002).
	KeepRecentTokens int
}

CompactionSettings holds the thresholds and retention knobs for compaction, mirroring pi's CompactionSettings.

func (CompactionSettings) EffectiveReserve added in v1.2.18

func (s CompactionSettings) EffectiveReserve(contextWindow int) int

EffectiveReserve returns the tokens held back before compaction triggers: the larger of the fixed ReserveTokens and HeadroomPercent of the effective window. A non-positive window returns ReserveTokens.

func (CompactionSettings) EffectiveWindow added in v1.2.18

func (s CompactionSettings) EffectiveWindow(contextWindow int) int

EffectiveWindow returns the window the compaction decision counts against: the provider window, lowered to MaxContextTokens when that is set. A non-positive contextWindow (unknown) returns MaxContextTokens, or 0 when neither is known.

func (CompactionSettings) KeepTokens added in v1.3.0

func (s CompactionSettings) KeepTokens(contextWindow int) int

KeepTokens returns the token budget for the verbatim tail that survives a compaction: KeepRecentTokens, clamped so that a compaction can always cut.

The clamp is not a nicety. The tail and the window are independent knobs, and a tail larger than the usable window leaves nothing to summarize: FindCutPoint walks backwards from the end, never reaches its budget, and keeps everything — so auto-compaction stops working silently, on exactly the small windows where overflowing the model's window is easiest, and the run then fails against the provider's limit instead of compacting. Half the usable window is the ceiling, which leaves the other half for what follows the cut (the summary plus the turn being worked on).

func (CompactionSettings) ReserveDescription added in v1.2.18

func (s CompactionSettings) ReserveDescription(contextWindow int) string

ReserveDescription names which knob set the reserve for a window, for the status displays that print the trigger point: the percentage headroom when it dominates, the fixed reserve otherwise.

func (CompactionSettings) UsableTokens added in v1.2.18

func (s CompactionSettings) UsableTokens(contextWindow int) int

UsableTokens returns the context-token ceiling at which compaction triggers: contextWindow minus the effective reserve. It is the single definition of "full enough", shared by ShouldCompact, the loop's decision, and the threshold /status and /memory print. A non-positive window returns 0.

type ContextUsageEstimate

type ContextUsageEstimate struct {
	// Tokens is the estimated total context tokens.
	Tokens int
	// UsageTokens is the peak tokens reported by the sampled assistant usage
	// blocks (the largest of the last usageSampleWindow readings).
	UsageTokens int
	// TrailingTokens is the estimated tokens after that usage block.
	TrailingTokens int
	// LastUsageIndex is the index of the message that provided the peak usage,
	// or -1 when no usage exists.
	LastUsageIndex int
}

ContextUsageEstimate reports the derived context-token usage for a message list, mirroring pi's ContextUsageEstimate.

func EstimateContextTokens

func EstimateContextTokens(msgs []agentcore.Message) ContextUsageEstimate

EstimateContextTokens computes context-token usage for messages, preferring provider-reported Usage over estimation: it takes the largest of the last usageSampleWindow valid assistant Usage readings and estimates only the messages that follow it. When no usage is available it estimates every message. This mirrors pi's estimateContextTokens with a windowed maximum instead of the single newest reading, so a gateway that reports one conversation at two levels cannot leave the run on the lower one.

Two kinds of reading are never used. A reading older than the newest compaction checkpoint described a context that no longer exists (its prefix was summarized away), and one carried by the tail that checkpoint kept verbatim described the pre-compaction request — reading either back would report the old size and re-trigger compaction on the very next turn. CompactionMessage.KeptCount is what marks that tail; a checkpoint written before the field existed (KeptCount 0) only excludes the prefix, so a legacy session settles after at most one extra compaction.

type CutPointResult

type CutPointResult struct {
	// FirstKeptIndex is the index of the first message retained after
	// compaction; everything before it is summarized.
	FirstKeptIndex int
	// TurnStartIndex is the index of the user message that starts the turn the
	// cut falls inside, or -1 when the cut lands on a clean turn boundary.
	TurnStartIndex int
	// IsSplitTurn reports whether the cut splits an in-progress assistant turn.
	IsSplitTurn bool
}

CutPointResult describes the cut selected for compaction, mirroring pi's CutPointResult (adapted to golder's flat message list).

func FindCutPoint

func FindCutPoint(msgs []agentcore.Message, keepRecentTokens int) CutPointResult

FindCutPoint finds the compaction cut that keeps approximately keepRecentTokens worth of the most recent messages. It accumulates token estimates from the newest message backwards; once the retained budget is reached it snaps to the nearest valid cut point at or after that message, never splitting a toolCall from its toolResult. This mirrors pi's findCutPoint.

When no valid cut point exists, it keeps everything (FirstKeptIndex 0).

type FileOperations

type FileOperations struct {
	// Read holds files read but not necessarily modified.
	Read map[string]struct{}
	// Written holds files written by full-file write operations.
	Written map[string]struct{}
	// Edited holds files modified by edit operations.
	Edited map[string]struct{}
}

FileOperations accumulates the file paths a compaction range touched, split by access kind. Mirrors pi's FileOperations.

func NewFileOps

func NewFileOps() FileOperations

NewFileOps returns an empty file-operation accumulator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL