extract

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package extract is the cheap-model tool-output extractor. A small model returns a SMALLER value of the same shape (selecting records/fields, never paraphrasing); the containment validator here PROVES the result is a lossless projection of the original, so a chatty model can never corrupt a value the agent relies on. On any failure it falls back to a deterministic projection, then to the original (fail-open). Ported from the reference prototype's actions/llm_compact.py.

ponytail: the model returns the selected JSON directly and containment verifies it — no model-generated code (the reference prototype's Python sandbox) and no custom spec language. The containment proof is what makes the mechanism safe, whatever produced the subset.

Index

Constants

View Source
const AdjudicationHeadChars = 90

AdjudicationHeadChars bounds the locating line. Small on purpose: it exists to disambiguate which output a label refers to, not to inform the judgement, and every character of it is paid fresh.

View Source
const FallbackSampleChars = 2000

FallbackSampleChars bounds each output shown in the FALLBACK prompt. The whole point of that path is comparative judgement across every candidate, so the per-output budget must stay small enough that a long list plus the contract still fits a window.

Variables

View Source
var Modes = []string{"auto", "code", "single", "rlm", "deterministic"}

Modes are the values Cfg.Mode accepts, in the order a settings form should offer them. The empty string means "auto".

It is a declared list because the settings form used to carry its own copy, which had drifted: "deterministic" was missing, so a stored `strategy: deterministic` was not recognised, fell back to "code", and the next save WROTE `strategy: code` over it — silently turning an LLM-free configuration into one that makes model calls. Anything offering these values reads them from here; TestModesAreTheModesRawStrategyOrderHonors pins the list against the switch below.

View Source
var PromptVersion = promptFingerprint()

PromptVersion identifies the extractor's prompt + acceptance semantics. The result cache key includes it, so a change MISSES every stale entry rather than serving an extraction derived under different rules.

DERIVED, not hand-maintained. A manual constant only works if every future editor of the prompt remembers to bump it, and the one time someone forgets, the cache serves extractions produced under rules that no longer exist — exactly the failure the issue warned about, and one with no symptom to notice. Hashing the prompt text makes the version a consequence of the prompt instead of a promise about it.

Functions

func BuildFallbackAsk added in v0.1.1

func BuildFallbackAsk(goal string, items []AdjudicationItem) string

BuildFallbackAsk renders the question as a SELF-CONTAINED prompt: the contract, the goal, and a bounded sample of each output.

THIS IS THE EXPENSIVE PATH AND IT EXISTS ON PURPOSE. It is used only when the prefix ask could not read the cache — a first turn with nothing stashed yet, a diverged prefix, an expired entry, a route with no asker. `a9d666f` chose to fall back rather than skip, and the reason is worth restating: treating "no prefix" as "no verdicts" would disable the component on every session's FIRST turn and read, in the counters, as a model that declined to act.

What it costs is what the prefix ask exists to avoid: fresh tokens for content the cached path would have read for a tenth of the price, and a TRUNCATED view of each output rather than the whole thing. So it is counted every time it happens, and an operator who would rather forgo the yield than pay for it can switch it off with `block_fallback`.

func BuildPrefixAsk added in v0.1.1

func BuildPrefixAsk(items []AdjudicationItem) string

BuildPrefixAsk renders the adjudication question for a PREFIX ASK — a call whose prefix is the transcript the agent already sent, read from the provider's prompt cache.

THE DIFFERENCE FROM A CONTENT PROMPT IS WHAT IS NOT HERE: the outputs themselves. A bare completion has no way to show them except by shipping a truncated sample of each, which caps every candidate and forces the model to judge an excerpt. A prefix ask has the whole transcript above it, so shipping samples would pay fresh tokens for content already being read from cache AND show a TRUNCATED copy of something the model can read in full.

There is no `goal` parameter, and that is the point rather than an omission: the conversation IS the prefix, so what the agent is doing now is above the question already. Rendering it again would be paying fresh for a copy of cached bytes.

func ClipSample added in v0.1.1

func ClipSample(s string, max int) string

ClipSample bounds one output for the fallback prompt and MARKS the cut, so the model knows it is judging an excerpt of something larger and does not reason as though it had seen the end.

func ContentKey

func ContentKey(text string) string

ContentKey is a stable, marker- and whitespace-insensitive key for a body, so the same output re-sent on a later turn hits the extraction cache.

Memoized by a fast hash of the input, like internal/tokens.Count and for the same reason: every offloader asks skipReduce about every candidate, so one request normalizes and sha256s the SAME tool output three or four times over — two regexp rewrites of a 50 KB body each time. Bounded the same way (cleared wholesale past cap).

func DeterministicProject

func DeterministicProject(value any, keepIDs []string, maxChars int) any

DeterministicProject filters a parsed value to the keep-set + important-key spine. Never empties: a value that projects to nothing falls back to a truncated copy.

func HarvestIdentifiers

func HarvestIdentifiers(text string, cap int) []string

HarvestIdentifiers pulls distinctive identifiers (paths, symbols, ids, numbers) from the agent's recent turns — the keep-set the extractor must retain.

func HeadLine added in v0.1.1

func HeadLine(s string, max int) string

HeadLine returns a single-line, bounded opening of s, for locating an output in the transcript above. Newlines are collapsed so one candidate stays one line and the inventory stays readable to a model counting labels.

func IsContained

func IsContained(result, original any) bool

IsContained reports whether result is a lossless projection of original (both parsed values): string → an order-preserving **character subsequence** of the original (result must be obtainable by DELETING characters — so a filter may drop whole lines/records OR trim words/sentences/parts within a line, but can never fabricate, reorder, or reword; this subsumes substring and whole-line subsequence); list → order-preserving subsequence of contained items; dict → keys subset with contained values; numbers/bools/nil → equal where present; nil result → always allowed (dropping is fine).

func RepairStats added in v0.1.1

func RepairStats() (tried, fixed int64)

RepairStats reports how many syntax-repair round-trips were attempted and how many produced an accepted-by-the-sandbox program. tried-fixed is what the retry cost for nothing, and the ratio is the only honest basis for keeping it.

func ReplyWasTruncated added in v0.1.1

func ReplyWasTruncated(reply string) bool

ReplyWasTruncated reports whether an unparseable reply looks CUT OFF rather than malformed.

A reply that opened the array and never closed it ran out of output budget; one that never opened it is a genuine format failure. The remedies are opposite -- raise the budget versus fix the prompt -- so folding them under one name hid a 70%-of-calls failure behind a label that reads as "the prompt is wrong" (`659e7a6`). Only meaningful when ParseVerdicts returned false.

func ResultKey added in v0.1.1

func ResultKey(contentKey, model string, cfg Cfg) string

ResultKey is the GLOBAL cache key for a derived extraction result. Unlike a conversational reference (issue #27's xdedup index, which is deliberately session-scoped because "same as step N" only means anything in-session), an extraction is a CONTEXT-FREE derived result: the same bytes under the same extractor semantics yield the same reduction in any session. Measured on Terminal-Bench, 82 of 103 unique contents recurred ACROSS sessions, so a session prefix threw away ~80% of the reuse.

The key must include everything that materially changes the result, or a stale entry is served silently — which is worse than a miss, because nothing surfaces it:

  • contentKey: the content itself (marker/whitespace-insensitive)
  • PromptVersion: prompt + acceptance semantics
  • model: a different extractor model writes a different program
  • cfgFingerprint: the config fields that steer the result (mode, rewrite, floor)

A change to ANY of these misses rather than mis-serves. Changing the key schema invalidates existing entries exactly once — acceptable, and noted in the docs.

func RunExtraction

func RunExtraction(ctx context.Context, body, goal string, keepIDs []string, tokenEst int, cfg Cfg, model Model) (string, string)

RunExtraction tries strategies in order, returning the first candidate that is strictly smaller AND passes the validation gate, else ("", "none"). Fail-open: the caller keeps the original on "none".

func RunExtractionDetail added in v0.1.1

func RunExtractionDetail(ctx context.Context, body, goal string, keepIDs []string, tokenEst int, cfg Cfg, model Model) (result, summary, strategy, reason string)

RunExtractionDetail is RunExtractionSummary plus WHY it failed.

The three-value version reported "none" for every failure alike, and this file's own callers complain about it: a reply that never arrived, a program the sandbox rejected, a result that did not shrink and a result that failed the recall check are indistinguishable in the return value, and they have completely different fixes — raise the reply budget, fix the prompt, stop calling, loosen the keep-set. On a real session that cost four calls, ~$0.27 and 100 seconds to learn nothing at all, because every one of them just said "none".

reason is empty on success, and a short stable slug otherwise, per strategy tried.

func RunExtractionSummary

func RunExtractionSummary(ctx context.Context, body, goal string, keepIDs []string, tokenEst int, cfg Cfg, model Model) (string, string, string)

RunExtractionSummary is RunExtraction plus the one-line SUMMARY the "code" strategy's program optionally emitted (empty for the other strategies). The summary is used as the marker digest so the agent sees the gist of the elided output inline.

Types

type Adjudication added in v0.1.1

type Adjudication struct {
	// Drop is the only field that authorises an action, and it is true only when every check below
	// passed. Every other outcome leaves the output verbatim.
	Drop bool
	// VerdictUnusable marks a verdict we do not act on — absent, empty, or a value the contract does
	// not offer (`trim`, most likely, since it used to be offered).
	VerdictUnusable bool
	// RefusedObligation marks a drop we would not perform: the model named an outstanding obligation
	// and then dropped the output anyway. ALERTABLE — it means the model tried to remove something
	// it had itself just said was still needed.
	RefusedObligation bool
	// QuoteFabricated marks an obligation quote that is not in the transcript. ALERTABLE — it means
	// the model is inventing evidence, and on this design it is the ONLY such signal left, because
	// nothing else the model returns is content.
	QuoteFabricated bool
	// CriterionMissing marks a verdict that never answered needed_by. Tolerated, but counted: it
	// means the forcing function did not run for this verdict.
	CriterionMissing bool
}

Adjudication is what OUR code concluded, which is not the same thing as what the model said. Every field but Drop exists so a failure is COUNTED rather than inferred from a yield number.

func Judge added in v0.1.1

func Judge(v Verdict, transcript string) Adjudication

Judge turns ONE verdict into a decision, applying the four safety rules that make it actionable. transcript is the agent's own text, flattened, and is what an obligation quote is checked against — verifying the quote is cheap and turns "did it make that up?" from a worry into a counter.

EVERY FAILURE PATH RESOLVES TOWARD KEEP. That is not caution for its own sake: a wrong keep costs tokens on one turn, a wrong drop is a silent permanent loss the agent does not notice and cannot ask about. The two errors are not comparable, so the code does not treat them symmetrically. This is orthogonal to batch size — the same rules applied per-verdict whatever the batch was.

type AdjudicationItem added in v0.1.1

type AdjudicationItem struct {
	// Label is the ANSWER key: the small integer the model must put in "i", and the only thing it is
	// asked to reproduce.
	//
	// An integer for a measured reason. Asked to answer with opaque tool_use ids the model REGULARISED
	// them -- `toolu_01..07` for `toolu_probe_00..07` -- because reproducing a random identifier from
	// thousands of tokens back is a copying task, not a judgement. With integer labels it was 0 bad
	// labels in 40+ trials. The rule generalises: give the model short things it cannot get wrong and
	// keep every mapping on our side.
	Label int
	// ID is the tool-call id, and it is the EXACT anchor between an inventory line and the content the
	// model is reading from cache. Shown, but never asked for.
	//
	// THE TWO AIDS HAVE SEPARATE JOBS, and conflating them is a mistake available in both directions.
	// Label above is what the model ANSWERS with; this is what it LOCATES with, and it is never asked
	// to reproduce it. The measurement behind integer labels says the answer key must be an integer --
	// it says nothing about whether an id may appear in the prompt, and the echo risk it describes was
	// always about what the model RETURNS rather than what it reads.
	//
	// Withholding it costs the one exact anchor there is. The id appears in the transcript the model
	// reads from cache, so shipping it makes an inventory line and a tool result identifiable to each
	// other; without it, head-plus-size is the only matching signal, and that is shaky on a transcript
	// carrying a dozen near-identical `Read` results.
	ID         string
	SizeTokens int
	// Head is a single bounded line so the model can LOCATE this output in the transcript above.
	// Not a sample of it: the model reads the output in full from cache, and an excerpt would be a
	// worse version of something it already has.
	Head string
	// Sample is a bounded excerpt used ONLY by BuildFallbackAsk, on the path where the cache read did
	// not happen and the model therefore cannot read the output from anywhere. Empty on the prefix-ask
	// path, which is what keeps the content off the wire there.
	Sample string
	// Evidence is a rendered reference-tracking record for this output. It goes into the inventory line
	// when non-empty and is omitted entirely when not.
	//
	// A SEAM, deliberately empty on `main`. There is no co-reference index here, so nothing populates
	// it and the contract says nothing about how to read one -- a prompt that taught the model to
	// interpret counters the prompt never carries would be teaching it to read a field that does not
	// exist. A field rather than a future signature change, because the alternative is reshaping the
	// contract when the index arrives, and the contract is the part with measurements attached to it.
	Evidence string
}

AdjudicationItem is one candidate named in the inventory. Note what it does NOT carry to the model: the output itself. Content is held only so the caller can resolve a label back to a message.

type Aggressiveness added in v0.1.1

type Aggressiveness string

Aggressiveness names the compaction target. Empty means AggroMedium.

const (
	AggroLow    Aggressiveness = "low"
	AggroMedium Aggressiveness = "medium"
	AggroHigh   Aggressiveness = "high"
)

The compaction targets. The percentages are a target for the MODEL, not a guarantee and not a gate: the acceptance checks (verbatim ids/paths/errors, strictly smaller, and in deletion-only mode the subsequence proof) are unchanged at every level, so a higher level asks for more and never buys it by weakening what must survive.

func ParseAggressiveness added in v0.1.1

func ParseAggressiveness(s string) (Aggressiveness, error)

ParseAggressiveness validates a configured level; empty means medium.

type Cfg

type Cfg struct {
	Mode  string // auto | single | rlm | deterministic
	Floor int    // token floor; rlm kicks in at max(floor*4, 8000) in auto
	// MinKeepRatio is the fraction of the body the result must still contain. 0 disables the
	// blunt ratio backstop and leaves only the keep-set check, which is not enough on its own:
	// see minKeepRatioFloor for the live failure that proved it.
	MinKeepRatio       float64
	AllowDeterministic bool
	MaxChars           int // deterministic projection window
	// AllowedStrategies, when non-empty, restricts strategyOrder to these strategy names
	// (code | single | rlm | deterministic) preserving the computed order. Empty means
	// "all" — prior behavior. Lets config enable/disable strategies purely by name.
	AllowedStrategies []string
	// Rewrite opts out of the containment proof (deletion-only guarantee): the model
	// may reword/summarize/rewrite freely. Lossy + unverified — the caller must accept
	// that (e.g. a non-full marker_mode). Default false keeps the verified guarantee.
	Rewrite bool
	// CacheContext moves the conversation context into a trailing CACHEABLE system block
	// instead of the user message. Worth it only when the request will make MORE THAN ONE
	// call: the context is identical across a request's candidates, so calls 2..N read it
	// instead of re-sending it — but a cache WRITE costs 1.25x fresh, so paying it for a
	// single call is a 25% loss. The caller decides; default false keeps the old placement.
	//
	// Measured on production: five haiku calls on ONE request each sent ~138,000 prompt
	// tokens with cache_read=0 and cache_write=0, the same transcript five times over.
	CacheContext bool
	// Aggressiveness selects the compaction target taught in the second system block
	// (low | medium | high; empty = medium). It changes what the model is ASKED for, never
	// what is ACCEPTED — the verbatim-preservation, strictly-smaller and (in deletion-only
	// mode) subsequence checks are identical at every level.
	Aggressiveness Aggressiveness
}

Cfg configures extraction.

func DefaultCfg

func DefaultCfg() Cfg

DefaultCfg mirrors the reference prototype's ExtractCfg defaults.

type Model

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

Model is the cheap-model client the extractor calls. The host (proxy / plugin) injects a concrete implementation; the extractor core stays transport-free.

type SystemBlocksModel added in v0.1.1

type SystemBlocksModel interface {
	CompleteBlocks(ctx context.Context, system []string, prompt string) (string, error)
}

SystemBlocksModel is the further optional capability: send the invariant instructions as SEVERAL ordered blocks, so a provider can cache each prefix separately. It exists because the general contract is identical for every tenant while the aggressiveness block is not, and one joined string would give the two a single cache key — making the shared half unshared the moment two tenants pick different levels.

type SystemModel added in v0.1.1

type SystemModel interface {
	CompleteSystem(ctx context.Context, system, prompt string) (string, error)
}

SystemModel is the optional capability a Model may also implement: send the invariant instructions as a separately-cacheable stable prefix. cheapmodel's Anthropic (a `system` block + cache_control) and OpenAI (a leading system message) both do. A Model that does NOT implement it still works — the extractor falls back to the single-message prompt — so this is additive, not a breaking interface change.

type Verdict added in v0.1.1

type Verdict struct {
	Label    int    `json:"i"`
	Verdict  string `json:"verdict"`   // keep | drop
	NeededBy string `json:"needed_by"` // a | b | c | none  (see adjudicationContract's CRITERION)
	Quote    string `json:"quote,omitempty"`
}

Verdict is one decision. Note what is NOT in it: any field carrying output content. A parse that succeeds cannot produce text to splice, which is what makes the transport failure mode unreachable rather than merely guarded.

func ParseVerdicts added in v0.1.1

func ParseVerdicts(reply string) ([]Verdict, bool)

ParseVerdicts reads the model's reply, returning the verdicts and whether the reply PARSED.

THE TWO MUST STAY DISTINGUISHABLE, and `4ca1f13` is the commit that separated them. An EMPTY array is a legitimate answer -- "keep everything", which the contract explicitly invites -- while unparseable output is a prompt or model failure. Folding both into "no verdicts" made a deliberate keep-all indistinguishable from junk in the counters, and those counters are the only way to tell "the model declined to act" from "the model was never successfully asked", which is exactly the distinction one live arm turned on.

Jump to

Keyboard shortcuts

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