01Problem
Context windows are a budget, not a pile, but they are usually packed by habit: top-k retrieval plus truncation. That silently drops a refund clause, keeps a stale memory, or lets an untrusted chunk sit next to instructions and pose as policy. Then the shorter prompt gets celebrated as a win. A shorter prompt that loses required evidence is a regression.
02Approach
A deterministic packing engine with versioned policies. A model is called only if you explicitly ask it to grade or compress.
- Three policies. Baseline (top-k and naive truncation), budget-aware (trust floor, freshness, dedup, reserved slots), and compressed (budget-aware, but an item that does not fit whole is compressed instead of skipped).
- A decision for every item. Each candidate is kept, cut, or compressed for a named reason. Instructions, the current task, and output constraints are reserved first. Evidence is labelled as untrusted data, not further instructions.
- Live turn. Pin a saved policy version (checked by hash), assemble without writing anything, then save the trace once the prompt has been used.
- Sufficiency grading. A task passes only when every expected fact is still in the pack.
03Key decision
Never promote a cheaper policy that drops required evidence. Assembly never calls a model. Compression keeps numbers, identifiers, and negations first. Near-duplicates are resolved by their distinctive tails, not by Jaccard score alone. A pinned item is placed regardless of trust, freshness, or duplicate checks.
04Architecture
- Candidates: instructions, task, constraints, retrieval, memory, tools, state
- Pinned policy version
- Eligibility: trust floor, freshness, dedup
- Score and allocate budget, reserving protected items
- Fits whole? Keep. Otherwise compress (compressed policy) or skip
- Assembled pack + decision trace
- Sufficiency grade: did the required facts survive?
The core lives in src/lib/context-os/: engine.ts for assembly, compression, and grading, and fixtures.ts for the demo tasks and the three policy presets.
05Results
| Policy | Required facts survive | Mean input tokens | vs baseline |
|---|---|---|---|
| Baseline | 4 of 9 | 637 | 100% |
| Budget-aware | 8 of 9 | 353 | 55% |
| Compressed | 9 of 9 | 374 | 59% |
The one task budget-aware still loses is the invoice task: only compression keeps the identifier that naive truncation and whole-item skipping both drop. Results on live traffic: to come.