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
- Variables
- func EstimateTokens(msg agentcore.Message) int
- func GenerateSummary(ctx context.Context, stream provider.StreamFn, model provider.Model, ...) (string, error)
- func ShouldCompact(contextTokens, contextWindow int, settings CompactionSettings) bool
- type CompactionDetails
- type CompactionResult
- type CompactionSettings
- type ContextUsageEstimate
- type CutPointResult
- type FileOperations
Constants ¶
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 ¶
var DefaultCompactionSettings = CompactionSettings{ Enabled: true, ReserveTokens: 16384, HeadroomPercent: 10, KeepRecentTokens: 20000, }
DefaultCompactionSettings matches pi's DEFAULT_COMPACTION_SETTINGS (reserve 16k, keep 20k) plus a 10% headroom. The percentage aligns the trigger with what the rest of the industry does — Codex compacts at 90% of the window and Claude Code around 90-95% — and with golder's own low-budget ladder, whose first notice fires at 10% remaining. Without it, a 1M-window model only compacted at 98.4% full, which is later than the point where a single fat turn can still overflow the window.
Functions ¶
func EstimateTokens ¶
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, 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.KeepRecentTokens), 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.
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 ¶
func (r *CompactionResult) Message(now int64) agentcore.CompactionMessage
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) 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.