Documentation
¶
Overview ¶
Package context assembles the minimum sufficient engineering context for a plain-English task.
The requirement is not "retrieve everything relevant" ¶
An agent has a finite context window, and every token spent on a file it did not need is a token it cannot spend on thinking. The objective this package optimises is therefore USEFUL ENGINEERING UNDERSTANDING PER TOKEN, not recall. Returning fifty files is a failure even when the right five are among them: the agent still has to read fifty, and the noise degrades its reasoning. Spec §43's golden test encodes exactly that — the assertion that carries the weight is the one about what must be ABSENT.
Why lexical retrieval alone cannot work ¶
The bundled payment fixture contains the trap in miniature. The file unrelated/marketing/MarketingReport.java carries the comment "Unrelated to payments", so for the task "Add idempotency to payment callback processing" full-text search ranks it ABOVE CallbackController — the word "payment" appears more prominently in a file that has nothing to do with payments. Any engine that scores by lexical similarity returns it.
What separates the two is not vocabulary but structure: CallbackController sits on a call path, MarketingReport shares no dependency edge with anything the task names. So graph connectivity is an ADMISSION GATE here, not merely a ranking signal (see admit in rank.go). Lexical evidence alone admits a candidate only when it is corroborated — several distinct task terms, not one word in a comment.
Determinism ¶
No LLM calls, no network, no clocks in the ranking path. The same task against the same index produces a byte-identical Pack, because an agent that gets a different answer on a retry cannot build a cache, a test, or trust. Every map in this package is iterated through a sorted key slice for that reason.
Honesty about what was left out ¶
Every Item carries a non-empty Why, and notable rejections are reported in Pack.Excluded with the reason. "We can tell you what we did not send you, and why" is the difference between a bounded answer and a silently partial one — the same principle the graph package applies to truncated traversals.
Query shape ¶
One Assemble call issues a bounded, fixed number of queries: two full-table reads (files, symbols) that build the in-memory catalogue, one full-text query per task term, one query per BFS level inside graph.Traverse, and at most Budget.MaxFiles content reads for the units that survive ranking. There is deliberately no per-symbol or per-edge query anywhere: an N+1 over a 94,000-symbol registry is how an interactive tool stops being interactive.
Measured performance ¶
From bench_test.go, 160 samples across four tasks, Apple M-series, in-memory store, CGO_ENABLED=0, without the race detector:
repository size p50 p95 p99 payment fixture (41 syms) 1.5ms 2.5ms 4.6ms synthetic 10,000 symbols 94ms 105ms 128ms synthetic 94,000 symbols 852ms 1.34s 1.54s
The 2s target holds at every size, but the margin at 94,000 symbols is thin and the reason is known rather than mysterious: BenchmarkLoadCatalogue shows the two full-table reads account for 79ms of the 138ms spent at 10,000 symbols, and they scale linearly while everything after them is bounded by the budget. If this ever regresses, the catalogue is the thing to fix — by caching it per index revision, which is safe because a committed run is immutable — and not the ranking.
Timing is not asserted under -race. Instrumentation costs 5-20x, so a budget that passed there would have to be loose enough to mean nothing; see race_off_test.go.
Index ¶
Constants ¶
const DefaultMaxTokensEstimate = 8000
DefaultMaxTokensEstimate is the default token ceiling for one pack.
8,000 estimated tokens is roughly 4% of a 200k window. That is deliberately frugal: a context pack is what the agent reads BEFORE it starts working, and it must leave room for the file reads, edits and test output that follow. config.Config has no equivalent field, so this constant is the only source.
Variables ¶
var ErrEmptyTask = errors.New("context: task must not be empty")
ErrEmptyTask is returned for a blank or whitespace-only task.
Functions ¶
This section is empty.
Types ¶
type Assembler ¶
type Assembler struct {
// contains filtered or unexported fields
}
Assemble builds the minimum sufficient context for req.Task.
The pipeline, in order, each stage narrowing the last:
normalise the task -> Intent (weighted terms, identifiers, verbs) candidate retrieval -> seeds by symbol name + files by full text graph expansion -> bounded, confidence-aware, from the seeds structural completion -> owning declarations, test coverage, tables touched admission -> the gate that keeps text-only matches out ranking -> one weighted score per unit compression -> summaries first, source ranges last budget -> stop at marginal value, report what was cut
runID must be the run g reads (the committed one, for a graph.Graph built with graph.New). Passing a different run yields a catalogue and a traversal that disagree; nothing here can detect that, so the caller owns it. Assembler owns the catalogue cache.
It exists because docs/development.md §4.2 forbids package-level mutable state, and the cache would otherwise be exactly that: a process-wide var, shared by every caller, invisible in every signature. The rule is right here for a concrete reason — a global cache is shared by tests that never asked for it, cannot be sized or dropped per consumer, and makes "which index is this serving?" a question the type system cannot answer.
Ownership also lands the cache where it earns its keep. The MCP server holds one Assembler for its lifetime and every request reuses the catalogue; a CLI command builds one, answers a question and exits, where a cache was never going to help. Neither has to know about the other.
func NewAssembler ¶
func NewAssembler() *Assembler
NewAssembler returns an Assembler with an empty cache.
func (*Assembler) Assemble ¶
func (a *Assembler) Assemble(ctx context.Context, reg Registry, g Graph, runID int64, req Request) (Pack, error)
Assemble builds a context pack, reusing this Assembler's catalogue when the run's content has not changed.
func (*Assembler) Warm ¶
Warm builds the catalogue for runID ahead of the first request, so the first context pack a person asks for is answered at warm speed. It is the load every Assemble would do on a cold cache, done early; an error is returned for the caller to log and otherwise ignore, since the first real request will simply load it again.
type Budget ¶
type Budget struct {
// MaxFiles bounds the number of DISTINCT file paths across all items.
// Files, not items, because reading a second symbol from a file the agent
// already has open is nearly free while opening a new file is not.
MaxFiles int
// MaxSymbols bounds the number of items.
MaxSymbols int
// MaxLines bounds total excerpt lines across the pack.
MaxLines int
// MaxTokensEstimate bounds the pack's ESTIMATED token cost. See
// EstimateTokens: the estimate is bytes/4 and is not exact.
MaxTokensEstimate int
// MaxGraphDepth bounds how many hops from a seed the expansion may travel.
// Depth is the cheapest knob to get wrong: each additional hop multiplies
// the reachable set, and by hop four "related to the task" has usually
// decayed into "in the same program".
MaxGraphDepth int
// HubDegreeLimit refuses to expand THROUGH a symbol wider than this many
// edges. Zero, the default, disables it, and withDefaults deliberately does
// NOT fill it from DefaultBudget: unlike every other field here, an unset
// value is a complete instruction ("do not prune"), not a forgotten one.
//
// Depth is the knob that multiplies the reachable set; this is the knob
// that stops one wide node from doing the multiplying on its own.
HubDegreeLimit int
}
Budget bounds what one context pack may cost the agent that reads it.
Every field is a ceiling, never a target. The assembler stops as soon as marginal value falls off (see Thresholds.MarginalFraction), which is usually well before any of these limits bind; the limits exist so that a pathological task — one naming a symbol every file touches — still produces something an agent can read rather than a dump of the repository.
func BudgetForProfile ¶
func BudgetForProfile(profile BudgetProfile) Budget
BudgetForProfile returns a pre-configured Budget tuned for the given profile.
func BudgetFrom ¶
BudgetFrom derives a Budget from resolved configuration.
The context.* keys in .graphlume.yml have been parsed and validated since M0 but nothing consumed them; this is the consumer. Repository config is untrusted, but these values can only make a response SMALLER or larger within limits the config package already validates (MaxGraphDepth is capped at 10 there precisely because an unbounded traversal is a denial of service).
func DefaultBudget ¶
func DefaultBudget() Budget
DefaultBudget returns the budget implied by config.Defaults.
type BudgetProfile ¶
type BudgetProfile string
BudgetProfile names a pre-calibrated context budget profile.
const ( // ProfileCompact is calibrated for fast subagent loops and tightly scoped tasks (~2,000 tokens). ProfileCompact BudgetProfile = "compact" // ProfileStandard is the default balanced budget for coding agents (~8,000 tokens). ProfileStandard BudgetProfile = "standard" // ProfileDeep is for complex multi-module refactoring and architectural changes (~32,000 tokens). ProfileDeep BudgetProfile = "deep" )
type Exclusion ¶
type Exclusion struct {
Name string `json:"name"`
Path string `json:"path,omitempty"`
Reason string `json:"reason"`
}
Exclusion is a candidate that was considered and left out.
Reporting these is a product requirement, not diagnostics. An agent (or a human reviewing the agent) can only trust a bounded answer if the boundary is visible; "we left out MarketingReport because nothing connects it to the callback flow" is a checkable claim, while silence is not.
type Graph ¶
Graph is the traversal surface. One method: expansion is bounded and confidence-aware inside internal/graph, and this package uses that rather than reimplementing it.
type Intent ¶
type Intent struct {
// Terms are de-duplicated and sorted by (descending weight, text) so that
// everything downstream — including the Interpretation string — is stable.
Terms []Term
// Identifiers are tokens the author wrote in code form (CamelCase,
// snake_case, or quoted). They are the strongest evidence a task carries.
Identifiers []string
// Verbs are the recognised action words, kept for Interpretation rather
// than for retrieval.
Verbs []string
}
Intent is a task normalised into something retrievable.
func ParseTask ¶
ParseTask turns a plain-English task into an Intent.
Quoted spans are lifted out first and treated as verbatim identifiers, which is how a user says "I mean this exact name" in a sentence that is otherwise prose.
func (Intent) TotalWeight ¶
TotalWeight is the denominator for lexical coverage: what fraction of the task's intent a candidate accounts for.
type Item ¶
type Item struct {
// Kind is the entity kind: class, interface, method, function, table, test
// or file. It uses model.EntityKind values so an agent sees the same
// vocabulary the rest of GraphLume speaks.
Kind string `json:"kind"`
Name string `json:"name"`
FQN string `json:"fqn,omitempty"`
Path string `json:"path"`
Line int `json:"line,omitempty"`
// Relevance is the composite score. Comparable within one pack only: it is
// not a probability and carries no meaning across tasks.
Relevance float64 `json:"relevance"`
// Why is never empty. An item an agent cannot justify to the human reading
// its output is an item that should not have been sent.
Why string `json:"why"`
// Confidence describes the RELATIONSHIP that justified inclusion, not the
// existence of the symbol: the minimum confidence along the graph path for
// an expanded item, "low" for a naming-convention or text match. It follows
// model.Confidence, so "exact" still means a compiler proved it.
Confidence string `json:"confidence,omitempty"`
// Excerpt is bounded, untrusted repository source. Present only on the few
// items where reading the code is cheaper than fetching it.
Excerpt string `json:"excerpt,omitempty"`
}
Item is one unit of context, with the reason it earned its tokens.
type Pack ¶
type Pack struct {
Task string `json:"task"`
// Interpretation is what GraphLume understood the task to be. It exists so a
// wrong answer can be diagnosed in one glance: almost every bad pack comes
// from a misread task, not from bad ranking.
Interpretation string `json:"interpretation"`
Items []Item `json:"items,omitempty"`
Excluded []Exclusion `json:"excluded,omitempty"`
// Notes carry coverage caveats: truncation, bounded traversals, areas the
// index does not cover. Never empty when something was cut.
Notes []string `json:"notes,omitempty"`
// TokenEstimate is an ESTIMATE, computed as bytes/4 over the pack's text.
// Real tokenisers disagree with it by 10-20% depending on how much of the
// content is code, and it is reported so a caller can budget, never as a
// billing figure.
TokenEstimate int `json:"token_estimate"`
}
Pack is the assembled context.
func (Pack) ContentTokens ¶
ContentTokens estimates only the material the agent has to READ: the task, GraphLume's reading of it, and the items.
This, not EstimateTokens, is what Budget.MaxTokensEstimate bounds, and the distinction is deliberate rather than convenient. Notes and exclusions are GraphLume's own reporting about the answer, they GROW as the budget bites, and trimming them to fit a budget would mean the tighter the budget the less honest the pack — exactly backwards. They are bounded separately, by Thresholds.MaxExclusions.
func (Pack) EstimateTokens ¶
EstimateTokens returns the approximate token cost of the whole pack, reporting included.
type Registry ¶
type Registry interface {
// CatalogueFingerprint is how the cache decides a run's content changed.
CatalogueFingerprint(ctx context.Context, runID int64) (registry.Fingerprint, error)
Files(ctx context.Context, runID int64) ([]model.File, error)
Symbols(ctx context.Context, runID int64) ([]model.Symbol, error)
SearchFiles(ctx context.Context, query string, limit int) ([]registry.FileMatch, error)
FileExcerpt(ctx context.Context, runID int64, path string, startLine, lines int) (string, error)
}
The ports this engine depends on.
docs/development.md §3 names the Context Engine explicitly under Dependency Inversion: a high-level module must depend on abstractions, never on a concrete driver. Taking *registry.Registry and *graph.Graph would mean the ranking and budgeting logic — the part of this product with the most judgement in it and the least I/O — could only be exercised against a real SQLite database.
internal/capability already declares its ports this way, so this is the project's own established pattern rather than a new one.
The interfaces are deliberately tiny: five methods and one. Every method here is a method a fake has to implement, and a fake that has grown to mirror the real registry has stopped being a test aid.
HONEST LIMIT. These signatures still name registry.Fingerprint, registry.FileMatch and graph.Query, so this package still IMPORTS those packages for their data types and `go list -deps` still reaches the SQLite driver transitively. What the interfaces buy is substitutability and testability — a caller can supply anything satisfying them. Severing the transitive import as well would mean relocating those DTOs into pkg/model, which is a larger change than the benefit currently justifies; it is recorded here so the remaining gap is visible rather than assumed closed.
type Request ¶
type Request struct {
// Task is the plain-English description of the work. Required; a blank
// task is an error rather than an empty pack, because it is always a
// caller bug and returning "nothing matched" would hide it.
Task string
// Budget bounds the result. The zero value means "use the defaults".
Budget Budget
// Tuning overrides the ranking policy. nil means DefaultTuning. Exposed so
// the weights are configurable from one place rather than being recompiled,
// and so a test can prove a weight actually does what its comment claims.
Tuning *Tuning
}
Request is one context assembly.
type Term ¶
type Term struct {
Text string
Weight float64
// Stem is a crude suffix-stripped form, or "" when stemming would not
// change the word. "processing" -> "process", "transactions" ->
// "transaction". Crude on purpose: a real stemmer is a dependency and a
// source of surprises, and the only job here is to bridge the plural and
// gerund forms that separate English prose from code identifiers.
Stem string
}
Term is one extracted concept from a task, with how much it should count.
Weight is not frequency. It encodes how much INTENT the word carries: an identifier the author typed verbatim ("TransactionService", "handle_callback") is a near-certain pointer at code, a domain noun is a good one, and the verb of the sentence is mostly grammar.
type Thresholds ¶
type Thresholds struct {
// SeedName is the minimum name signal to become a seed. At 0.35 a single
// identifier-part match on a full-weight noun (0.7/1.5 = 0.47) qualifies
// and a stem-only match on a demoted verb does not.
SeedName float64
// MinLexicalTerms is how many DISTINCT task terms a file must match to earn
// a place on lexical evidence alone. Two, because one is exactly the decoy
// case the golden test encodes.
MinLexicalTerms int
// MarginalFraction stops the pack when value falls off rather than when the
// budget fills: an item scoring under this fraction of the best item is
// noise next to what is already included, and including it costs the agent
// capacity to think.
MarginalFraction float64
// AbsoluteFloor drops items that are weak in absolute terms even when
// everything else is weaker still, so a task that matched almost nothing
// returns almost nothing instead of promoting its best rubbish.
AbsoluteFloor float64
MaxSeeds int
// LexicalSeeds is how many seed slots are RESERVED for corroborated text
// evidence, taken from the weakest name seeds when the set is full.
//
// It is not a ranking weight and must not be tuned like one. It exists
// because the seed budget is otherwise monopolised by marginal name
// matches: measured on the self bench, all five cases filled every slot
// with name seeds and discarded 53-98 corroborated lexical files. Set to 0
// this package behaves exactly as it did before lexical seeding existed.
//
// Measured sensitivity on the self bench, so the next person does not have
// to rediscover it: 3 and 6 both score 2/5 at 50% mean recall; 12 falls
// back to 1/5 at 30%. There is a plateau at small values and a cliff, and
// the cliff has an explanation — past a point the quota displaces name
// seeds that were carrying real evidence. 6 sits inside the plateau rather
// than on its edge, which is the reason to prefer it over 3. Raising it
// toward 12 is known to be wrong.
LexicalSeeds int
MaxGraphNodes int
MaxQueryTerms int
LexicalLimit int
// DefinitionLimit is how many functions and methods the whole-task text
// query over definitions returns (see searchDefinitions). 0 turns
// definition evidence off and the pack is assembled from file text alone.
DefinitionLimit int
// ExcerptLines caps how much source ANY ONE item may show. Source is the
// last thing added and the first thing cut: a symbol summary costs a line
// and tells the agent where to look, while a source range costs twenty and
// tells it something it can fetch itself.
//
// It is a ceiling, not the allocator — a 200-line method is not the fastest
// way to teach one idea no matter how much of the envelope it won. Which
// items get source, and how much each gets, is decided by weight in
// allocateBodies.
//
// There is deliberately no MaxExcerpts beside it any more. A count of items
// allowed to carry source WAS the allocation-by-count defect: it handed the
// first three items the whole envelope regardless of how much stronger the
// first was than the third, and an item it skipped freed nothing for the
// items behind it. How many items can carry source now falls out of the
// envelope itself — BodyFloorShare and MinBodyChars together admit at most
// BodyFloorShare*envelope/MinBodyChars of them — so the bound is a
// consequence of the budget rather than a second, unrelated number.
ExcerptLines int
// may spend, converted to characters at bytesPerToken.
//
// It is a minority share on purpose. A summary line is the part of a pack an
// agent CANNOT reconstruct — it is our reading of the repository — while a
// source range is something it can fetch itself in one call with the path
// and line we already gave it.
//
// 0.06 was chosen by measurement, and against the first instinct. A share
// of 0.10 would take `graphlume bench
// fixtures/bench/payment.yml` from 1,640 / 1,246 / 988 tokens to
// 2,200 / 1,607 / 1,427 — about 34% more — while recall stays at 100% on
// all three cases, exactly as at 0.06. The extra characters
// buy nothing the harness can see.
//
// The harness is saturated, so this is NOT evidence that wider source
// coverage is worthless; it is the absence of evidence that it is worth
// paying for. With the objective being useful understanding per token, the
// burden of proof sits on the more expensive default, and it is unmet. Raise
// it when a benchmark exists that can tell the two apart — one that scores
// whether the agent's ANSWER improved, not whether the right files were
// named.
BodyShare float64
// eligible items before the remainder is split by weight.
//
// This is the knob that decides whether a diffuse question gets a spread or
// a spotlight. At 0 the leader takes nearly everything, which is right for
// "fix handleCallback" and wrong for "how does payment settlement work". At
// 1 every item gets the same share regardless of relevance, which is exactly
// the allocation-by-count defect this replaces. 0.35 was chosen against the
// golden task: it leaves every one of nine items ~124 characters — two or
// three lines, enough to see a signature — while the top item still wins
// about six times the weakest item's allocation.
BodyFloorShare float64
// BodyCliffFraction is the relative cliff: an item whose body weight is
// below this fraction of the STRONGEST item's weight is named in the pack
// but carries no source.
//
// It is the same 0.15 as MarginalFraction, and sharing the number is the
// point: an item that far below the leader is already at the edge of being
// worth listing, so its bytes are past that edge. Two numbers for one
// judgement would drift apart and neither would be explainable.
//
// The cliff is applied over the WHOLE candidate list, before the item cap.
// Applied after, the cap fills with cliff-bound items and the envelope they
// free is never handed to the items behind them.
BodyCliffFraction float64
// MinBodyChars is the smallest excerpt worth printing: about three lines at
// the fixture's measured ~40 characters per line of Java. Below that an
// excerpt shows a signature and half a statement, which tells an agent less
// than the item's own summary already did while still costing tokens. When
// the envelope cannot give every eligible item this much, the allocator
// withholds source from the weakest rather than dusting everyone with
// fragments.
MinBodyChars int
// MaxExclusions bounds how many rejections are reported. The list is a
// trust feature, not an audit log; naming the near-misses is useful,
// enumerating every file in the repository is not.
MaxExclusions int
}
Thresholds are the cut-offs that decide what is even considered.
type Tuning ¶
type Tuning struct {
Weights
Thresholds
}
Tuning is the complete ranking policy.
func DefaultTuning ¶
func DefaultTuning() Tuning
DefaultTuning returns the policy the golden test is calibrated against.
type Weights ¶
type Weights struct {
SymbolNameMatch float64
GraphProximity float64
Lexical float64
TestRelation float64
DataAccess float64
Centrality float64
ModuleAffinity float64
Recency float64
// is scaled by the path's minimum confidence. At 0.6, a path built entirely
// from low-confidence guesses still counts for 40% + 15% = 55% of a proven
// one — discounted, never erased, because under-reporting a real dependency
// is the more expensive error.
ConfidenceShare float64
// MemberBonus rewards a unit that contributed several relevant members: a
// class where three methods sit on the path is more central to the task
// than one where a single field was touched. Capped, because a large class
// would otherwise win on size alone.
MemberBonus float64
MaxMemberBonus float64
// WorthGenerated discounts generated, vendored or minified source (see
// looksGenerated). A generated PaymentRequestBuilder matches "payment" as
// well as a hand-written one and is ranked accordingly, but its body is
// templated: reading it teaches an agent about the generator, not about the
// change. 0.2 rather than 0 because a schema-generated DTO still shows the
// field names, which is occasionally the answer.
WorthGenerated float64
// WorthTextOnly discounts a unit admitted on text alone. That evidence is a
// word that may well be in a comment — the decoy case this package exists to
// get right — so its bytes are the least likely in the pack to repay their
// cost. Half, not less, because the words could equally be in the code.
WorthTextOnly float64
}
Weights are the ONLY place a ranking coefficient appears.
Spec §17 warns specifically about scoring logic scattered across files: once three packages each add "a small boost", nobody can explain a ranking or change it safely. Every number below is applied exactly once, in score, and nothing else in this package multiplies a signal by a constant.
The absolute values matter less than the ORDER, which encodes a claim about evidence quality:
SymbolNameMatch > GraphProximity > TestRelation > DataAccess > Lexical
- SymbolNameMatch is highest because the task naming a symbol is the only
signal that reflects the author's own intent rather than our inference.
- GraphProximity is second and must stay above Lexical. That ordering is
the whole reason the golden test passes: in the payment fixture the decoy
file scores BETTER lexically on "payment" than the real controller does,
and only structure tells them apart.
- TestRelation is high because existing coverage is disproportionately
valuable for a change task — it tells the agent what must keep passing —
and because nothing else in the pipeline would surface it.
- DataAccess is high for the same reason for persistence: an idempotency
change lives at the write, so the tables on the path are context, not
trivia.
- Lexical is deliberately the weakest evidence that can admit anything. A
word in a comment is not a dependency.
ModuleAffinity and Recency are MODIFIERS: they reorder material that is already relevant and can never admit anything on their own (see score). Recency is weakest of all because file mtime is noisy — `git checkout` rewrites it wholesale, which is exactly why the indexer compares content hashes instead.