# MYELIN: Budget Prompting for Persistent Memory Agents: v1.9 → v2.0

From v1.9 (29 Jul) to v2.0 (25 Nov): 15,173 words to 15,810 words, 681 words in new or rewritten paragraphs and 44 taken out, 49 paragraphs changed.

## Change note of v2.0

**Cost is now measured per model call**

The cost metrics now count each model call, not each conversational turn, because one turn can hold many calls. The improvement notes give the reason: the authors' system started recording every call separately.

- A count the provider did not report is left out, never written as zero.
- The context sent with each call is broken down by source before the call.
- The limitations add that the per-call record is live only, so studies over past weeks must use the slower usage ledger.
- The rest is wording and list layout.

## Changed paragraphs

Marks: [-removed-] {+added+}.

### Abstract

Thirteen of these techniques are implemented and [-battle-tested-] {+in daily use+} in TinkerClaw, a fork of the OpenClaw agent framework running a personal assistant (Jarvis) 24/7 since January 2026. Seven are designed but not yet shipped, informed by analysis of the Hermes Agent architecture and our own continuous compaction research. We report real cost data, cache hit rates, and failure modes from three months of production operation.

### Contributions

1. **A taxonomy of 20 Budget Prompting techniques**, organized into five categories with implementation status, expected savings, and interaction effects. 2. **Production cost data** from a real 24/7 agent deployment, including per-technique attribution where measurable. 3. **The prefix stabilization principle**: a formalization of why prompt caching and memory writes are fundamentally in tension, and architectural patterns to resolve it. 4. **Evaluation framework** for measuring cost reduction without quality degradation, including proposed metrics for cache efficiency, context density, and personality [-drift.-] {+drift, all computed from a per-call usage record and a pre-call composition of the context.+} 5. **Composition analysis**: how techniques interact, which combinations are synergistic, and which create conflicts.

### 2.5 Industrial Convergence — Evidence from the Claude Code Source Exposure

