# trim-2: the line-selection model trim-2 is the small model inside the Caveman Engine that decides which lines of a tool result an agent needs for its current ask. It returns a verbatim subset of the input's lines, in their original order, with one marker line wherever a run of lines was removed: ```text … 237 lines … ``` It never rewrites, summarizes, or reorders a line. Identifiers, paths, numbers, and error text come through byte for byte, or not at all. Every removed line stays recoverable through [Caveman Context Recovery](context-recovery.md). | Property | Value | |---|---| | Source | [`engine/trim2`](../../engine/trim2/) | | Model file | `model.bin`, 3,565,964 bytes, embedded in the binary | | Model type | Two-stage gradient-boosted tree ensemble ("KEEP v2" format) | | Stage 1 | 701 trees, 86,364 split nodes, 134 features per line | | Stage 2 | 641 trees, 40,270 split nodes, 174 features per line (stage 1's 134 plus 40 contextual) | | Selection | Exact O(N) Viterbi dynamic program over keep/drop states | | Runtime | Pure Go standard library, no cgo, no network, no files read at runtime | | Output | Deterministic: the same context and query give the same output | | Default in 5.0 | `smart_max` in proxy `compress` mode | trim-2 is the successor to [trim-1](https://github.com/caveman-ai/trim-1), a single-stage, 67-feature model. trim-1's README told users to expect small savings on coding-agent tool outputs. trim-2 keeps trim-1's 67 features, adds 67 aimed at what coding agents read (diffs, gutters, stack frames, repeated log templates, identifiers split across `camelCase` and `snake_case`), stacks a second forest that sees the whole context at once, and replaces trim-1's score threshold with a token-budget optimizer. ## Where it runs | Surface | What trim-2 does there | |---|---| | Proxy, `compress` mode | Prunes `tool_result` blocks, paired with the structural Engine (see [How the proxy uses it](#how-the-proxy-uses-it)). Runs on Anthropic, OpenAI (HTTP and Responses WebSocket), Azure, OpenAI-compatible, and Gemini requests; not on Bedrock or Vertex, where the proxy reads no query yet | | Aged epoch compaction | Scores the lines of old tool results so compaction keeps the highest-signal ones ([proxy docs](proxy-and-providers.md#compress-mode-in-50)) | | `caveman-mcp codemode` | Prunes oversized multi-line string results inside Code Mode JSON envelopes at `balanced` (keeping valid JSON and archiving the full original in CCR first), and exposes explicit query-driven trimming via pipeline step `op: "trim"` and QuickJS `caveman.trim(text, query, level?)` | | Native runtime hooks | An inline PostToolUse path exists in `proxy/internal/nativeruntime`, but 5.0.0 ships it switched off: nothing sets its level yet | trim-2 never touches the user's prompt, the system prompt, or the tool catalog. It is not registered in the Engine's `Detect` router or `Capabilities()` manifest, and the WebAssembly build does not import it. ## What the model reads Each line becomes one row of numbers. Stage 1 computes 134 features from the line, its neighbors, the whole context, and the query: | Group | Features | What they capture | |---|---:|---| | trim-1 base | 67 | BM25 and query-term coverage, compound terms, bigrams and trigrams, IDF, line kinds (error, test, path, heading, diff, signature, JSON key, stack frame), repetition and templates, position, length, character mix, indentation, enclosing block header, neighbor scores | | Context fingerprints | 12 | Share of duplicate, code, diff, JSON, and error lines; line-number gutters; BM25 spread and Gini | | Coding-agent line kinds | 10 | Diff additions and deletions, return and control lines, imports, comments, noisy log lines, closing braces, URLs and SHAs, numeric outliers, ANSI control codes | | Template dynamics | 4 | How rare a line's template is, its last occurrence, first duplicate, run length | | Precise matching | 8 | Z-scored BM25 and coverage, exact-case symbol hits, file basename hits, identifier density, rare-term count | | Multi-scale proximity | 10 | Distance to the nearest error, top BM25 line, and diff change; block and section maxima; error counts in a 5-line window | | Sub-identifier channel | 8 | A second BM25 over identifier parts, so `ledgerClient` matches a query about the ledger client | | Scope and byte economy | 9 | Line's share of bytes, block and section size, position inside them, indent depth, query path directories, character-trigram similarity | | Sole witness and waste | 6 | Lines that are the only place a query term appears, control-flow guards, timestamped log lines, waste (lockfiles, `node_modules/`, `__pycache__`, long hex or base64 blobs) | Stage 1's forest turns each row into a raw score. Stage 2 then computes 40 more features from those scores across the whole context: each line's rank, z-score, and share of the total probability mass; the scores of the lines 1 and 2 away, and the best or mean score within 3, 7, and 15 lines; the best and mean score of its block, section, and template cluster; the distribution's quantiles and entropy; how much probability mass and how many bytes rank above it; and a 2-hop anchor signal. The 2-hop signal takes terms that are rare in the context, absent from the query, and present on stage 1's top 3 to 8 lines, and credits other lines that share them, so a line that never mentions the query can still be kept when it names the function the answer line names. Stage 2's forest scores the 174-column row, and a sigmoid turns that score into a keep probability between 0 and 1. Blank lines score 0. Tree evaluation is exact: each split threshold is stored as the largest `float32` not above the trained `float64` threshold, and the sigmoid uses a vendored copy of Go's portable `math.Exp` (BSD license, `LICENSE-go`). The copy skips Go's per-architecture assembly, and its explicit `float64` conversions stop the compiler from fusing multiply-adds, so the CPU architecture does not change the result. ## From scores to a selection A keep probability per line is not yet a decision. trim-2 chooses the set of kept lines with a two-state Viterbi pass that maximizes: ```text sum over kept lines ( p_i ^ α − λ · tokens_i ^ β ) − sum over removed runs ( λ · marker_tokens ^ β ) + sum over adjacent kept ( cohesion · min(p_i, p_i−1) ) ``` - `p_i` is the line's keep probability and `tokens_i` its estimated tokens (`(bytes + 3) / 4`, minimum 1). - `λ` is the price of a token. It scales with the payload's shape and with the context's mean probability, so a short context full of likely lines and a long context of unlikely ones are cut to comparable standards. - Every removed run costs a marker (5.5 tokens). A cheap line between two kept lines usually costs less than the marker that would replace it, so it stays. - Cohesion rewards keeping neighbors together, capped at 0.8 λ. The pass is exact and linear in the number of lines. After it, fixed rails widen the selection: - the 3 highest-scoring lines are always kept; - each kept line's enclosing block header is kept (1 level; 2 or 3 levels in source code, depending on the point), along with the opening section line; - in source code at `conservative` and `balanced`, one line of context on each side of every kept line; - in logs and diffs, every line matching `error:`, `exception:`, `traceback`, `panic:`, `fatal:`, `--- FAIL:` and similar is pinned, whatever its score; - a gap of 1 removed line (at most 40 bytes) between kept lines is filled; in source code, gaps of up to 2 lines and 120 bytes, so Edit and `apply_patch` anchors stay contiguous. A shape classifier reads up to 90 non-blank lines sampled across the head, middle, and tail of the payload and labels it `code`, `diff`, `log`, `grep`, `structured`, or `prose`. The label drives the shape-specific token price, the code rails, within-file unit coherence and call-graph pooling, and the `smart_max` dispatch. It uses only the bytes in front of it. ## Operating points | Point | Token price λ | Shape scaling | Code headers / context | Smallest code file cut | Informative query terms needed | |---|---:|---|---|---:|---:| | `conservative` | 0.0060 | Yes | 3 / ±1 line | 1,200 bytes | 2 | | `balanced` | 0.0130 | Yes | 3 / ±1 line | 900 bytes | 2 | | `aggressive` | 0.0155 | Yes | 2 / none | 512 bytes | 1 | | `max` | 0.0190 | Yes | 2 / none | 512 bytes | 1 | | `smart_max` | `balanced` policy on code and diffs, `max` policy on everything else | | | | 2 | `smart_max` is the 5.0 default. Source code and diffs are what an agent edits next, so they get `balanced`, with its Edit-safe code rails. Logs, search results, prose, and dumps are what an agent skims, so they get `max`. The dispatch is a pure function of the context bytes, which keeps the result stable across turns. Across the benchmarked dev and held-out suites, token counts are non-increasing from `conservative` through `balanced`, `aggressive`, and `max`. ## A worked example `engine/trim2/trim_test.go` builds a synthetic 404-line `kubectl logs` output: 400 INFO lines, one `ERROR payment client: ledger-db timeout`, its stack frame, and `exit status 1`. The query is *"Why did the checkout payment fail? Find the ledger error."* At `smart_max`, which takes the `max` policy for a log: ```text $ kubectl logs deploy/checkout --since=1h … 269 lines … 2026-10-11T03:04:29Z INFO checkout request 1269 served in 24ms 2026-10-11T03:04:30Z INFO checkout request 1270 served in 25ms 2026-10-11T03:04:31Z INFO checkout request 1271 served in 26ms 2026-10-11T03:04:31Z ERROR payment client: ledger-db timeout after 30s (order 1271) at LedgerClient.charge (ledger/client.go:88) 2026-10-11T03:04:32Z INFO checkout request 1272 served in 10ms 2026-10-11T03:04:33Z INFO checkout request 1273 served in 11ms 2026-10-11T03:04:34Z INFO checkout request 1274 served in 12ms … 126 lines … ``` | Point | Lines kept of 404 | o200k tokens (`inferred`) | Error and stack frame kept | |---|---:|---:|---| | Input | 404 | 10,061 | | | `conservative` | 42 | 1,051 | Yes | | `balanced` | 16 | 376 | Yes | | `aggressive` | 12 | 296 | Yes | | `max` | 9 | 216 | Yes | | `smart_max` | 9 | 216 | Yes | | Structural Engine, log compressor | | 169 | Yes | On this log trim-2 loses. Four hundred of its 404 lines share one template, which is exactly what the Engine's log compressor folds, and it keeps the header, the first and last lines, the error, and its stack frame in 169 tokens. The proxy runs both and sends the smaller result (see [How the proxy uses it](#how-the-proxy-uses-it)), so here the agent gets the Engine's 169. trim-2 earns its place on blocks with little repetition to fold, where the Engine's compressors keep every distinct unit or pass the block through untouched. `Example_goldenLog` in [`engine/trim2/example_test.go`](../../engine/trim2/example_test.go) pins every number in this table, so `go test ./engine/trim2/` fails if a model, policy, or log-compressor change moves one. This is a synthetic log with one planted error, and its token counts are local `o200k_base` estimates (basis `inferred`), not provider-reported usage. It shows what the model does; it is not a savings estimate for real sessions. ## When it does nothing trim-2 fails closed. It returns the context unchanged, with a reason, when: - the query is blank; - the ask is exhaustive: "review the whole file", "list all", "every line", "line by line", or a bare "continue", "yes", "ok", "go ahead", "ship it"; - the query is vague: fewer informative words than the point requires, and no code identifier, compound term, or file name; - the context is under 512 bytes, or is an active source file under the point's smallest code file size; - the context is over 8 MiB or 200,000 lines; - the context already has a line that reads as an elision marker; - the cut would remove less than 5% of the bytes; - the operating point is unknown or the embedded model fails to load. From the same fixture: `"continue"` and `"review the whole log"` come back unchanged as exhaustive asks, and `"ok fix it"` as a vague one. ## How the proxy uses it In `compress` mode the proxy pairs trim-2 with the structural Engine on each live `tool_result` block. The Engine handles format-aware work (JSON, CSV, HTML, config, test reports); trim-2 handles line selection. 1. Explicit whole-file code reviews (e.g. "review this entire file line by line") fail closed verbatim on source code before any body elision runs. 2. Otherwise the structural Engine compresses the block first, with the human ask as its query. 3. The bare human ask (with `` and IDE harness envelopes stripped) goes through trim-2's exhaustive and vague checks before any enrichment, so tool metadata cannot turn a "continue" into a scoring query. 4. Each `tool_result` block gets its own chronological scoring query derived strictly from the messages before that block: the assistant turn that issued its matching `tool_use_id` (tail text plus that tool call's `file_path`, `path`, `pattern`, `command`, `query`, `glob`, `symbol`, `url`, `target`, or `filename` argument) followed by the preceding human ask, up to 2,048 bytes. Parallel tool calls never cross-pollinate, and tool results never feed the query. 5. `trim_level` decides when trim-2's cut competes with the Engine's: | `trim_level` | trim-2 runs | |---|---| | `off` | Never | | `conservative` | Only when the Engine passed the block through (excluding `json`, `tabular`, `html`) | | `balanced`, `smart_max` | Never on `json`, `tabular`, `html`; fallback on `config`, `test-report`; query-aware override on `code`; best-of on line-oriented text, logs, diffs, terminal and search output | | `aggressive`, `max` | Never on `json`, `tabular`, `html`; query-aware override on `code`; best-of on all other line-oriented outputs | 6. On best-of (non-`code`), trim-2 wins only when it beats the Engine's result by at least 5% and at least 16 tokens. On `code`, trim-2 is preferred over the structural body-elider whenever trim-2 reduces tokens, keeping relevant function bodies verbatim instead of eliding every body query-agnostically. 7. A trailing `` envelope is cut off before trimming and reattached verbatim. 8. The original block goes to CCR before the smaller one is sent. No store, no trim. 9. The decision is memoised in the PrefixCache under a key scoped to both the level and a digest of the block's chronological query (`|trim2:|q:`). Because a block's chronological query depends only on messages before it, frozen history stays byte-identical across turns (zero cache busts), while a different session asking a different question about the same file never replays the first session's query-trimmed cut. A `tool_result` that answers the agent's own `caveman_retrieve` call is never compressed. ## Configuration | Setting | Values | Default | |---|---|---| | `trim_level` in `caveman.yaml`, or `CAVEMAN_TRIM_LEVEL` | `off`, `conservative`, `balanced`, `smart_max`, `aggressive`, `max` | `smart_max` when `savings_profile` is `max` (the `compress` mode default); `balanced` under `standard` | An unknown value fails closed to `off`. `record` mode never transforms anything, whatever the level. The proxy's startup log line records the effective `savings_profile`, `trim_level`, and `epoch_compact`. From Go, call the package directly: ```go import "github.com/JuliusBrussee/caveman/engine/trim2" res := trim2.Compress(context, query, trim2.Options{Point: "smart_max"}) if res.Unchanged { log.Println("trim-2 passed through:", res.Reason) } fmt.Print(res.Output) ``` `trim2.Score(context, query)` returns every line with its keep probability, for callers that want to make the selection themselves. ## Speed Measured 2026-11-29 with the package's own benchmarks on one core of an Apple M5 Max, Go 1.26.11, five runs each, median reported: ```bash go test ./engine/trim2/ -run '^$' -bench BenchmarkCompress -benchmem -count 5 -cpu 1 ``` | Benchmark context | Time per call | Allocated per call | |---|---:|---:| | Mixed log, code and prose, about 8 KB (`BenchmarkCompress2k`) | 4.7 ms | 0.65 MB | | Mixed log, code and prose, about 200 KB (`BenchmarkCompress50k`) | 96 ms | 13.9 MB | The benchmark sizes its contexts at 4 bytes per token, so "2k" and "50k" are approximate token counts. In these two runs, 25 times the input took about 20 times the time. ## Tests | Test | What it pins | |---|---| | `TestPredictionParity` | Go tree evaluation against the training library's own raw scores for both stages, bit for bit, on 256 rows of 174 features (`testdata/parity.bin`) | | `TestGolden` | Full `balanced` output on the log fixture (`testdata/golden.txt`) | | `Example_goldenLog` | Every figure in the worked example above | | `TestOperatingPoints` | Every point keeps the ledger error | | `TestCodeEditSpanContiguity` | Edit anchors and enclosing control guards survive in code | | `TestSmartMaxShapeAsymmetry` | `smart_max` equals `balanced` on code and `max` on logs, and is deterministic | | `TestViterbiAvoidsWastefulMarkers` | No marker over a line cheaper than the marker | | `TestRefusals`, `TestClassifyShapeAndSafetyGuards` | Fail-closed cases and shape detection | | `TestCRLFMarkers`, `TestFinalNewlineIsNotALine`, `TestClaudeReadGutterIndent` | Line endings and Claude Code's `N→` read gutter | | `TestTrim2EvalScorecard`, `TestTrim2RefusalAndSafetyInvariants` | 25-case dev suite and 8-case held-out real-repo quality gate (shape accuracy, monotonicity, CRLF invariance, Edit hunk contiguity, needle recall, and refusal/bounds invariants) | ## Limits - **No committed quality benchmark yet.** The tests above pin behavior, not answer quality. No reduction or quality figure for trim-2 on real agent sessions is published in this repository. The session-level [wrap benchmark](../WRAP-BENCHMARK.md) predates trim-2 and has not been re-run on 5.0. - **Line-level only.** trim-2 cannot shorten a long line. A minified JSON document on one line is the Engine's job, not trim-2's. - **Needs a query.** With no human ask it does nothing. - **Lexical at its root.** Every feature starts from words, identifiers, and structure. The 2-hop signal reaches one step past the query's vocabulary, not more. - **Training is not in this repository.** This repository ships the trained model, its feature code, and its parity fixture, not the training pipeline or data. - **Local counts are inferred.** Token figures use the Engine's offline `o200k_base` counter. See [Accounting and evidence](accounting-and-evidence.md). ## License Apache-2.0, like the rest of the repository. `model.go` includes Go's portable `math.Exp` under the BSD license in [`engine/trim2/LICENSE-go`](../../engine/trim2/LICENSE-go).