Synthesis of 4 parallel deep-research passes (agent-memory SOTA, production coding agents, KV-cache economics, retrieval methods). Supersedes the v1 prototype in CONTEXT_MEMORY.md. The v1 mechanical pruner is wrong (cache-hostile) — see §5.
All four research threads independently point to the same split:
- READ path — per turn, cheap, NO model call, cache-friendly. Assemble context fresh each turn by APPENDING to a stable prefix + a small curated suffix.
- WRITE path — lazy, background/idle, model-driven. Heavy extraction/consolidation runs at idle or epoch boundaries, NOT every turn.
The per-turn instinct (manage context every turn) is right for the read path; the batch design is right for the write path. It was never either/or — it's both, split by path. Evidence: Letta sleep-time compute = ~5× less test-time compute doing consolidation off the hot path; production coding agents all append-and-compact (not per-turn rebuild); small local models (Qwen) can't be trusted to self-compact well every turn.
Prefill (~156s/85k on our rig) is cached ONLY up to the first changed token. Rebuilding early tokens every turn = re-pay 156s every turn (~25–75× slower). So:
FROZEN PREFIX (compute once, cache forever — NEVER rewrite):
tool defs -> system prompt -> skill index -> durable project memory
-> append-only turn history
VOLATILE SUFFIX (cheap to recompute each turn — ALL curation happens here):
retrieved memory for THIS turn -> current state -> user message
Hygiene that silently kills the cache: no timestamps/UUIDs in the prefix, deterministic
JSON (sort_keys=True), deterministic tool order. Qwen is MORE position-sensitive than
Llama, so putting fresh retrieved evidence LAST (suffix) is doubly good: cache-cheap AND
in the high-attention recency zone. When ranking many items, use the CacheWeaver
pattern — fixed cacheable order + a "prioritize X,Y" instruction AFTER the block — instead
of reordering.
Measured: tool results = 90% of context. The fix everyone ships (Cursor, Claude Code):
- Cap tool output at source (~25k tokens, Claude Code's default) with pagination/ concise modes.
- Spill big outputs to a file, return a short handle:
[wrote 42k-char grep to .pit/scratch/grep_003.txt — read_file/grep it for detail]. The handle is tiny + stable → appends cleanly, never bloats, never breaks cache, and is re-fetchable. This replaces v1's in-place stub (which invalidated the cache from the edit point on). Spill-to-file is simultaneously anti-FLUFF (body leaves context) and anti-MISSING (body is on disk, re-fetchable). Prefer observation masking + re-fetch over LLM summarization of tool output — cheaper, and small Qwen summarizes unreliably.
- BM25/keyword ties or beats dense embeddings on OUR data (topic keys, typed facts, IDs, dates). Dense only wins on pure paraphrase. Skip the vector DB + embedding model.
- Agentic JIT is proven:
recall(query)/read_thread(id)tools; the model pulls what it needs. "Is Grep All You Need?" — grep beat vector for every model tested. - Retrieval for agent memory is a PRECISION problem, not recall — distractors actively hurt (topically-related-but-irrelevant is the WORST). Surface little + precisely.
- Auto-surface a FEW items via recency × importance × relevance scoring (Generative Agents, ablation-validated; recency is ~free from our timestamps).
- Skip graph memory unless real multi-hop failures appear (flagship numbers are disputed, ingestion cost brutal). Cheap explicit thread cross-links get most of the benefit.
- Render retrieved memory INLINE + tight (inline-vs-file flips results; small precise memory is cheap enough to inline; only big tool DUMPS go to file).
- Run the batch extractor at IDLE / epoch boundaries, not per turn (sleep-time evidence).
- ADD/UPDATE/DELETE/NOOP: ADD is reliable everywhere; UPDATE/DELETE is the weakest link in every system (Supersede/MemFail) → add a contradiction check before overwrite.
- Keep raw-segment pointers beside typed facts (TriMem: pure atomic-fact extraction is LOSSY — this is the MISSING failure mode, named). Never fully replace source with its distillation; keep a pointer back.
"Estimating importance without knowing future queries" + "consolidation without catastrophic loss" are explicitly unsolved (survey arXiv 2603.07670). No paper to copy. We can't solve it in general, but we DE-RISK both:
- anti-FLUFF: spill-to-file + surface-little-precisely + suffix-only curation.
- anti-MISSING: nothing is ever deleted (on disk, re-fetchable) + raw pointers beside facts + agentic recall so the model can always dig. Recoverability IS the safety net.
The memory literature ignores KV-cache economics; the cache literature ignores memory curation. We sit in the seam. The novel artifact: a memory manager whose every move respects prefix-stability — append-only handles, suffix-only retrieval, epoch-boundary consolidation, and a crude "is this edit worth the cache miss?" policy (only bust cache when projected token savings > recompute cost). Nobody ships this.
Anchor to MemoryArena-style agentic-task memory (does memory improve downstream ACTIONS), NOT LoCoMo (saturated; recall≠use — models acing it drop to 40–60% on decision tasks). Our _drive/_gen harness is already action-based — extend it with multi-session memory tasks.
- agentic+keyword, no vectors — CONFIRMED.
- aggressive distill, safe via recoverable store — PRINCIPLE SURVIVES (recoverability), MECHANISM CORRECTED: spill-to-file (not in-place stub, which is cache-hostile).
- free self-notes, no per-turn model call — REFINED: self-notes as a lightweight signal; heavy consolidation moves to idle/epoch (sleep-time), not every turn.
- prefix-stable append-only, rebuild only at epochs — STRONGLY CONFIRMED + quantified (25–75×).
- cache_probe.py = Experiment 0. Uses llama-server /completion
timings.prompt_n(freshly prefilled) vstimings.cache_n(reused) as ground truth. - metrics.py = trace analyzer for any session jsonl. Reports FLUFF (tool token-turns), MISSING (duplicate calls + same-target re-touch), COST (total token-turns), tool-share. Baseline (gen2 diagnosis): 91% of cost is re-sent tool output, biggest single 30k chars.
| move | KV reuse | prefill | verdict |
|---|---|---|---|
| append at end | 95.4% | 716ms | ✅ cheap, build on it |
| edit EARLY token | 0% | 4200ms | ☠️ never touch the prefix |
| edit near END | 80.6% | 1014ms | ✅ curate in the suffix |
| delete MID block | 0% | 4146ms | ☠️ full reprocess (cache-reuse off) |
KILLED: in-place tool-result stubbing (the v1 pruner — now disabled in loop.py) AND
mid-context eviction. VIABLE: spill-to-file (append-only handle), suffix-only curation,
epoch-rebuild. Optional future test: enable --cache-reuse 256 + re-run cache_probe to
see if contiguous mid-delete becomes viable on this model (known broken on qwen3-next).
- Exp 1 — spill-to-file: DONE, WIN (2026-07-04). tools.spill_result() keeps a 4k preview + spills the full dump to .scratch/ with a re-fetchable handle; gated by PIT_SPILL (default ON). Head-to-head on gen2 log-diagnosis: context 30,097→11,431 tok (−62%), fluff 25,003→6,670 tok (−73%), biggest dump 30k→4.1k chars, grade HELD (cert cause + red herring ruled out), MISSING stayed 0 (never re-fetched, but could). Single-turn so token-turns= context; multi-turn the saving COMPOUNDS (a spilled 30k dump not re-sent across N turns). Now default-on in pit.
- Exp 2 — cross-turn tool-result cache: DONE, NEGATIVE/inconclusive (2026-07-04).
Exact-match (name+args) cache to stop cross-turn re-fetch. Result: 0 cache hits — two
causes: (1) BUG — the mutation-detector regex matched bare '>' i.e. comparison operators
in analysis code (
if count>400), wiping the cache every call; (2) DESIGN FLAW — 0 byte- identical repeats that run; real re-fetches VARY in exact args (same target, different command), so exact-match structurally can't catch them. Verdict: wrong mechanism. Cache demoted to opt-in (PIT_TOOLCACHE=1, default off); regex bug fixed. LESSON: re-fetch is real but content-caching on an exact key is not the fix — solve it on the RETRIEVAL side (model recalls its prior FINDING from memory instead of re-querying the source), or a cross-turn "you already looked at X" nudge. Also: this run hit 128k chars / 35k tok and ~58k-token server context = the source of the observed 40 t/s (decode falls with depth). - Exp 3 — recall/memory over re-fetch: recall() tool + keyword over subject threads so the model pulls its earlier CONCLUSION instead of re-running the query. Measure re-touch ↓.
- Exp 4 — idle consolidation: batch at epoch boundary vs per-turn; measure cost + grade.
Earlier notes (HANDOFF.md, memory) claimed "SWA makes long-context generation flat/free."
llama-server logs disprove it on Qwen 3.6 Q4_K_P: decode ~56 t/s at ~0 ctx vs ~40 t/s at
~58k ctx (pure eval ... tokens per second, not an averaging artifact). ~28% decode tax by
58k, climbing with depth. This STRENGTHENS context management: lean context buys decode
speed AND prefill savings. TODO: map the full decode-vs-context curve (0/20/40/60/80/100k)
when the GPU is free, and fix the stale "flat" claim in HANDOFF.md + memory.