One caveat on provenance: this is leaked code, not documentation Anthropic stands behind, and a few figures [-(notably the-] {+(the+} daily-waste number and the default output cap) come from secondary analysis of the dump rather than a line we can point to. We mark those as reported-but-unconfirmed where they appear.

### A2. Extended Thinking Control

{+Control thinking budget explicitly:+}

### A2. Extended Thinking Control

[-Control thinking budget explicitly:-] - `thinking: off` — No extended thinking. Suitable for simple responses, heartbeats, formatting tasks. - `thinking: low` — Minimal reasoning budget (~1,024 tokens). Suitable for moderately complex tasks, sub-agent work. - `thinking: high` — Full reasoning budget. Reserved for genuinely hard problems.

### B1. System Prompt Caching

{+For a 18K-token system prompt:+}

### B1. System Prompt Caching

[-For a 18K-token system prompt:-] - Uncached: 18,000 × $3/MTok = $0.054/turn - Cached: 18,000 × $0.30/MTok = $0.0054/turn - Savings: $0.049/turn × 200 turns = **$9.72/day**

### B1. System Prompt Caching

**The dynamic boundary, in two codebases.** The prefix-discipline this technique depends on shows up as an explicit marker in both the system we run and the leaked Claude Code source. TinkerClaw splits every system prompt at a `__PREFRONTAL_CACHE_BOUNDARY__` sentinel (`src/fork/prompt-cache-boundary.ts`): the text before the marker becomes a single content block carrying `cache_control: { type: "ephemeral" }`; everything after it is emitted as an uncached block that may change each turn. The split is the operational form of "keep the prefix static" — dynamic context is physically moved past the cache line rather than mixed into it. Claude Code does the same with a `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` sentinel (`constants/prompts.ts`): everything before it is globally cacheable (shared across sessions when `shouldUseGlobalCacheScope()` is on), per-session content goes after, and the helper that emits an uncacheable section is named to warn — `DANGEROUS_uncachedSystemPromptSection()` (`constants/systemPromptSections.ts`). Two systems, the same line drawn in the same place: strong evidence {+that+} the principle in Section 8.1 {+matters, not that it+} is [-load-bearing, not aesthetic.-] {+a matter of taste.+}

### B1. System Prompt Caching

**Three slabs, three breakpoints.** Anthropic assembles the cached prefix in a fixed order — **tools → system → messages** — and allows up to four `cache_control: { type: "ephemeral" }` breakpoints. Each breakpoint marks the end of a stable span; everything before it is reused on a hit. The seam [-is load-bearing:-] {+matters:+} slow-changing context (tool definitions, persona, skills, memory) belongs *above* a breakpoint and per-turn context (live turn, heartbeat, dynamic state) *below* it, because a single volatile token below the last breakpoint that is placed too high would invalidate everything after it. The tool-definitions array is the front slab — large, stable, and re-sent every turn — yet it is the one most often left uncached. TinkerClaw places a breakpoint on the last tool definition so the entire tool catalog is cached as one prefix: `applyAnthropicCacheControlToTools` attaches `cache_control` to `tools[tools.length - 1]` (`src/agents/anthropic-payload-policy.ts`), alongside the system-prefix breakpoint at the boundary marker and a breakpoint on the last user message. Three of the four available breakpoints are spent, each closing one stable slab.

### B1. System Prompt Caching

[-![Figure 1. The-] {+![The+} tools-to-system-to-messages cached prefix. Anthropic assembles the prefix in a fixed order and allows up to four ephemeral cache breakpoints; TinkerClaw spends three of them — one closing the tool-definitions array, one at the system-prompt boundary, one on the last user message. Everything above a breakpoint is reused on a cache hit; the volatile per-turn content lives below the final breakpoint. A single dynamic token placed above a breakpoint invalidates every span after it, which is why slow-changing context is hoisted above the seam and live turn state is pushed below it.](images/fig-cache-prefix-tinker.png)

### B2. Aggressive Session Management

The solution: start new sessions aggressively. New topic? New session. Context approaching threshold? New session. The agent's persistent memory files [-ensure-] {+carry+} continuity across sessions — that's what they're for.

### B3. On-Demand Retrieval over Bulk Loading

**Status:** [Y] Implemented for both surfaces. Memory files are searchable via semantic search; the system prompt injects only a curated [-subset: - Core identity (SOUL.md) — always loaded (~1K tokens) - Today's memory file — always loaded (~1–3K tokens) - Yesterday's memory file — always loaded (~1–3K tokens) - Tool guidance (TOOLS.md) — always loaded (~2K tokens) - Everything else — retrieved on demand via `memory_search()`-] {+subset:+}

### B3. On-Demand Retrieval over Bulk Loading

{+- Core identity (SOUL.md) — always loaded (~1K tokens) - Today's memory file — always loaded (~1–3K tokens) - Yesterday's memory file — always loaded (~1–3K tokens) - Tool guidance (TOOLS.md) — always loaded (~2K tokens) - Everything else — retrieved on demand via `memory_search()`+}

### B4. Context Compaction

**Two distinct operations, not one.** Compaction is easy to treat as a single step, but the Claude Code source separates two operations whose distinction is worth importing. *Summarization* (lossy, [-comprehensive)-] {+broad)+} compresses a span of conversation into prose — Claude Code calls this Context Collapse, gated behind a `CONTEXT_COLLAPSE` feature flag in `services/compact/autoCompact.ts`. *File extraction* (lossless, selective) pulls exact facts out to a file that lives outside the summary — Claude Code's Session Memory (`services/SessionMemory/`) does this. The two have different failure modes: summarization can hallucinate or drift; extraction can only omit. A precise compaction tier should run both — extract the facts you must not lose, then summarize the rest — rather than forcing everything through one lossy pass. We recommend B4 implementations expose extraction and summarization as separate stages.

### B6a. Content-Type-Specific Compression (Typed Compressors and Reversible Retrieval)

**Interaction effects:** Strict generalization of B6 — every B6 interaction [-(synergy-] {+(fit+} with B2, complement to B4) carries over. Synergistic with B8 (rolling window): CCR's cached-original-plus-retrieve is the same shape as B8's vector store, and a typed compressor feeding a retrieval store is a natural unification of the two. Tension with caching (B1): retrieval injects variable content per turn, so retrieved spans must live *after* the cache boundary, exactly as B8's retrieved turns do.

### B8. Rolling Window + Vector Retrieval

{+This creates a hybrid memory model:+}

### B8. Rolling Window + Vector Retrieval

[-This creates a hybrid memory model:-] - **Working memory:** Last 5–8 turns, always in context (recency) - **Episodic memory:** All past turns, retrievable by relevance (semantic search) - **Context budget:** Fixed, regardless of conversation length

### C1. Silent Reply (NO_REPLY / HEARTBEAT_OK)

{+TinkerClaw defines sentinel responses:+}

### C1. Silent Reply (NO_REPLY / HEARTBEAT_OK)

[-TinkerClaw defines sentinel responses:-] - **`NO_REPLY`** — The agent has nothing to say. Zero meaningful output tokens. - **`HEARTBEAT_OK`** — Acknowledgment of a heartbeat check. Minimal output.

### D3. Dual-Account Pool Staggering

**Mechanism:** Anthropic's flat-rate plans reset weekly. A single account hits its limit mid-week, leaving the agent degraded for 2–3 days. Two accounts with staggered reset days (e.g., one resetting Sunday, one resetting Friday) [-ensure-] {+keep+} at least one account [-always has budget.-] {+with budget at all times.+}

### F1. Security Scanning on Memory Writes

{+Defense: regex-based scanning of all memory writes:+}

### F1. Security Scanning on Memory Writes

[-Defense: regex-based scanning of all memory writes:-] - Block strings matching system prompt patterns (`<system>`, `[INST]`, `you are`, `ignore previous`) - Block base64-encoded payloads above a size threshold - Block known prompt injection patterns from public datasets - Alert on suspicious writes that don't match known patterns

### 4.1 The Request Lifecycle

[-![Figure 2. The-] {+![The+} Budget Prompting request lifecycle. An incoming request is classified for model and thinking budget (A1, A2), assembled with a frozen memory snapshot and search-based injection (B5, B3), pruned and compacted if oversized (B6, B4, B7, B2), checked against the prompt cache (B1) and the token-bucket pacer (D4, D3), run through inference with output controls (C1), and finally writes memory to a staging area with a security scan (B5, F1) before updating pacing accounting.](images/fig-pipeline-tinker.png)

### 4.2 Budget Pressure Cascade

[-![Figure 3. The-] {+![The+} five-level budget pressure cascade. As 7-day rolling utilization climbs from GREEN (<50%) to CRITICAL (>95%), the system progressively downshifts model tier, disables extended thinking, and skips lower-priority work. Each level inherits every restriction below it; critical cron jobs run at all levels, background jobs are the first to be dropped.](images/fig-cascade-tinker.png)

### 4.3 The Caching Stability Core

[-![Figure 4. Techniques-] {+![Techniques+} arranged as concentric rings around the caching stability core. Ring 0 (B1 + B5) establishes the stable prefix; each outer ring — context management, request routing, output control, temporal smoothing, protection — operates without disturbing the prefix beneath it. Distance from the centre tracks how directly a technique touches the cached prompt.](images/fig-rings-tinker.png)

### 4.4 Interaction Matrix

{+**Strong synergies:**+}

### 4.4 Interaction Matrix

[-**Strong synergies:**-] - B1 + B5: Frozen snapshots maximize cache hit rate. This is the highest-value pair. - A1 + A2 + C1: Cheap model + no thinking + silent reply = minimum possible cost per turn. - B6 + B4 + B7: Surgical pruning → compaction → iterative compression forms a staged cost reduction pipeline. - E2 + A1: Sub-agents on cheap models — delegated work at minimum cost. - D3 + D4: Dual accounts + pacing — availability insurance.

### 4.4 Interaction Matrix

{+**Tensions:**+}

### 4.4 Interaction Matrix

[-**Tensions:**-] - B5 (frozen snapshot) vs. memory freshness: The agent can't see its own memory writes within a session. - B2 (session restart) vs. conversational flow: Frequent restarts feel disruptive to users. - D4 (pacing) vs. responsiveness: Paced requests may be delayed. - A1 (cheap models) vs. quality: Haiku is noticeably less capable than Sonnet for complex tasks.

### 4.4 Interaction Matrix

[-![Figure 5. The-] {+![The+} technique interaction map. Solid edges mark synergies (combined effect exceeds the sum of parts), dashed edges mark tensions (one technique undermines another). The densest [-synergy-] cluster {+of synergies+} is the caching core (B1–B5–B6); the principal tensions all trace back to prefix stability versus freshness, responsiveness, or quality.](images/fig-composition-tinker.png)

### 5.1 Cost Metrics

{+**The unit of measurement is the model call.** A conversational turn can hold many internal calls (tool rounds, retries, sub-agent hand-offs), and a usage figure summed over them is neither the resident context nor the cost of any one request. Section 6.4 shows what goes wrong when a gate reads such a sum. Every metric below is therefore computed from a per-call record with three phases:+}

### 5.1 Cost Metrics

{+- **Send.** Written at the moment the request leaves, with the call's index within its lane and its provenance (which session, which run, which round). - **Usage.** Written when the provider reports tokens. Fresh input, cache read, cache write and output are stored as four separate parts and never pre-summed, so cache share and fresh-input share can be recomputed later without guessing how a total was formed. - **End.** Written when the call closes, with its outcome.+}

### 5.1 Cost Metrics

{+A count the provider did not report is left out of the record, never written as zero. A zero claims a measurement; an absence admits there was none, and every ratio below must be able to tell the two apart. An agent runtime that exposes no pre-request hook cannot write the send phase; its records start at usage, and latency metrics must skip it rather than fill the gap.+}

### 5.1 Cost Metrics

{+**Pre-call composition.** Before each call, the context about to be sent is itemised by contributor: system prompt, standing rule pack (the agent's ethical rules and conventions, injected on every call), injected memories, conversation history, tool results, and the current request. The composition is stored per (run, round), so a revision can cite what the input of a given turn was made of, contributor by contributor, from rows written before the call rather than reconstructed after it. The rule pack gets its own line because it is fixed per session but large, and it is the slab an operator is most tempted to grow. The first call of a session must be itemised as well. It carries the coldest cache and the full prefix, and a sampler that skips it under-reports exactly the expensive case.+}

### 5.1 Cost Metrics

{+**Ledgers as rows.** The context-budget ledger (every eviction, compaction and trigger decision) and the prompt-cache ledger (every cache read and write) are written as structured outcome rows in the same store as the per-call record, with past log lines backfilled, so one query can join a budget decision to the calls before and after it. The cache-read share is computed only over calls that measured their cache reads; a call with no cache figure is excluded from both numerator and denominator instead of counting as a miss.+}

### 5.1 Cost Metrics

{+**Savings from an eviction.** When a slab is dropped from context, its saving is its size summed over the calls that follow the drop, for as long as the session would otherwise have carried it. An earlier formula (tokens evicted × turns in the session) also charged each drop against the turns before it and overstated the saving. Figures computed that way are not comparable with this definition and are not used in this paper.+}

### 5.1 Cost Metrics

**Tokens per turn (TPT).** Average input + output tokens per conversational turn, retained as a descriptive metric rather than the primary cost proxy. It [-must come from-] {+is the sum of the turn's+} per-call [-telemetry;-] {+records, never+} a turn-aggregate `usage` [-field-] {+field. Its input side+} is [-unsafe. Decomposed into: - System prompt tokens (fixed per session) - Conversation context tokens (growing) - Tool output tokens (variable) - Thinking tokens (output, variable) - Visible response tokens (output, variable)-] {+decomposed with the pre-call composition above:+}

### 5.1 Cost Metrics

{+- System prompt tokens (fixed per session) - Standing rule pack tokens (fixed per session) - Conversation context tokens (growing) - Tool output tokens (variable) - Thinking tokens (output, variable) - Visible response tokens (output, variable)+}

### 6.5 Industrial Convergence as Validation

This is not proof that the techniques save what we claim — convergence validates the *architecture*, not the *magnitudes*. Two independent designs can be equally wrong about cost. But when the design space is large and two teams land in the same corner of it, the corner [-is-] probably [-load-bearing.-] {+matters.+} We treat this as the next best thing to replication, and a direct prompt to run the ablations in Section 9.2.

### 7.5 OpenClaw

{+TinkerClaw is a fork of OpenClaw, which provides the foundation for several Budget Prompting techniques:+}

### 7.5 OpenClaw

[-TinkerClaw is a fork of OpenClaw, which provides the foundation for several Budget Prompting techniques:-] - Built-in compaction (`/compress`) — technique B4 - Sub-agent spawning with clean context — technique E2 - Memory file system with search — technique B3 - Session management — technique B2

### 8.2 The Composition Problem

{+No single technique provides the 3–5× cost reduction we claim. The reduction comes from composition:+}

### 8.2 The Composition Problem

[-No single technique provides the 3–5× cost reduction we claim. The reduction comes from composition:-] - Model routing saves 30% on automated work → 15% overall - Caching saves 80% on system prompt tokens → 20% overall - Session management prevents 3× context bloat → 30% overall - Silent replies save output tokens on 50% of turns → 10% overall

### 8.5 Limitations

{+**Live stream versus history.** The per-call record of Section 5.1 is published as a live stream for the operator's panel; nothing replays it. A study over dated windows must read the durable usage ledger, which keeps one row per call, and the pre-call composition rows, which are stored. The July cache figures in this paper were measured before the per-call record existed; they should be re-derived from per-call rows before they are compared with later windows.+}

### 9.1 Implementation of Proposed Techniques

3. **B6 (Surgical Tool Output Pruning):** [-Start with the measured free wins:-] {+First,+} remove line-number scaffolding, then address stale Read output and the currently unclaimed Bash-output slab. Preserve reversible retrieval for the long residency tail.

### 9.2 Rigorous Evaluation

{+A future revision will add:+}

### 9.2 Rigorous Evaluation

[-A future revision will add:-] - Controlled ablation studies for each technique category - Statistical analysis with confidence intervals - Quality metrics (SyncScore, task completion) with before/after comparison - Repeat cache-hit and reads-per-write measurements across dated [-windows-] {+windows, computed only over calls that measured their cache reads - Repeat the context anatomy from pre-call composition rows across main-session calls, not only sub-agents, with the standing rule pack reported as its own slab+} - Liveness assertions for every optimizer and telemetry producer (non-zero requests during active traffic) - **A public-benchmark accuracy-delta protocol, borrowed from headroom (§7.1).** Our weakest claim is "no degradation we have been able to observe," resting on a single deployment. headroom demonstrates a concrete, reproducible alternative: run the candidate configuration against standard benchmarks (GSM8K, TruthfulQA, SQuAD, BFCL) with and without each context-economics technique, and report the accuracy delta directly. This converts our subjective "no degradation observed" into a measured number for the techniques where it applies (B3, B4, B6, B6a, B8) — the compression/retrieval levers whose quality risk is exactly what a benchmark can isolate. The billing and reliability techniques (B1, D3, D4, E1) are not benchmark-measurable in this way and remain the province of our production data.

### 10. Conclusion

The second insight is compositional: **no single technique provides [-transformative-] {+large+} savings, but 20 techniques multiplied together do.** Budget Prompting is not a silver bullet — it's a toolkit. The value is in the systematic application of many small optimizations that compound.

### 10. Conclusion

We release this as a working paper from a real system, not an academic exercise. The techniques [-are battle-tested-] {+run+} in daily operation. The numbers are real, the failures are documented, and the path to further improvement is clear. We hope this taxonomy [-serves as-] {+is+} a practical guide for anyone building persistent agents who, like us, has stared at their API bill and wondered if there's a better way.
