components

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 19 Imported by: 2 modules, 1 package

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

Package components defines context-guru's component model: the abstract API every context-engineering operation implements, the per-component report used for metrics, the runtime context handed to each component, and the pipeline that stacks them in configured order.

The API is split by lossiness (design D3, after headroom's Rust traits) so reversibility is type-enforced:

  • Reformat: lossless repack (re-encode, skeletonize, add cache_control). No information leaves the wire, so nothing needs stashing.
  • Offload: drops bytes and MUST return a non-optional cache_key proving it stashed the original in the Store — you cannot compile an Offload that silently loses data.

The pipeline is fail-open (any error/panic reverts that component), applies a never-worse guard (a component that grows the request is reverted), and emits one Report per component.

Index

Constants

View Source
const (
	FieldBool    = "bool"
	FieldInt     = "int"
	FieldFloat   = "float"
	FieldEnum    = "enum"
	FieldString  = "string"
	FieldStrings = "strings"
)

Field types.

View Source
const (
	CacheStateAny       = "any"
	CacheStatePreExpiry = "pre_expiry"
)
  • THERE ARE ONLY TWO, AND THAT IS THE RESULT OF A RETRACTION

CacheState values. "any" is spelled explicitly rather than left as "" because it has to be SAYABLE: a component whose default is a restrictive state needs an opt-out an operator can write down, and "" is what the settings form posts for "unset" (see config/form.go normalize).

THERE ARE ONLY TWO, AND THAT IS THE RESULT OF A RETRACTION

This key shipped with four values — `cold` and `pre_expiry_or_cold` alongside these two — on the argument that compaction should wait until invalidating the cached prefix was free. Three things retired that argument, and they are recorded on summarizeDefaultCacheState because that is where the default lived. In short: the downside it avoided was measured at **−$0.84 across the whole corpus**, the payback for firing on a WARM cache is 2-3 turns, and the two-turn commission shape means a cold-gated component pays the first full rewrite anyway.

So there is exactly one question left worth asking about the cache, and it is not "is invalidation free" but "is there a live prefix for the summarizing CALL to hit". Only a component whose model call reuses the conversation's own prefix has that question, which is why `pre_expiry` survives while the two cold states do not.

View Source
const DefaultPreExpiry = time.Minute

DefaultPreExpiry is the pre-expiry window's width when none is configured. One minute, which is this codebase's own clock-uncertainty margin for cache expiry (see apply.cacheIsCold) — chosen because it is the margin already trusted elsewhere, not because it was measured.

Variables

CacheStates is the permitted set, in display order — the Options for the settings form and the set a constructor validates against.

View Source
var ErrCoordsShifted = errCoordsShifted{}

ErrCoordsShifted is what a caller should treat an attempted PrefixAsk as having returned when an earlier component in the pipeline changed the MESSAGE COUNT, so the span the caller wanted to verify against the host's stash cannot be located at all: rawSpanForHash reports !ok and there is no slice of either coordinate system safe to compare. Kept apart from ErrStalePrefix for the same reason the two have different counters: the stash itself can be perfectly current here — the pipeline geometry moved, not the data — and on a `high` or `xhigh` pipeline, where `summarize` runs before the later guards and compacts, this is the expected decline on every turn rather than a defect in the stash.

View Source
var ErrNoPrefix = errNoPrefix{}

ErrNoPrefix is what Ask returns on the FIRST turn of a session: nothing has been forwarded yet, so there is no cached prefix to append to.

Declared here rather than in the host so a component can tell it apart from a transport failure without string matching. The distinction is worth a sentinel because the two mean opposite things to an operator: "there was nothing to read yet", which every session does once and which needs no attention, against "the read failed", which does.

View Source
var ErrStalePrefix = errStalePrefix{}

ErrStalePrefix is what a caller should treat an attempted PrefixAsk as having returned when it checks PrefixCoverage.CoversSpan itself and finds the stash does not (or no longer) cover the span it is about to claim as summarized — see cache_aware_summarizer's own call closure for the PrefixAsk path, which checks CoversSpan immediately before calling Ask and substitutes this for the call entirely rather than paying for an answer it would then have to discard. Declared alongside ErrNoPrefix and distinct from it for the same reason the two have different counters: one means "nothing stashed yet" (every session's first turn, routine), the other means "something IS stashed and it is not enough of the right thing" (caught before paying for it).

Functions

func AllFields added in v0.1.1

func AllFields() map[string][]Field

AllFields returns every registered component's declared fields.

func ConfigProto added in v0.1.1

func ConfigProto(name string) (any, bool)

ConfigProto returns the zero-value config struct a component declared with its fields. For the parity test; nothing in the run path needs it.

func Decode added in v0.1.1

func Decode(raw []byte, dst any) error

Decode unmarshals a component's raw config block STRICTLY: an unknown key is an error rather than silence.

Non-strict was the default and it made the settings form untrustworthy in the one way that matters — `min_tokns: 5000` on any component parsed fine, changed nothing, and reported nothing. config.LoadBytes has rejected typos at the top level since day one; per-component blocks are where the numbers that cost money live.

func Names

func Names() []string

Names lists every registered component name, sorted.

func Register

func Register(name string, c Constructor)

Register makes a component available by name. Called from each component's init(); double-registration or an empty name panics at boot (the database/sql pattern used elsewhere too).

func RegisterFields added in v0.1.1

func RegisterFields(name string, config any, f []Field)

RegisterFields declares a component's configurable keys, from the same init() that registers the component. config is a ZERO VALUE of the component's config struct: the anti-drift test reflects over its yaml tags and fails when the declared keys and the struct's keys disagree, which is the only thing that catches "a component gained a knob and nobody told the form".

func SpanHash added in v0.5.0

func SpanHash(msgs []schemas.ChatMessage) string

SpanHash is a stable content hash of a normalized message span, shared by every caller that needs to tell whether two slices of a transcript are byte-for-byte the same conversation. Exported so a PrefixCoverage implementation living outside this package (the host's own stash) can compute the identical hash a components/offload caller computes over its own span, without either package importing the other.

Hashes each message with its per-block cache_control stripped first (see stripCacheControl): cache_control marks WHERE a client wants the provider's prompt cache to break, not anything the model reads, and a client that moves the marker to a different message every turn (Claude Code does, to keep it on the last message) must not change this hash — otherwise SpanHash reports two slices of the identical conversation as different spans purely because the cache breakpoint moved, which is exactly the false mismatch that sent cache_aware_summarizer's stale-prefix guard into declining every commission at small keep_last_turns values (PR #402 re-review).

Types

type Budgeter added in v0.1.1

type Budgeter interface {
	WithMaxTokens(n int) Model
}

Budgeter is an optional interface on a Model: the same endpoint, the same credential and the same model id, with a larger REPLY budget.

It exists because a truncated reply is the worst outcome available — full price, zero result — and it is indistinguishable from a model declining to act. MEASURED (`659e7a6`): the batched adjudication arm had 24 of 34 replies unparseable, and the cause was the client's default output budget, not the prompt. A verdict array over a dozen items, each carrying an obligation label and a verbatim quote, is simply long; a request model running adaptive thinking spends part of the budget before emitting any text at all. The array was cut mid-flight, the parse failed, and the caller changed nothing — misread as "the model declined" for three iterations.

Why an interface rather than raising cheapmodel.DefaultMaxTokens: the budget a caller needs is a property of what it ASKS FOR, not of the endpoint. A one-tool-output compaction reply and a twelve-verdict array are different lengths, and raising the shared default would move both.

Output tokens bill as generated, not as budgeted, so a raised ceiling costs nothing until used. Optional, and callers must fall back to the client as-is: a Model implementation that does not support it still works, it just keeps its own budget.

type CachePhase added in v0.2.0

type CachePhase int

CachePhase names where a request sits in the life of the prompt-cache entry its prefix populated. It exists because two components now need the same fact and deriving it twice is how the cold decision and the dashboard came to disagree once already (see ttlTier in apply): one fact, one reader.

THE PHASE THAT MATTERS IS PreExpiry, AND IT IS THE RESOLUTION OF A CONTRADICTION. A component that both ASKS the provider something over the cached transcript and REWRITES deep history wants opposite cache states:

the ASK needs a WARM cache — a prefix ask reads an entry that must still exist, or the call
pays fresh for the whole transcript, which is the cost the design exists to avoid;
the REWRITE wants a COLD cache — rewriting deep history invalidates a live prefix and forces
a cache-write of the whole suffix at 1.25x fresh.

Both are cheap in the window where the entry still exists but has little life left: the ask still reads it, and what the rewrite invalidates is nearly worthless.

THE LIFETIME'S PROVENANCE MATTERS. Anthropic's explicit cache tier provides an expiry for apply's cold decision. GPT-5.6+ instead guarantees at least 30 minutes after the last write or reuse and may retain the entry longer: before that boundary it is Warm, but afterward it is Unknown. A minimum can prove neither PreExpiry nor Cold. Zero CacheTTLMs means no reliable lifetime was available.

WHAT CALLERS DO WITH Unknown IS THEIR POLICY, NOT THIS FUNCTION'S, and the two shipped callers answer it oppositely on purpose. extract_llm_sweep must not fire on Unknown: it would invalidate live prefixes on exactly the deployments whose TTL could not be read. A size-gated compactor must fire on Unknown, because Unknown is not rare or exotic: CacheTTLMs is zero whenever the cache-aware path is off entirely (`cache_mode: off`, a bypassed turn) or the provider has an unknown lifetime, and declining there would disable the component on those deployments.

UNKNOWN DOES NOT IMPLY THERE IS NO LIVE PREFIX, and this comment used to claim it did — that "on those deployments MaxCachedIdx stays -1 so every offloader is already permitted to rewrite deep history". The implication is false, and a live run reached the gap: a request can carry MaxCachedIdx >= 0 with no readable TTL, in which case there IS a cached prefix and Unknown means only that we cannot say how much life is left in it. Two reachable shapes —

  • apply's legacy no-Tracker path (every library consumer of BodyFull/BodyOpts) sets MaxCachedIdx from the store and never sets CacheTTLMs at all;
  • `cache_mode: on` against a provider whose TTL this repo does not derive.

A third, the same-millisecond concurrent turn, was the one observed live; that one is now fixed at its root by making IdleMs distinguish zero from unknown. The remaining two are answered by Trigger.CacheAllows, which refuses Unknown when MaxCachedIdx says a prefix exists.

const (
	// CachePhaseUnknown means the lifetime or idle clock is not reliable enough
	// to classify a cached prefix — not that there isn't one.
	CachePhaseUnknown CachePhase = iota
	// CachePhaseWarm means the entry is believed live with meaningful lifetime left.
	CachePhaseWarm
	// CachePhasePreExpiry means the entry is believed live but within the caller's window of
	// expiring, so invalidating it costs little.
	CachePhasePreExpiry
	// CachePhaseCold means the entry is believed gone, so there is no prefix to disturb.
	CachePhaseCold
)

func (CachePhase) String added in v0.2.0

func (p CachePhase) String() string

String names the phase, so a test failure and a log line say which one rather than an int.

type Component

type Component interface {
	Name() string
	Enabled(*Ctx) bool
}

Component is the common surface: identity + a per-request enable check.

func New

func New(name string, raw []byte) (Component, error)

New builds a single component by name with its raw config block.

type Configurable

type Configurable interface {
	Configure(raw []byte) error
}

Configurable receives its typed config block from the registry/loader.

type Constructor

type Constructor func(raw []byte) (Component, error)

Constructor builds a component instance. It receives the raw config block for its name (may be nil), so a component can be configured purely from YAML with no core change. Returning an error aborts pipeline construction.

type Ctx

type Ctx struct {
	Ctx     context.Context
	Session string
	// Thread is the thread of the session this request belongs to (main agent, a subagent, a
	// fork): "" for the primary thread. A component that keeps per-CONVERSATION state between
	// requests, outside the Store's session keys, keys it by thread.Key(Session, Thread) — each
	// thread is its own conversation with its own provider cache entry. See internal/thread.
	Thread string
	// ThreadInherits says this request starts a NEW thread that continues another thread's prefix
	// (a Claude Code side request, a fork), and ThreadParent names that thread: "" with
	// ThreadInherits true means the parent is the primary (main) thread. internal/thread sets it
	// only on the FIRST request of a new thread, the one request whose own per-thread state is
	// still empty, so a component may fall back to thread.Key(Session, ThreadParent) there and
	// nowhere else. apply's cached boundary does exactly that (modes.Tracker.TurnFrom).
	ThreadParent   string
	ThreadInherits bool
	// DeclaresTools says the request declares tools: the metadata internal/thread uses to tell the
	// main agent (and a fork of it) from a tool-less side request (a title, a quota check, an
	// end-of-turn note). cache_aware_summarizer and summarize use it to decide whether a new
	// inheriting thread keeps a copy of its parent's checkpoint (see offload.adoptParentCheckpoint).
	DeclaresTools bool
	Store         store.Store
	// DisallowCountChange prevents transcript-restructuring components from
	// running when a host cannot safely write their output back to its wire shape.
	DisallowCountChange bool
	// Restored maps the content key (extract.ContentKey) of each expanded original that the host
	// re-inserts this turn as a separate message at a fixed anchor, to that original's marker id
	// (`expand.fixed_restore`, #407). For those, kept-verbatim no longer applies: the compacted
	// bytes at the original position are replayed exactly as before the expand, so nothing inside
	// the cached prefix changes, and the model reads the content from the inserted copy instead.
	// Nil (the default, and whenever the anchor cannot be honoured) is today's behaviour.
	Restored map[string]string
	// CacheAnchorToolID is set by a component that SPLICED the transcript (cache_aware_summarizer,
	// #723): the tool_call_id of the last tool_result it kept verbatim after the summary. The host's
	// count-changing rebuild writes one cache_control breakpoint onto that block in the raw body,
	// when the provider's 4-breakpoint cap leaves room. Without it, the history after a splice is
	// text turns only, and a provider entry that ends at a text turn is never read by the next
	// request, so every turn after a splice re-writes the whole kept history. "" = no anchor.
	CacheAnchorToolID string
	// NoCacheBreakpoint is true when the backend takes no explicit cache breakpoint (OpenAI and
	// Gemini shaped wires cache an implicit prefix). The host cannot write the CacheAnchorToolID
	// mark there, so a summary span has no reason to stop before the last tool exchange (#730).
	// False (the default) keeps the retreat.
	NoCacheBreakpoint bool
	// AllowSummarySpan is supplied by a wire adapter when only some normalized
	// spans can be rebuilt without dropping opaque provider state. Nil means the
	// ordinary Chat/Anthropic adapter has no extra restriction.
	AllowSummarySpan func(start, end int) bool
	// SummaryStashPayload lets an adapter preserve exact provider wire items in
	// the expand stash when normalized ChatMessages omit opaque fields. Nil uses
	// the ordinary normalized-message JSON payload.
	SummaryStashPayload func(start, end int, span []schemas.ChatMessage) ([]byte, error)
	Model               ModelSpec
	// Bypass short-circuits the whole pipeline (x-context-guru-bypass header).
	Bypass bool
	// CtxWindow is the model's max input tokens for THIS request, resolved by the
	// host (dynamically, via internal/modelinfo). 0 = unknown, in which case
	// fraction-based Trigger thresholds are ignored and only absolutes apply. Stored
	// as a resolved int so Trigger stays a pure, network-free, unit-testable function.
	CtxWindow int
	// CtxWindowExact says CtxWindow is a figure published for THIS model, not a family
	// guess. It matters because ok=true from the resolver is not the same as right: the
	// substring table of last resort answers 200,000 for every Opus, and LiteLLM publishes
	// those at 1,000,000. A fraction resolved against the guess fires five times too early.
	//
	// A per-item FLOOR may act on a guess — too small a window merely raises the floor. A
	// decision about how FULL the context is may not, and Trigger declines rather than
	// guessing (see Trigger.CacheAllows). Zero value is false, so a Ctx built without it
	// fails closed for the fraction and unchanged for everything else.
	CtxWindowExact bool
	// PrevBilledInput is the provider's own input-token count for this session's PREVIOUS turn
	// — fresh input + cache reads + cache writes — or 0 when this session has no earlier
	// response to read (its first turn, a lost store key, or a host that does not record it).
	//
	// It is the ONLY figure on this Ctx that can be compared against CtxWindow, and that is
	// why it exists. schema.MessagesTokens counts message TEXT only: no system prompt, no tool
	// declarations, no JSON envelope. A context window is stated in the units the provider
	// bills, which include all of those. Measured on this deployment's uncompacted traffic the
	// two differ by a median 3.38x (p25 2.43, p90 6.80 — dash/overview.go's
	// EstimatorDivergence, computed over requests where nothing was compacted, so the two are
	// describing the same prompt). Testing `MessagesTokens >= 0.9 * window` therefore waits for
	// roughly three times a 1M window's worth of transcript and never becomes true: the
	// provider rejects the request, or the client compacts, long before the gate opens. That is
	// not a rounding error, it is a gate that silently never fires.
	//
	// One turn stale by construction — it is written from a response and read on the next
	// request. Not an approximation to apologize for: a transcript only grows, so the previous
	// turn is a sound lower bound on this one, and a size gate that opens one turn late is the
	// harmless direction. A component must treat 0 as UNKNOWN and decline a fill decision, the
	// same rule CtxWindowExact carries, for the same reason.
	PrevBilledInput int
	// CacheAware is true when this request goes to a prompt-caching backend and the
	// pipeline should avoid mutating already-cached content. When true, supersession/
	// age-based offloaders (failed_run, mask, collapse) must restrict their
	// mutations to the uncached tail (message index > MaxCachedIdx) so they don't
	// invalidate the provider's KV cache at a full→collapsed transition. Deterministic
	// tail/in-place offloaders (dedup, cmdfilter, extract) are already byte-stable on
	// the unchanged prefix and ignore this. False = legacy compact-everything.
	CacheAware bool
	// ColdCache is true when this session has been idle longer than the provider's prompt
	// cache TTL, so the cached prefix CacheAware exists to protect is certainly gone.
	//
	// It is INFORMATION, not a global lifting of the tail gate: the gate stays where it is
	// and each component opts in. mask, failed_run and collapse opt in BY DEFAULT since
	// 2026-08 (their replacements are pure functions of (content, config), which is what
	// makes a decision taken at depth re-derivable on every later warm turn); readlifecycle
	// and skeleton do not, because theirs are not. `cold_cache: false` restores the gate per
	// component. See coldCacheDefault in components/offload for the measurement that flipped
	// it — 90.8% of the context was being frozen on turns whose cache had already expired.
	//
	// False means "warm, or unknown". A new session, an evicted tracker entry and the first
	// turn after a restart all read false: acting on a fabricated idle time would invalidate
	// a live cache, which costs a full cache-write of the suffix at 1.25x the fresh rate.
	ColdCache bool
	// ModelName is the id of the model this request targets, so a component that reuses it
	// (model.source: incoming, the default for the LLM components) can say WHICH model it
	// called instead of recording an empty string.
	ModelName string
	// SelfRates are the per-token rates for the model a component would call itself — the
	// incoming model's, since that is what `source: incoming` uses. Zero when unknown.
	SelfRates TokenRates
	// RatesFor resolves the operator's rate card for ANY model id, not just the incoming
	// one. nil, or a zero return, means "not on the card" and the component must fall back.
	//
	// It exists because a component that names its own cheap model (`model.model:
	// claude-haiku-4-5`) could not price it: SelfRates covers the request's model and nothing
	// reached the host's price table, so the economic gate spent against the built-in haiku
	// LIST rates while the dashboard priced the same call from the operator's card. MEASURED
	// on this deployment: `cheap_model_price_unconfigured` was recorded on 1,770 of 1,770
	// requests, so every allow/suppress decision in the window was made against the wrong
	// card, and the same 93 calls were booked at $0.7946 in extraction_calls.cost_usd against
	// $0.6039 in requests.cg_llm_cost_usd — 32% apart, for one set of calls. Two numbers for
	// one invoice is not a rounding difference; it is a component and a dashboard disagreeing
	// about whether a configuration pays.
	RatesFor func(model string) TokenRates
	// IdleMs is how long this session was idle before this request, in milliseconds. Carried
	// alongside ColdCache so a component can demand MORE idle time than the provider TTL implies,
	// and so the figure can be reported rather than re-derived.
	//
	// NEGATIVE MEANS UNKNOWN — there is no previous turn on record, or the clock went backwards.
	// ZERO MEANS ZERO IDLE, which is a positive fact about the warmest possible cache.
	//
	// The distinction is load-bearing and it was missing. IdleMs used to be 0 for both, so
	// CacheRemaining reported "cannot tell" for a request that arrived in the same millisecond as
	// the previous one — and CachePhase turned that into Unknown, which the compaction gate
	// PERMITS. A live run reached it with nothing exotic: four concurrent requests on one session,
	// which any agent issuing parallel sub-requests does routinely, produced 13 of 26 turns
	// classified Unknown over an 8-message live cached prefix. A turn with genuinely zero idle is
	// the warmest cache there can be and must classify as Warm, not as "no information".
	//
	// Writers must therefore initialise this to -1, not 0, when they have no previous timestamp.
	IdleMs int64
	// CompactionPoint is C: the provider-billed input at which the CONVERSATION'S OWN compaction
	// mechanism acts — the largest prompt that mechanism allows before it rewrites the transcript.
	// 0 = unknown, and a caller must then fall back to CtxWindow.
	//
	// IT IS THE DENOMINATOR THE FILL FRACTION BELONGS OVER, not the model window, and that is the
	// argument for this whole component: compacting just before the conversation's own mechanism
	// would have acted captures the saving of a large prefix going cold and costs no accuracy that
	// was not already going to be lost — because a compaction was going to happen there anyway.
	// Comparing against the window is only correct when C equals the window.
	//
	// Measured in the same units as PrevBilledInput and CtxWindow: provider-billed input. Never the
	// client's own token count, which for one real request read ~168,000 where the provider billed
	// 199,184 — the same event in a different ruler. See internal/compactionpoint.
	CompactionPoint int
	// CompactionPointSource says where CompactionPoint came from: observed on real traffic, assumed
	// from reported behaviour, or fallen back to the window. Carried so a decision made on a guess
	// is distinguishable from one made on a measurement — the discipline CtxWindowExact keeps.
	CompactionPointSource string
	// MaxCachedIdx is the highest req.Input index considered already committed to the
	// provider cache (the messages present on the previous turn of this session).
	// -1 = unknown/first turn/cache off ⇒ no tail restriction. Only meaningful when
	// CacheAware is true.
	MaxCachedIdx int
	// RawInput is the normalized message array AS APPLY HANDED IT TO THE PIPELINE, before any
	// component — including the first one configured — ran. apply sets it once, from a shallow
	// copy taken before Pipeline.Run starts, so a later component's in-place rewrite (SetMessageText
	// replaces the Content pointer; it never mutates a message this slice still points at) cannot
	// change what RawInput reports.
	//
	// It exists for a stale-prefix guard that must hash the SAME span the host's prefix stash
	// recorded (proxy's sentStash.preBody, via components.PrefixCoverage.CoversSpan). That stash is
	// keyed on apply's own pre-pipeline body, in RAW coordinates — MaxCachedIdx is in those same
	// coordinates. req.Input, read at a component's OWN position in the pipeline, is for every
	// component but the first already the OUTPUT of every earlier one: a prior Reformat/Offload
	// (textclean, format, dedup, cmdfilter, …) can rewrite a message inside the cached span on
	// every turn, so hashing req.Input there and comparing against the raw stash disagrees even
	// though the stash is exactly right (PR #431 round 1 review). Hash RawInput[:n], never
	// req.Input[:n], for any guard whose other side is a pre-pipeline stash.
	//
	// apply sets it on every route (Messages and Responses). It is nil only for a Ctx built
	// directly, as most component unit tests do. A guard then falls back to req.Input
	// (offload.rawSpanForHash), which is correct only when no component runs before the guarded
	// one. So every host path that builds a Ctx for a real request must set this field.
	//
	// A component BEFORE the guarded one that changes the MESSAGE COUNT (summarize, a
	// count-changing extract path) shifts req.Input's indices out of RawInput's coordinates even
	// though both are non-nil; a guard must therefore also decline whenever len(req.Input) at its
	// own position differs from len(RawInput), rather than hash the wrong span under a matching
	// nil-ness check alone.
	RawInput []schemas.ChatMessage
	// WireGroup names, for each req.Input index, the ORIGINAL wire message it came from (#457).
	// On Anthropic traffic several normalized messages can share one wire message — a
	// tool_result's synthetic role=tool message and a sibling text block beside it (mid-turn
	// user text, a system reminder, a task/teammate notification) — and a span boundary that
	// landed between them would ask the count-changing rebuild to keep half of one wire message
	// and summarize the other half, which it cannot represent. summarizeSpan's groups parameter
	// uses this to push a boundary candidate out to the nearest WIRE-message edge instead.
	//
	// Nil (OpenAI-shaped traffic, and a Ctx built directly as most component unit tests do) means
	// every normalized message already is its own wire message, so no boundary can ever split
	// one — summarizeSpan treats a nil/length-mismatched groups slice as "nothing to align".
	// apply sets it in the SAME coordinates as RawInput (pre-pipeline), for the same reason: a
	// value computed against req.Input at a later component's own position would already be
	// shifted by any earlier count-changing component.
	WireGroup []int
	// PrefixAsk, when non-nil, lets a component put a question to the request's own model with the
	// previous turn's SENT body as the prefix, so the provider reads its prompt cache instead of
	// being re-sent the transcript. See PrefixAsker for why that body and not the incoming one.
	//
	// HOST CONTRACT: a host that sets this must stash each request's forwarded body when its
	// upstream answers, then call offload.ResolveDeferredCacheAwareSummary(session, thread) when
	// the request ends. cache_aware_summarizer holds a prefix-ask commission until then, so it
	// reads that request's body and not the previous one (#722).
	PrefixAsk PrefixAsker
	// CanKeepAlive, when non-nil, reports whether the host's keep-alive can ping THIS request's thread:
	// the policy is on, the kill switch is off, an audit sink exists. A component that prepares
	// something for a ping (extract_llm_sweep's question) registers only when it returns true, so a
	// thread that will never be pinged keeps nothing for it. nil => false: a host with no keep-alive
	// leaves it unset and such a component keeps nothing.
	CanKeepAlive func() bool
	// CacheTTLMs is a known cache lifetime in milliseconds: Anthropic's explicit
	// expiry tier or GPT-5.6+'s documented 30-minute minimum. The latter has
	// CacheTTLMinimum set, because OpenAI may retain the entry longer. 0 means unknown.
	//
	// Carried alongside IdleMs and ColdCache so a component can reason about where in the cache's
	// LIFETIME this turn falls, not merely whether the entry is already gone. extract_llm_sweep
	// needs exactly that: a prefix ask must read a cache that still EXISTS, while rewriting deep
	// history wants one that is nearly worthless — which is a window before expiry, not after it.
	CacheTTLMs int64
	// CacheTTLMinimum means CacheTTLMs is a guaranteed minimum, not a known
	// expiry. GPT-5.6+ entries may outlive their default 30-minute guarantee;
	// after that point their phase is Unknown, never Cold by arithmetic alone.
	CacheTTLMinimum bool
	// FilterStats receives cmdfilter's per-filter ledger (which command families pay
	// off, and which output shapes matched nothing). nil = not recording.
	//
	// Read it through Stats(), never directly: in observe mode nothing is forwarded, so
	// recording into an enforced-namespace field would report savings that never happened.
	FilterStats FilterStatsSink
	// ExistingBreakpoints is how many prompt-cache breakpoints the RAW request already
	// carries, counted across `system`, `tools` and `messages` — which is what the
	// provider's cap of four applies to. A component that spends breakpoint slots must
	// budget against this number rather than what it can see in Input, for two reasons
	// measured on real Claude Code traffic: 2 of its 3 breakpoints live in the
	// top-level `system` array, which components never see at all, and the third sits
	// on a `tool_result` block whose mark the host's own normalize step drops. Both
	// were invisible, so the budget came out as 3 free slots when only 1 was free —
	// enough to put 6 on the wire and take a 400 (issue #32). The host fills it from
	// the raw body; 0 means "unknown, fall back to what you can see".
	ExistingBreakpoints int
	// Mode is the operating mode this request runs under. Components that behave
	// differently off the request path read this rather than inferring anything.
	Mode Mode
	// SystemSplit says the host already split a volatile tail out of the top-level
	// `system` array for this request. Only `cachesplit` reads it, and only to report
	// itself honestly: the split is body-level work that happens in the host (components
	// never see the system array), so without this the marker component reported Skipped
	// on the very requests where the mechanism had just run — and everything downstream
	// derives "did it do anything" from that.
	SystemSplit bool
	// ToolSchema says the host already stripped JSON-Schema annotation keywords from
	// the top-level `tools` array for this request. Only `toolschema` reads it, and
	// only to report itself honestly — same arrangement, same reason, as SystemSplit.
	ToolSchema bool
	// FilteredDecls is how many tool/MCP declarations the host dropped from `tools` on
	// this request under the account's opt-in removal list. Set for the same reason
	// ToolSchema is: `tools` is a top-level field no component can see, so toolfilter
	// would otherwise report itself as skipped on every request where it just acted.
	FilteredDecls int
}

Ctx is the per-request runtime handed to every component.

func (*Ctx) CachePhase added in v0.2.0

func (c *Ctx) CachePhase(preExpiry time.Duration) CachePhase

CachePhase classifies this request against preExpiry, the width of the window before the entry's believed expiry that the caller considers cheap to invalidate.

ColdCache is checked FIRST: it is apply's own verdict over the same timestamps, and a turn apply has called cold is Cold here even if the arithmetic below would have said otherwise.

It is NOT a safety check, and an earlier version of this comment implied it was ("one cheap agreement check costs nothing next to a wrongly invalidated prefix"). Checking ColdCache first can only make this classifier MORE willing to say cold, never less, so it cannot protect a live prefix. The reachable disagreement was the opposite one — the arithmetic below calling an entry cold while apply called it warm — and that was answered by a stricter cold test carrying a clock-skew margin, not by this line. That test went away with the cold-gated cache states (see the note above the phase constants); apply's ColdCache, checked here, is now the only margin-bearing verdict.

func (*Ctx) CacheRemaining added in v0.2.0

func (c *Ctx) CacheRemaining() (time.Duration, bool)

CacheRemaining is the known expiry or guaranteed minimum minus this session's idle time. ok=false means unknown, and a caller must not treat that as zero. For a minimum, zero is only the end of the guarantee, not proof of expiry.

Exported separately from CachePhase because the arithmetic is one subtraction over two Ctx fields, and anything else that wants it (a dashboard row, a keep-alive deadline) must read it here rather than re-derive a TTL of its own.

func (*Ctx) FillDenominator added in v0.2.0

func (c *Ctx) FillDenominator() int

FillDenominator is what a fill FRACTION is a fraction OF: C, the point at which the conversation's own compaction mechanism acts, falling back to the model's context window when C is unknown.

It exists as one function so that "90% full" cannot come to mean two different things in two callers — the failure this repo has had with cache TTLs and with token rulers, twice each.

THE FALLBACK IS THE WINDOW AND THAT IS CORRECT FOR TWO OF THE FOUR CASES: a deployment where nothing compacts (a raw API client) genuinely has C == W, because the conversation grows until the provider rejects it. It is a guess for the case where a client compacts and we have not observed it — and those two are not currently distinguishable, which is why CompactionPointSource is carried rather than the number alone.

A GUESSED C IS STILL ACTED ON, deliberately, where a guessed WINDOW is not (see FracResolvable). The asymmetry is about the direction of harm. A wrong window fires the gate at the wrong absolute size against a live cache: five times too early on the Opus family, invalidating prefixes that had most of their life left. A wrong C only moves the moment within the window — and the cache-state conjunct still has to agree, so the turn is one where the write was due anyway. Too-high a C means the component never fires (no harm, no benefit); too-low means it compacts a smaller prefix at a moment that was already cheap. Refusing to act on an assumed C would disable the component on every model whose client behaviour has not been measured, which today is all of them but haiku.

func (*Ctx) Stats added in v0.1.1

func (c *Ctx) Stats() FilterStatsSink

Stats returns the per-filter ledger sink, or nil in observe mode.

Observe computes what compaction WOULD have done and forwards the request untouched, so every enforced-namespace metric must stay zero: a figure that cannot be told apart from a real saving is worse than no figure, because it silently inflates the product's own headline. The savings totals are already namespaced (potential_* / projected_*), but the filter ledger is not — an observe-only run was reporting real-looking `cmdfilter_families` and `cmdfilter_filters` entries with no mode label and no hypothetical counterpart.

Gating here rather than at the call site is deliberate. A component author reaching for c.FilterStats has no reason to think about modes, and the next sink added to Ctx would reproduce the bug; an accessor makes the safe path the only convenient one.

Two enforced fields are deliberately NOT suppressed in observe mode, because they are real rather than hypothetical: cg_added_ms_avg (a true measurement of the enforced path, which correctly reads ~0) and context-guru's own model spend (observe measures off-path, and that costs real money). Those are labelled instead — see metrics.Snapshot's observe notices.

func (*Ctx) TailOnly

func (c *Ctx) TailOnly(i int) bool

TailOnly reports whether a supersession/age-based offloader may mutate the message at index i without risking the provider's cached prefix. When cache-awareness is off or the boundary is unknown, every index is fair game (legacy behavior).

func (*Ctx) TailOnlyCold added in v0.1.1

func (c *Ctx) TailOnlyCold(i int, optIn bool) bool

TailOnlyCold is TailOnly with the depth restriction lifted on a turn whose prompt cache is provably gone (ColdCache), for a component that opted in.

The opt-in is per component. It defaults ON for the three whose replacement is a pure function of (content, config) — mask, failed_run, collapse — and OFF for the two whose is not. When ColdCache is right there is no prefix to disturb, so acting at depth is free by construction; when it is WRONG the component flips content the provider is still holding and forces a cache-write of the whole suffix at 1.25x the fresh rate, where a missed cold turn only forgoes a saving. That asymmetry is why the DETECTION is conservative rather than why the default is off: see cacheIsCold, sessionTTL and the alias clock in apply/apply.go, and docs/design.md.

Only safe for a component whose replacement is a pure function of (content, config) — the same property repairLostFreeze requires — because the decision it makes at depth is frozen and replayed on every later (warm) turn.

type Emitter

type Emitter interface {
	Component(Report)
	Run(RunReport)
}

Emitter receives one Report per component and one RunReport per request. Defined here (not in metrics) so the pipeline has no dependency on any concrete telemetry backend; metrics provides the implementations.

type Field added in v0.1.1

type Field struct {
	// Key is the DOTTED path of the key inside the component's block —
	// `cold_cache.min_tokens`, `model.source` — so a nested block needs no nesting here.
	Key string `json:"key"`
	// Type is one of the Field* constants below. It tells the form what control to draw
	// and the server what a posted value must decode to.
	Type string `json:"type"`
	// Default is what an ABSENT key means to the component, i.e. what the form should show
	// greyed as the fallback. It is NOT the recommended prefill — that is a policy layer
	// (see config.RecommendedExtractLLM), and conflating the two is how a form ends up
	// writing its own opinion over an operator's deliberate value. nil = the type's zero.
	Default any `json:"default,omitempty"`
	// Options is the permitted set for Type == FieldEnum, in display order.
	Options []string `json:"options,omitempty"`
	// Hint is one line of prose for the field, taken from the doc comment already written
	// on the config struct.
	Hint string `json:"hint,omitempty"`
	// Secret marks a credential: the form must never echo a stored value back, and the
	// control is write-only.
	Secret bool `json:"secret,omitempty"`
	// Min is the smallest accepted number. It carries real semantics: 0 on a CAP means
	// "unlimited" and is a legitimate choice, while a size threshold with Min 1 rejects 0
	// because 0 there is not a setting, it is a removed brake.
	Min int `json:"min,omitempty"`
	// Withdrawn maps a value this field ONCE accepted to the guidance an operator who wrote it
	// should be given. Not part of Options, so the form never offers one; consulted before the
	// generic enum error so the refusal names a replacement.
	//
	// IT EXISTS BECAUSE THE GENERIC MESSAGE IS WRONG FOR THIS CASE. "not one of [any pre_expiry]"
	// is what you tell someone who made a typo. Someone whose config worked yesterday made no
	// typo — they wrote a value that was documented and defaulted to, and then retired on
	// evidence — so they need to know which surviving value matches what they were buying. The
	// alternative, aliasing the old value onto a new one, changes when a component fires without
	// saying so, which is the failure mode this mechanism was added to stop repeating.
	//
	// Not serialized: the form has no control to draw for a value it must never offer, and
	// shipping the list to the browser would invite a client to "helpfully" migrate it.
	Withdrawn map[string]string `json:"-"`
}

Field describes ONE configurable key of one component, for the settings form. It is form metadata only: nothing in the run path reads it, and a component's constructor behaves identically whether or not its fields are declared.

It exists because the settings page used to hand-list the keys it knew about, in Go and again in JavaScript, and nothing could notice an omission: the form exposed 18 keys of ~100, one component of fifteen, and the keys it did expose had already drifted from the values the engine accepts (a stored `strategy: deterministic` was not recognised and got REWRITTEN to `code`, silently turning an LLM-free configuration into one that makes model calls). Declaring the keys beside the config struct they describe, and deriving the form from that, makes the omission a compile-or-test failure instead of a silent one.

func Fields added in v0.1.1

func Fields(name string) []Field

Fields returns a component's declared fields, in declaration order.

func TriggerFields added in v0.1.1

func TriggerFields(prefix string) []Field

TriggerFields declares Trigger's keys for the settings form, under prefix (normally "trigger"). It lives beside the struct so a new threshold cannot be added without the form learning about it — the fields parity test compares these keys against the struct's yaml tags. TriggerFields declares every key a Trigger accepts, for every component that embeds one.

It is deliberately NOT split per component, and an attempt to split it is what established that. `extract` and `extract_llm` consult neither CacheAllows nor CachePhase, so their `cache_state` control did nothing — and the obvious fix, hiding the key from their form, breaks this repo's own contract: TestEveryComponentDeclaresExactlyItsConfigurableKeys requires that a key the config STRUCT accepts is declared, because a key that is accepted but undeclarable is settable in YAML and invisible in the UI. Hiding the control would have made the inert key harder to see, not gone.

So the inert key is refused instead — see Trigger.Validate's consultsCache argument — which means it can never be silently ignored, and an operator who sets it is told which component does honour it. The form still offers the control; its default (`any`) is the no-op, so only a deliberate restriction reaches the error.

type FilterStatsSink added in v0.1.1

type FilterStatsSink interface {
	// FilterAct notes one applied filter: its family (builds/tests/iac/pkg/net/...),
	// its name, the content key (so a compaction re-sent verbatim next turn is counted
	// once), and the tokens saved.
	FilterAct(family, filter, contentKey string, saved int)
	// FilterMiss notes a selector that matched no filter — the ledger that says which
	// filter is worth writing next (after rtk's parse_failures table).
	FilterMiss(selector string)
}

FilterStatsSink records cmdfilter's per-filter/per-family ledger. metrics.Aggregator implements it; the pipeline depends only on this interface. Implementations must be safe for concurrent use.

type KeepAliveEmitter added in v0.4.1

type KeepAliveEmitter interface {
	KeepAlivePing(KeepAliveReport)
}

KeepAliveEmitter is an OPTIONAL capability an Emitter implementation may add. Most Emitter implementations don't care about keep-alive specifically, so this is a separate interface rather than a new required method on Emitter — adding a required method would break every existing implementer the next time this type is embedded or asserted against. The keeper type-asserts for this and no-ops if absent, the same pattern used elsewhere in this codebase for optional capabilities (e.g. store.Stasher, FilterStatsSink above).

It exists so the host-level keep-alive mechanism — which cannot be a Component (see its package comment) and therefore never runs through Pipeline.Run — can still report through whatever Emitter the host already configured, instead of calling a concrete sink (dash) directly from the keeper itself. That direct call was the one piece of host-specific machinery wired into the keeper, and it is what blocked exporting the keeper as a host-agnostic package (docs/proposals/cortex-integration.md §5; issue #382).

type KeepAliveReport added in v0.4.1

type KeepAliveReport struct {
	Tenant, Session, Model, Provider, Route string
	// Thread is the session thread the ping kept warm ("" = the primary thread), so a ping row
	// says WHICH cache entry it protected. See internal/thread.
	Thread                        string
	Pings                         int
	CacheRead, CacheWrite, Output int64
	CostUSD                       float64
	Status                        int
	DurationMs                    float64
	// TS is when this ping was recorded (the keeper's own clock, which production reads from
	// time.Now but a replay/test may inject), in epoch milliseconds — not derivable from
	// anything else here, and a sink that timestamps its own row from wall-clock-at-receipt
	// would disagree with a keeper running on an injected clock.
	TS int64
	// Agent, Preset, StopReason and Strategy are copied verbatim from the kaEntry that
	// established this ping — see keepalive.go's record1 — so a sink that mirrors the
	// pre-existing dash.Event can reproduce every column it wrote before this type existed.
	// Strategy is the manager-controlled keep-alive strategy id that resolved this ping's
	// policy, "" when none did (account config or a session override supplied it instead).
	Agent, Preset, StopReason, Strategy string
	// FreshInput and CacheWrite1h are the ping's own usage tiers beyond CacheRead/CacheWrite/
	// Output, carried for the same reason.
	FreshInput, CacheWrite1h int64
	// MaxTokens is what the ping itself asked for (see keepalive.go's pingOutputBudget), so a
	// sink can record what was requested rather than reading as a request with no output
	// budget at all.
	MaxTokens int
	// Manual marks a ping the USER asked for (keepalive.Keeper.PingNow), not one the keeper
	// scheduled; Strategy is then "manual". RewriteUSD is the cache write it avoided, 0 when it
	// read nothing. A sink keeps both off every strategy's ledger.
	Manual     bool
	RewriteUSD float64
	// SweepAnswerUSD is, when extract_llm_sweep's question stood in for this ping, what the ANSWER cost
	// beyond the read a plain ping would have paid (#404 point 9): the output (thinking included), plus
	// any fresh input or cache write. Booked here once, on the ping row the question replaced, as the
	// summary's call is (#458). Part of CostUSD, not added to it. 0 for every other ping.
	SweepAnswerUSD float64
}

KeepAliveReport is the per-ping result the host-level idle keep-alive mechanism (proxy/keepalive.go) reports — independent of any particular sink. It carries what that mechanism itself knows and prices about one ping: who it was for, what the ping's own usage tiers were, what it cost, and how it went.

Most of this mirrors Report's shape deliberately (tokens by tier, cost, status, duration) because the keep-alive IS a component in every sense except the one that matters for Pipeline.Run: it fires between requests, with nothing on the wire to hook (see keepalive.go's package comment, "Why it is host-level and not a component"). This type lets it still report through the same Emitter a host already has, instead of reaching into a concrete sink directly the way it used to.

Agent, Preset, StopReason, Strategy, FreshInput, CacheWrite1h and MaxTokens go beyond the fields issue #382 sketched. They are here because dropping them would be a real behavior change for the one sink that exists today: cmd/context-guru-proxy's dashEmitter writes a dash.Event carrying all of them (the agent and preset the dashboard groups by, the strategy a manager-controlled policy resolved, the stop reason and output-token budget an operator reads off the row, the usage tiers beyond cache-read/cache-write/output), and dropping any one would silently blank a column on every keep-alive row a dashboarded deployment has always shown. If this drifts from what docs/proposals/cortex-integration.md §5 implies, that doc is the one to correct, not this.

type MessagesModel added in v0.2.0

type MessagesModel interface {
	CompleteMessages(ctx context.Context, system string, msgs []schemas.ChatMessage) (string, error)
}

MessagesModel is an OPTIONAL capability on a Model: a client that can send a full message ARRAY rather than one flattened prompt string. Components detect it by type assertion and must degrade gracefully when a client does not implement it.

IT EXISTS FOR CACHE-REUSE COMPACTION, and the reason is arithmetic. A summarizer that builds a fresh prompt ("summarize this trajectory: {text}") shares no prefix with the conversation it is summarizing, so the call pays full prefill on every token — measured at ~57k prompt tokens per call on a 50-task SWE-bench arm. A summarizer that sends the conversation ITSELF plus a short trailing instruction reuses the prefix the agent's own turn just cached, and pays prefill only on the appended suffix.

That is the shape Anthropic's own caching guidance prescribes for exactly this case: "Fork operations must reuse the parent's exact prefix. Side computations (summarization, compaction, sub-agents) often spin up a separate API call. If the fork rebuilds system / tools / model with any difference, it misses the parent's cache entirely."

system is the parent request's system prompt, passed verbatim so the fork's prefix can match the parent's. "" means send no system block — which is what a component on Anthropic-shaped traffic must do, because the top-level `system` field is not part of the messages array and the pipeline never sees it (see Ctx: there is no System field to read). On that path the shared prefix therefore starts after the system block, and the saving is correspondingly smaller. Measure it; do not assume it.

type Mode added in v0.1.1

type Mode string

Mode is context-guru's operating mode for one request. The host sets it explicitly (proxy Options / config `mode:`); it is NEVER inferred.

ModeSync    — compact inline; the caller waits and the compacted request is sent.
              The default, byte-identical to pre-mode behavior.
ModeObserve — the pipeline runs on a copy whose output is discarded. The agent
              receives the untouched original; results land in a strictly separate
              (hypothetical) metric namespace.

An async mode — deferring compaction off the request path — is designed and implemented on a separate branch (#31/#35), held back because its measured benefit collapsed once the expensive component stopped running on caching backends. Mode is a closed set here so an unknown value fails loudly rather than silently meaning sync.

const (
	ModeSync    Mode = "sync"
	ModeObserve Mode = "observe"
)

The operating modes. See Mode.

func ParseMode added in v0.1.1

func ParseMode(s string) (Mode, error)

ParseMode validates a configured mode string; empty means sync.

type Model

type Model interface {
	Complete(ctx context.Context, prompt string) (string, error)
}

Model is the minimal LLM surface a component may call: one prompt in, text out. internal/cheapmodel's Anthropic and OpenAI clients implement it.

type ModelCall added in v0.1.1

type ModelCall struct {
	Component string
	Model     string
	Strategy  string
	// Aggressiveness is the compaction target asked for, so a level's real effect on this
	// workload can be read off recorded calls instead of inferred.
	Aggressiveness string
	// Cold marks a call made during a cold-cache sweep, whose economics differ by ~12.5x.
	Cold bool
	// Escalated marks a call that fell back to the agent's own model because the transcript
	// did not fit the extraction model's window.
	Escalated       bool
	CandidateTokens int
	SavedTokens     int
	LatencyMs       float64
	// Token usage of the CALL itself, split by tier, and its cost priced with the extraction
	// model's rates rather than the agent's.
	PromptTokens     int64
	CompletionTokens int64
	CacheRead        int64
	CacheWrite       int64
	CostUSD          float64
	Accepted         bool
	// GateReason is what the economic gate concluded, including when it was overridden — the
	// counterfactual an operator needs to see after choosing to override it.
	GateReason string
	// Rejection says why a call produced nothing: no usable reply, a result that was not
	// smaller, or one the acceptance check refused. Empty on success. Without it every
	// failure looked identical, and they have opposite fixes.
	Rejection string
	Summary   string
	Before    string
	After     string
}

ModelCall is one LLM call a component made, with what it cost and what it bought.

It exists because "this component spent money" was previously a single dollar figure per REQUEST, priced at the agent model's rate, with no record of how many calls made it up, which candidate each looked at, whether it was accepted, or what the gate thought. For the one component that can be net-negative, that is the difference between an operator being able to answer "was that worth it?" and having to guess.

Before/After hold the candidate's text either side of the call. They are transcript content, so whether they are ever PERSISTED is decided downstream by the same per-account capture consent that governs the diff view — this struct only carries them.

type ModelSpec

type ModelSpec struct {
	Incoming Model
	Static   Model
}

ModelSpec carries the LLM clients a NeedsModel component may use, resolved per request by the host adapter. Incoming is the proxied request's own model + credentials (nil when unavailable, e.g. a sidecar-plugin host); Static is a configured cheap model (nil when none is configured). A component selects one by its own `model.source` config via For.

func (ModelSpec) For

func (m ModelSpec) For(source string) Model

func (ModelSpec) ForModel added in v0.1.1

func (m ModelSpec) ForModel(source, id string) Model

For returns the client the component's configured source asks for: "config" -> the static cheap model; anything else ("incoming"/unset) -> the incoming model, falling back to the static one when there is no incoming client. Returns nil when nothing is available, and the caller must degrade gracefully. ForModel is For plus an optional model-id override: when id is set and the selected client can be re-pointed, the returned client talks to id instead of its own model. An id the client cannot honour is ignored rather than fatal — the component still runs, on the model it would have used anyway, and the caller sees that in the recorded model name.

func (ModelSpec) ForModelSource added in v0.1.1

func (m ModelSpec) ForModelSource(source, id string) (Model, string)

ForModelSource is ForModel plus the source actually used — see ForSource.

func (ModelSpec) ForSource added in v0.1.1

func (m ModelSpec) ForSource(source string) (c Model, used string)

ForSource is For, plus the source that was ACTUALLY used. It exists because the fallback below is silent and the substitution is not cosmetic: `source: incoming` means "spend on the model and credential the caller is already paying for", and falling back to the static one spends a DIFFERENT credential on a DIFFERENT model. A component that cannot tell the difference cannot report it, and an operator reading `model.source: incoming` in their config has no way to learn that none of their calls went there.

Cost a real investigation: a local run's extraction calls failed authentication, and because the fallback is invisible there was no way to tell whether the caller's credential or the operator's static one was being presented. Callers should record `used` (extract_llm gates on it) rather than assume the configured source is the one that ran.

type NeedsModel

type NeedsModel interface {
	NeedsModel() bool
}

NeedsModel is implemented by components that call an LLM (extract's code/rlm strategies, summarize). A component that needs a model but finds none available (Ctx.Model.For returns nil) MUST degrade gracefully — fall back to a deterministic path or no-op — never fail the request.

type NopEmitter

type NopEmitter struct{}

NopEmitter discards all telemetry. Default when none is configured.

func (NopEmitter) Component

func (NopEmitter) Component(Report)

func (NopEmitter) Run

func (NopEmitter) Run(RunReport)

type Offload

type Offload interface {
	Component
	Offload(req *schemas.BifrostChatRequest, rep *Report, c *Ctx) (cacheKeys []string, err error)
}

Offload is a lossy-but-reversible component: it drops bytes from the wire and returns the cache_keys under which it stashed the originals (via c.Store) — one per offloaded item. If it shrinks the request but returns no keys, the pipeline treats it as a failed offload and reverts (you cannot silently lose data) — UNLESS it set rep.Irreversible, the deliberate lossy drop a non-`full` marker_mode makes (summary/off: no stash, no restoration). Returning no keys AND leaving the request unchanged is a legitimate no-op (set rep.Skipped). Examples: collapse, dedup, cmdfilter, extract, smartcrush.

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline runs an ordered list of components over a request. Order is set by config (the pipeline: name-list); this type just executes it. Each component is isolated: a panic or error reverts only that component, and a component that fails to shrink the request is reverted too (never-worse guard, after rtk). The original request is always a valid fallback — fail open, always.

func NewPipeline

func NewPipeline(comps []Component, e Emitter) *Pipeline

NewPipeline builds a pipeline from already-constructed components in order.

func (*Pipeline) Emitter added in v0.4.1

func (p *Pipeline) Emitter() Emitter

Emitter returns the pipeline's configured Emitter, so a caller that needs an optional capability on it (e.g. KeepAliveEmitter) has one path to reach it instead of threading a second field through every place a Pipeline is built. Nil-safe: a nil *Pipeline (a Tenancy built with none, or one from before a pipeline exists) reports NopEmitter, so a caller's type assertion simply finds nothing rather than panicking.

func (*Pipeline) Find added in v0.1.1

func (p *Pipeline) Find(name string) Component

Find returns the configured component with this name, or nil. It is Has for the case where the host needs the component's CONFIGURATION and not just its presence — toolfilter carries the account's removal list, and a body-level transform in apply cannot read it off a boolean. Callers type-assert to the narrow interface they need.

func (*Pipeline) FixedRestore added in v0.5.0

func (p *Pipeline) FixedRestore() bool

FixedRestore reports whether expanded content is restored as a separate message at a fixed anchor rather than by un-compacting the original in place (#407). Nil-safe: false.

func (*Pipeline) Has added in v0.1.1

func (p *Pipeline) Has(name string) bool

Has reports whether a component with this name is configured in the pipeline. Hosts use it to gate body-level work that belongs to a component's concern but cannot be done inside it — e.g. cacheinject's cache-prefix repair, which must touch the top-level `system` array that components never see.

func (*Pipeline) HasOffload added in v0.1.1

func (p *Pipeline) HasOffload() bool

HasOffload reports whether any component in this pipeline is an Offload — i.e. whether a request through it can produce a `<<cg:HASH>>` marker at all.

Asked by the host to decide whether advertising `context_guru_expand` is meaningful. A pipeline with no Offload mints no markers, so every expand call a model makes against it MUST fail: there is nothing in the Store to resolve. Advertising it there costs a wasted round trip and a step of the user's turn to learn that.

A type assertion, deliberately, rather than a list of component names: a name list is a second copy of "which components are lossy" that drifts the moment somebody adds one, and the interface is the definition. `components.Offload` cannot be implemented by accident — it requires returning cache keys that prove the original was stashed.

func (*Pipeline) Names added in v0.2.0

func (p *Pipeline) Names() []string

Names returns the component names in pipeline order, which is what makes an EMPTY pipeline reportable. Without it a caller can only see the per-component stats, and a pipeline configured with no components is indistinguishable there from one whose components all ran and did nothing: both are an empty map. That ambiguity is the same class as the one that made `cachesplit` look dead for a release — it is Mutated-never-Acted by design, so acted/ran read 0% and a panel painted it red (docs/results/measured-2026-08.md). `off` is now the default preset, so the empty case is the COMMON case and has to be legible rather than merely correct.

func (*Pipeline) RecordDiscards added in v0.1.1

func (p *Pipeline) RecordDiscards(rr *RunReport, discarded map[int]int)

RecordDiscards emits one follow-up Report per component whose changes the writeback layer threw away, so a silently-suppressed component is visible in telemetry instead of looking like a working one. discarded maps req.Input index -> number of discarded changes at that index; hosts call this after the splice.

One discarded message is charged to exactly ONE component: the LAST one that changed that index. Several components can touch the same message, but the writeback layer discards the final cumulative state, so that component's change is the one actually thrown away — charging every earlier toucher too would make this counter a false-positive generator, and its whole point is to be trustworthy enough to catch a #32-class bug.

func (*Pipeline) Run

func (p *Pipeline) Run(req *schemas.BifrostChatRequest, c *Ctx) *RunReport

Run applies every enabled component to req in place and returns the aggregate report. req is mutated; on any per-component failure that component's changes are rolled back, so the returned request is never worse than the input.

func (*Pipeline) SetFixedRestore added in v0.5.0

func (p *Pipeline) SetFixedRestore(on bool)

SetFixedRestore records the config's `expand.fixed_restore` switch. Set once by the builder, before the pipeline serves a request.

type PrefixAsker added in v0.1.1

type PrefixAsker interface {
	Ask(ctx context.Context, session, ask string) (reply string, usage PrefixUsage, err error)
}

PrefixAsker completes `ask` as a trailing user message appended to the EXACT body this session sent upstream on the PREVIOUS turn.

WHY THE PREVIOUS TURN'S SENT BODY AND NOT THE INCOMING ONE. The provider's prompt cache was populated by what context-guru emitted, which is the COMPACTED form. The incoming body is uncompacted, so it diverges from the cached bytes at the first thing any component removed, and everything after that point is a miss. Appending to the bytes actually sent is the only construction that reliably reads the cache — measured at 19,595 read against 0 created.

THE CONSEQUENCE, stated here rather than left to be rediscovered: the ask sees the transcript as of the PREVIOUS turn, so the newest tool output is invisible to it. That is acceptable for the judgement this serves — the missing part is tail content, which has had no turns in which to be superseded and would be kept anyway — and it has the side benefit of keeping a large model call off the agent's critical path.

nil when the host cannot support it: no stashed body for this session yet, the first turn, a non-Anthropic route, or the feature switched off. A caller must decide for itself what nil means; see extract_llm_sweep, which DECLINES rather than falling back, because the fallback is the cost the mechanism exists to avoid.

session is the THREAD key, thread.Key(Ctx.Session, Ctx.Thread) (#423): the host stashes each thread's last body apart, because each thread is its own conversation. Pass Ctx.Session alone and a subagent's question is answered against the main thread's transcript.

type PrefixCoverage added in v0.5.0

type PrefixCoverage interface {
	CoversSpan(session string, count int, hash string) bool
}

PrefixCoverage, when a PrefixAsker also implements it, answers whether the body it would append `ask` to actually covers a given prefix of the conversation: the first `count` normalized messages, content-hashed with SpanHash to `hash`. A PrefixAsker that does not implement this interface is assumed to always cover — a caller MAY skip the check rather than refuse an asker it cannot verify, since that is what every caller did before this interface existed.

WHY THIS EXISTS: the host's stash holds the LAST body forwarded for a session, which Ask appends to on the theory that it is the current transcript. That theory breaks when the stash declines to hold a body (too large, see proxy/prefixask.go's maxSentBody) and keeps an OLDER one instead — Ask then silently answers from a transcript that does not include everything the caller is about to claim its checkpoint covers. CoversSpan lets the caller catch that BEFORE paying for the call, by checking the stash's actual coverage against the span it is about to commission a summary for.

type PrefixCoveredAsker added in v0.5.3

type PrefixCoveredAsker interface {
	AskCovered(ctx context.Context, session string, count int, hash, ask string) (string, PrefixUsage, error)
}

PrefixCoveredAsker, when a PrefixAsker also implements it, checks coverage and asks on ONE snapshot of the stash. PrefixCoverage.CoversSpan followed by Ask reads the stash twice: when the call runs detached, the thread's next request can replace the stashed body between the two reads, and the ask then goes out over a body the check never approved. AskCovered returns ErrStalePrefix when the snapshot does not cover the first `count` normalized messages hashed to `hash`, ErrNoPrefix when nothing is stashed, and otherwise asks on exactly the body it checked.

type PrefixUsage added in v0.1.1

type PrefixUsage struct {
	CacheRead  int
	CacheWrite int
	// CacheWrite1h is the SUBSET of CacheWrite the provider billed at the one-hour write
	// premium rather than the default five-minute rate — never an addition to CacheWrite. Kept
	// in the same position as cheapmodel.PrefixUsage's own field of the same name: proxy/
	// prefixask.go converts directly between the two types, which Go only permits when every
	// field name, type and order matches.
	CacheWrite1h int
	Fresh        int
	Output       int
	// ViaTool records that the answer arrived as a tool_use for the proxy's own structured-answer
	// tool rather than as reply TEXT. Reported for the same reason CacheRead is: a caller that
	// declares a verdict tool in order to get a schema-shaped answer cannot otherwise tell whether it
	// got one. A sweep whose tool is never used and a sweep that works look IDENTICAL in every other
	// counter -- both return parsed verdicts and real savings -- because the prose parser accepts
	// both. Measured: a review of PR #137 found 0 of 5 live asks using the declared tool while every
	// verdict arrived through the text path, and no counter in this repo could show that.
	ViaTool bool
}

PrefixUsage reports what one PrefixAsk cost, straight from the provider's usage block. It exists because the whole point of a prefix ask is the cache READ, and a cache read that silently is not happening looks identical to one that is — except on the bill.

RETURNED rather than merely recorded, and that is the load-bearing part of this type. A caller whose entire justification is the cache read has to be able to gate on whether the read happened, which a metrics counter cannot support.

type Reformat

type Reformat interface {
	Component
	Reformat(req *schemas.BifrostChatRequest, rep *Report, c *Ctx) error
}

Reformat is a lossless component: it repacks the request denser in place and loses no information. Examples: format re-encode, code skeleton, cache_control injection.

type Remodeler added in v0.1.1

type Remodeler interface {
	AsModel(id string) Model
}

Remodeler is an optional interface on a Model: the same endpoint and the same credential, pointed at a DIFFERENT model id. It exists for one measured reason.

The incoming-source client is the proxied request's own model, which for a coding agent is a frontier model. Compaction on a frontier model cannot pay: measured on a real Claude Code session through the hosted service, a cold-cache sweep cut the provider bill by $0.63 and spent $1.25 of opus doing it — net MINUS $0.62. The same work on a cheap model is roughly an order of magnitude less on the call side, which is the difference between a component that pays and one that does not.

The static ("config") source cannot supply that cheap model on a multi-tenant deployment, because there the operator will not spend its own credential on a tenant's traffic. So the remaining honest option is the tenant's OWN credential and upstream with a cheaper model id on it, which is exactly what this returns.

type Report

type Report struct {
	Component    string
	Kind         string // "reformat" | "offload"
	TokensBefore int
	TokensAfter  int
	DurationMs   float64
	// CacheKeys are this run's content-derived dedup keys. An Offload sets them itself,
	// one per stashed original (they double as the store keys the expand loop resolves). A
	// Reformat stashes nothing, so the PIPELINE fills them from the pre-fold text of each
	// message it rewrote — without that, every Reformat took metrics' keyless fallback and
	// reported SavedUnique == Saved by construction (overcount_ratio 1.0 for
	// format/textclean/toon/searchfold, against a measured token replay of 10x-95x). The
	// pipeline does the same for an Irreversible Offload that returned no keys (marker_mode
	// summary/off), whose keys are then dedup keys only, not store keys.
	CacheKeys    []string
	Skipped      bool // component ran but chose not to act
	Reverted     bool // pipeline reverted it (error/panic/never-worse)
	Irreversible bool // Offload dropped content on purpose without stashing (marker_mode summary/off)
	Err          error
	// ChangedIdx are the req.Input indices this component modified, filled by the
	// pipeline. The writeback layer uses them to attribute a discarded change back to
	// the component that made it (see Pipeline.RecordDiscards).
	ChangedIdx []int
	// Discarded counts changes this component made that the WRITEBACK layer then threw
	// away (bifrost could not round-trip the message, so splicing would have dropped
	// provider fields). A report carrying Discarded > 0 is a follow-up attribution, not
	// a fresh run — emitters must not count it as one. A component that mutates and is
	// then silently discarded looked identical to one that works, which is how issue
	// #32 survived two benchmark studies.
	Discarded int
	// Mode is the operating mode the run happened under, stamped by the pipeline from
	// Ctx.Mode. Emitters MUST branch on it: an observe-mode report is a HYPOTHETICAL and
	// may never be summed into enforced savings.
	Mode Mode
	// Gates counts, per named gate, how many CANDIDATES this component turned away — either
	// declined outright or resolved without a fresh decision (extract_llm's reapplied_*).
	// "acted: 0" is the one number a diagnosis can't use — it cannot tell a component
	// with nothing to do from one whose guard is misfiring, which is how eight components
	// sat at zero on a whole workload without anyone being able to say which case each
	// was in. Filled by the component via Gate(); rolled up into /stats per component.
	Gates map[string]int
	// Events counts, per named event, things this component DID rather than declined — a cache
	// hit replayed, a candidate reached at depth, an output removed, an inventory offered.
	//
	// Separate from Gates because they were one map and the name lied. Everything in Gates is
	// exported as `cg_component_gate_declines_total`, so `reapplied_same_session` (a cache HIT)
	// and `sweep_dropped` (a removal that WORKED) were being counted as declines: anyone summing
	// that series to gauge whether the pipeline was doing anything got the wrong SIGN, because the
	// more a component succeeded the higher its "declines" climbed. Splitting the map rather than
	// classifying names in the exporter puts the judgement at the call site, where the author knows
	// which one it is, instead of in a lookup table that goes stale the next time a gate is added.
	//
	// A name must not appear in both maps for one component: that would mean the component cannot
	// say whether the thing succeeded or was refused, and TestGatesAndEventsAreDisjoint pins it.
	// Filled via Event()/EventN(); rolled up into /stats beside Gates.
	Events map[string]int
	// Calls records each LLM call this component made on this request. Empty for every
	// deterministic component; one entry per model call for the two that make them.
	//
	// Assigned SERIALLY by the component, never appended to from a goroutine: a Report is
	// copied by value all over this codebase (emitters take one), so it cannot carry a lock.
	// extract_llm fans out into a pre-sized slice and assigns the result once, which is the
	// same shape its projected-output collection already uses.
	Calls []ModelCall
	// Replays counts changes this component made by REPLAYING a decision it had already taken
	// and frozen — the same bytes it emitted on an earlier turn, spliced again with no model
	// call and no new spend.
	//
	// It exists because /stats could not tell a replay from an act (#176). `acted` is
	// `Saved() > 0`, and a replay saves tokens, so a component whose every activation was a
	// free replay of work done days ago reported `acted: 239` — indistinguishable from 239
	// paid extractions. MEASURED (iteration 023, arm B): 239 acts, 2,291 replays, and the
	// component's own record showing zero surviving candidates, i.e. not one fresh call. The
	// two readings have opposite consequences ("this component is expensive, turn it off"
	// against "this component is amortizing, leave it on"), so they cannot share a counter.
	//
	// Set via Replay(), which also files the descriptive Event, so the count and the histogram
	// cannot drift apart.
	Replays int
}

Report is the per-component result, modelled after lean-ctx's ToolOutput token accounting and headroom's record_pipeline_run inputs. The pipeline fills TokensBefore/After/DurationMs; the component fills CacheKey and may set Skipped. It feeds every Emitter.

func (*Report) Event added in v0.1.1

func (r *Report) Event(name string)

Event records that the component DID the named thing once — a replay served, a candidate reached at depth, an output removed. The counterpart to Gate, and the distinction is the whole reason both exist: a decline and a success exported under one metric name called "declines" produced a series whose value rose as the component worked better. See Report.Events.

Same stability rule as Gate: the names are read off /stats and scraped by label.

func (*Report) EventN added in v0.1.1

func (r *Report) EventN(name string, n int)

EventN records n at once, for an event whose subject is a COUNT rather than a single candidate — how many were offered, how many were removed. GateN's rationale applies unchanged.

func (*Report) Gate added in v0.1.1

func (r *Report) Gate(name string)

Gate records that one candidate was declined by the named gate. Names are the component's own vocabulary (e.g. "min_size", "no_filter_match", "marker_no_win"); keep them stable, they are read off /stats.

func (*Report) GateN added in v0.1.1

func (r *Report) GateN(name string, n int)

GateN records n at once, for a gate whose subject is a COUNT rather than a single candidate.

It exists because a per-candidate loop cannot express "this many were OFFERED". The distinction is not cosmetic: a live batched-adjudication arm reported 2.80 verdicts per call and that was read as the batch size, when it counted what the model chose to ANSWER rather than what it was SHOWN. The truncation counter was firing on 43 of 162 calls at the same time, which is arithmetically impossible for batches of 2.8 — the resolution being that the model silently omitted labels. Without a way to count the offer, "the batch is starved" and "the model answered for a third of the batch" are the same number, and the first reading cost three iterations.

func (*Report) Replay added in v0.1.1

func (r *Report) Replay(name string)

Replay records that one change on this request came from replaying an already-frozen decision, under the descriptive event name the component uses for it.

It files BOTH the Event and Report.Replays deliberately, in one call: the Events histogram is the operator-facing vocabulary ("reapplied_same_session" vs "reapplied_cross_session") and Replays is the machine-readable "this cost nothing" that /stats needs to keep replays out of `acted`. Two separate calls at each site is how one of them gets forgotten when a third replay path is added — which is precisely how the free path came to be counted as paid work.

func (Report) Saved

func (r Report) Saved() int

Saved returns non-negative tokens saved by this component.

type RunReport

type RunReport struct {
	Session      string
	TokensBefore int
	TokensAfter  int
	DurationMs   float64
	Components   []Report
	// Mode is the operating mode this run happened under (see Report.Mode).
	Mode Mode
}

RunReport aggregates a whole pipeline run for one request.

func (RunReport) Saved

func (rr RunReport) Saved() int

Saved returns the net tokens saved across the run.

type TokenRates added in v0.1.1

type TokenRates struct {
	Input      float64
	Output     float64
	CacheRead  float64
	CacheWrite float64
}

TokenRates are per-token USD rates for the model a component would call ITSELF, so a component that spends money can price its own calls correctly.

It exists because the alternative was a constant. extract_llm priced every call it made at claude-haiku rates, while the shipped default routes extraction to the AGENT's model — so a call on a sonnet-class model was recorded, and judged by the economic gate, at roughly a third of what it actually cost. MEASURED on a real session: a call recorded at $0.0276 had really cost about $0.083.

Zero means unknown, and a caller must then fall back rather than treat a call as free.

func (TokenRates) Cost added in v0.1.1

func (r TokenRates) Cost(fresh, output, cacheWrite, cacheRead int64) float64

Cost prices one call's four token tiers.

func (TokenRates) Zero added in v0.1.1

func (r TokenRates) Zero() bool

Zero reports whether no rate is known.

type Trigger

type Trigger struct {
	MinRequestTokens int `yaml:"min_request_tokens"` // whole request must be at least this many tokens
	MinMessages      int `yaml:"min_messages"`       // …and carry at least this many messages (≈ steps)
	MinOutputTokens  int `yaml:"min_output_tokens"`  // per-item floor: only offload an output at least this big

	// Context-window fractions (0 = unset) make triggers general across models: each is
	// resolved against Ctx.CtxWindow (the model's max input tokens, obtained dynamically).
	// When the window is unknown (0) fractions are ignored and only the absolute thresholds
	// apply — fully backward compatible.
	//
	// MinRequestFrac is compared against Ctx.PrevBilledInput, NOT against
	// schema.MessagesTokens: a window is stated in the provider's billed units and
	// MessagesTokens counts message text only, a median 3.38x smaller. See Fires. The per-item
	// fractions below are floors on a single tool output, where our own tokenizer is both sides
	// of the comparison and no conversion arises.
	MinRequestFrac float64 `yaml:"min_request_frac"` // fire when request >= frac*window (e.g. 0.6)
	MinOutputFrac  float64 `yaml:"min_output_frac"`  // per-item: only offload an output >= frac*window
	HugeOutputFrac float64 `yaml:"huge_output_frac"` // HARD per-item trigger: a single output >= frac*window

	// CacheState restricts firing by where the request sits in its prompt cache's life:
	// "" / "any" (no constraint) or "pre_expiry". See CacheAllows, and CachePhase for what the
	// phases mean. "cold" and "pre_expiry_or_cold" were withdrawn — see removedCacheStates.
	CacheState string `yaml:"cache_state"`
	// PreExpirySeconds is how wide the pre-expiry window is (0 = DefaultPreExpiry). Wider
	// fires more often and invalidates more remaining lifetime; narrower fires rarely.
	// Nothing measures either side — it is the same unmeasured number extract_llm_sweep
	// carries, and for the same reason.
	PreExpirySeconds int `yaml:"pre_expiry_seconds"`
}

Trigger is the shared, configurable gate that decides whether an expensive (LLM-based) component should ACT on a request — so summarize/extract run only when it's worth an LLM call, not on every turn. It is embedded in a component's config as `trigger:` and works for any agent/benchmark/use-case because the thresholds are pure request shape (tokens and message count), not task-specific.

A zero field is "no constraint", so the zero Trigger fires always (backward compatible with configs that don't set it). Request-level thresholds (MinRequestTokens, MinMessages) are checked by Fires; the per-item MinOutputTokens floor is checked by the component against each candidate (e.g. extract, per tool output).

func (Trigger) CacheAllows added in v0.2.0

func (t Trigger) CacheAllows(c *Ctx, p CachePhase) bool

CacheAllows reports whether the cache phase permits firing.

UNKNOWN IS PERMITTED, AND THAT IS THE OPPOSITE OF WHAT extract_llm_sweep DOES WITH IT. The asymmetry is deliberate and load-bearing both ways.

The sweep must not fire on Unknown because its ASK reads a cache entry that has to exist; a window computed from a guessed TTL would invalidate live prefixes on exactly the deployments whose TTL could not be read.

A size-gated compactor must fire on Unknown, because Unknown is not rare or exotic: CacheTTLMs and IdleMs are both zero whenever the cache-aware path did not run at all — a non-Anthropic-family provider with no cache_control breakpoint, `cache_mode: off`, a bypassed turn, a session's first turn. Declining there would make the component DEAD on those deployments while protecting nothing: with cacheAware false, MaxCachedIdx stays -1, so Ctx.TailOnly already permits every offloader to rewrite deep history there. There is no live prefix whose invalidation we would be avoiding.

An unrecognised value permits, rather than silently disabling the component. Constructors validate the string and refuse a bad one at config time, which is where a typo belongs.

func (Trigger) Fires

func (t Trigger) Fires(req *schemas.BifrostChatRequest, c *Ctx) bool

Fires reports whether the request-level thresholds are met. Thresholds are ANDed; a zero threshold imposes no constraint. Does not consider the per-item floors (OutputFloor/IsHuge).

The two size thresholds are measured on DIFFERENT RULERS, and are therefore separate

This function used to take `reqFloor = max(MinRequestTokens, frac(MinRequestFrac, window))` and compare the result against schema.MessagesTokens. That is a units error, and it made the fraction unreachable rather than merely inaccurate:

  • MessagesTokens counts message TEXT ONLY — no system prompt, no tool declarations, no JSON envelope. MinRequestTokens has always been stated in those units and still is.
  • A context window is stated in the units the PROVIDER bills, which include all of the above. Measured on uncompacted production traffic the provider's count runs a median 3.38x higher than MessagesTokens (p25 2.43, p90 6.80 — dash/overview.go's EstimatorDivergence).

So `MessagesTokens >= 0.9 * 1_000_000` really asks for about 3M provider tokens on a 1M model: the request is rejected upstream, or the client compacts, long before it can be true. A gate that never fires looks exactly like a gate that is working, which is why this is worth the paragraph.

max() cannot be salvaged either — taking the larger of two numbers on two different rulers is meaningless. They are ANDed as separate conjuncts, each against the figure measured its own way. For a config that sets only one (the common case, and every shipped default) this changes nothing; for one that sets both it is stricter, and honestly so.

The fraction is skipped when PrevBilledInput is 0 rather than treated as a zero fill — see FracResolvable, which is the conjunct a caller uses to tell "not full enough" from "cannot tell", and which summarize counts separately.

AND THE DENOMINATOR IS C, NOT THE MODEL WINDOW

"90% full" has to mean 90% of the way to the point where the conversation's own compaction mechanism acts — Ctx.CompactionPoint — and not 90% of the model's window. That IS the argument for this component: compacting just before the client would have acted captures the saving of a large prefix going cold and costs no accuracy that was not already going to be lost, because a compaction was going to happen there anyway. Against the window it is only correct when C equals the window.

The direction of the error is what makes it worth fixing rather than noting. A client that compacts EARLY — Claude Code with a lowered auto-compact threshold, or any agent that caps its own context — resets the transcript before billed input ever reaches `frac x window`, so the component NEVER FIRES on that deployment, silently, and looks exactly like a gate that is working. Measured on haiku behind the current client C is 0.996 of the window, so the two denominators are nearly the same there and this branch's own acceptance run was not affected; that is luck, not design.

See Ctx.FillDenominator for the fallback, and internal/compactionpoint for the definition.

func (Trigger) FracResolvable added in v0.2.0

func (t Trigger) FracResolvable(c *Ctx) bool

FracResolvable reports whether the configured fractions can be resolved against a window worth trusting. False only when a fraction is actually configured AND the window is a guess or unknown — so a Trigger carrying no fractions is unaffected.

WHY THIS IS NOT JUST `CtxWindow > 0`: the resolver's ok=true is not the same as right. Its last resort is a substring table whose Claude entries are `claude-sonnet-5` and a `claude` catch-all at 200,000, so every Opus and every Fable resolves to 200,000 against a real window of 1,000,000. A 0.9 fraction against that fires at 180k — five times too early, on the exact sessions the fraction exists to protect. Frac(0.9, 0) already evaluates to no constraint, so without this check an unknown window silently DROPS the size gate instead of declining.

A per-item floor (OutputFloor, IsHuge) does not consult this on purpose: too small a window there merely raises a floor, which is the safe direction.

func (Trigger) IsHuge

func (t Trigger) IsHuge(outputTokens, window int) bool

IsHuge reports whether a single tool output is large enough (>= HugeOutputFrac*window) to be a "huge tool call" hard trigger — worth acting on regardless of the request-level Fires gate. Returns false when the window is unknown or HugeOutputFrac is unset.

func (Trigger) OutputFloor

func (t Trigger) OutputFloor(window, legacyDefault int) int

OutputFloor is the per-item minimum size an Offload should act on: the absolute MinOutputTokens if set, else MinOutputFrac*window, else legacyDefault (the component's pre-trigger min_tokens default). Lets a component keep firing sensibly whether configured absolutely, as a fraction, or not at all.

func (Trigger) PreExpiry added in v0.2.0

func (t Trigger) PreExpiry() time.Duration

PreExpiry is the configured window width, or DefaultPreExpiry.

func (Trigger) Validate added in v0.2.0

func (t Trigger) Validate(component string) error

Validate checks the Trigger's own keys and is called by every component constructor that embeds one, so a bad value is refused at config time rather than becoming a silent behaviour change.

IT IS SHARED BECAUSE IT DRIFTED. CacheAllows' docstring promised that "constructors validate the string and refuse a bad one at config time", and exactly one of the three constructors that accept the key did. `extract` and `extract_llm` took `cache_state: pre_expiryy` without complaint — which mattered less than it sounds, because neither consults the key either, but the promise in the docstring was load-bearing for the component that DOES.

`component` names the caller so the error says which config block is wrong.

WHAT THIS DELIBERATELY DOES NOT DO: refuse a cache_state on a component that ignores it. `extract` and `extract_llm` embed a Trigger and call neither CacheAllows nor CachePhase anywhere, so `cache_state: pre_expiry` on either of them is silently inert while the settings form describes it as "Restrict firing by the prompt cache's state". A review found that, and both obvious fixes were tried here and both break a contract this repo already keeps:

  • Hiding the keys from those components' form fields fails TestEveryComponentDeclaresExactlyItsConfigurableKeys — a key the config struct accepts must be declared, or it is settable in YAML and invisible in the UI.
  • Refusing the value in the constructor fails TestEveryDeclaredFieldReachesTheDocumentAndNothingElseMoves — a declared field must accept every value it declares.

Both contracts are right, and together they say the real defect is upstream of validation: the key should not be in those components' config at all. That wants Trigger split into a size-only embedded struct plus the cache keys, which is a config-shape change with its own compatibility surface — its own issue, not a rider here. Honouring the key on those components is NOT the answer either: they only ever rewrite the uncached tail (Ctx.TailOnly), so they never invalidate the cached prefix, which is exactly why they have no economic reason to wait for a cache state.

So this validates what is true for every component that embeds a Trigger: that the enum value exists, and that the window is in range.

Directories

Path Synopsis
Package all blank-imports every built-in component so their init() registrations run.
Package all blank-imports every built-in component so their init() registrations run.
Package dsl is a declarative, user-extensible text-filter engine, adapted from rtk's TOML filter DSL (design D11).
Package dsl is a declarative, user-extensible text-filter engine, adapted from rtk's TOML filter DSL (design D11).
Package offload holds the lossy-but-reversible components (they drop bytes and stash the original for the expand tool loop).
Package offload holds the lossy-but-reversible components (they drop bytes and stash the original for the expand tool loop).
Package reformat holds the lossless components (they repack the request denser or add caching hints without losing information).
Package reformat holds the lossless components (they repack the request denser or add caching hints without losing information).

Jump to

Keyboard shortcuts

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