v1.1 → v1.2
What changed from v1.1 to v1.2
From v1.1 (31 Mar) to v1.2 (2 Jun): 9,904 words to 11,984 words, 2,086 words in new or rewritten paragraphs and 6 taken out, 58 paragraphs changed.
Adds evidence from the leaked Claude Code sourceThis version adds four sections on the Claude Code source code that leaked in March 2026. The authors read its compaction and budget code and found the same three-layer design the paper proposes. The paper's own notes give the leak as the reason for the revision.
- New sections: industrial convergence (2.5), when to stop spending (4.5), the leak as validation (6.5) and a related-work entry (7.8).
- The abstract now names the leak as outside evidence.
- About 2,000 words added; almost nothing removed.
v1.1 · 31 March 2026v1.2 · 2 June 2026
··· 1 unchanged paragraph folded ···
v1.1 · MYELIN: Budget Prompting for Persistent Memory Agents**Authors:** Oscar Serra, Jarvis (TinkerClaw) **Date:** March 2026 (v1.1) **Internal codename:** MYELIN **Keywords:** budget prompting, token economics, persistent agents, prompt caching, context management, cost optimization, LLM billing, agent architecture
v1.2 · MYELIN: Budget Prompting for Persistent Memory Agents**Authors:** Oscar Serra, Jarvis (TinkerClaw) **Date:** June 2026 (v1.2) **Internal codename:** MYELIN **Keywords:** budget prompting, token economics, persistent agents, prompt caching, context management, cost optimization, LLM billing, agent architecture
··· 6 unchanged paragraphs folded ···
not in v1.1
v1.2 · AbstractA new section in this revision draws on the March 2026 Claude Code source exposure — Anthropic shipped a 59.8 MB source map in `@anthropic-ai/claude-code@2.1.88`, exposing ~512,000 lines of TypeScript. We examined the relevant compaction and budget code directly. The leak is strong external validation: Anthropic's production agent independently arrived at the same three-tier compaction architecture MYELIN proposes, and ships several techniques (cache-pinned micro-compaction, forked-agent cache sharing, diminishing-returns budget tracking) that we had theorized but not confirmed at scale.
··· 12 unchanged paragraphs folded ···
not in v1.1
v1.2 · 1. Introduction — The Cost Problem Nobody Talks AboutThis is not only a single-operator problem. The March 2026 Claude Code source exposure surfaced an internal figure: autocompact failures alone were reported to waste on the order of 250,000 API calls per day. Whatever the exact number, the direction is clear — getting compaction wrong is expensive even at a lab with deep pockets, and the waste scales with the size of the deployment. Budget-aware compaction is the lever that targets exactly this waste.
··· 28 unchanged paragraphs folded ···
not in v1.1
v1.2 · 2.5 Industrial Convergence — Evidence from the Claude Code Source Exposure### 2.5 Industrial Convergence — Evidence from the Claude Code Source Exposure
not in v1.1
v1.2 · 2.5 Industrial Convergence — Evidence from the Claude Code Source ExposureIn March 2026 Anthropic accidentally published a 59.8 MB source map inside the npm package `@anthropic-ai/claude-code@2.1.88`, exposing roughly 512,000 lines of unobfuscated TypeScript. We read the compaction, budget, and prompt-assembly code directly (file paths cited below are from that tree). It is the closest thing the field has to a look inside a production agent at scale, and it independently confirms the core architecture MYELIN proposes.
not in v1.1
v1.2 · 2.5 Industrial Convergence — Evidence from the Claude Code Source ExposureThe most striking finding is convergent design. Claude Code organizes context management into three tiers that map almost one-to-one onto MYELIN's:
not in v1.1
v1.2 · 2.5 Industrial Convergence — Evidence from the Claude Code Source Exposure| MYELIN tier | Claude Code equivalent | Source | |---|---|---| | Continuous indexing (B6) | MicroCompact — per-tool-result clearing during the conversation | `services/compact/microCompact.ts` | | Per-turn / per-session retrieval (B4) | Session Compact — full-history summarization via a forked agent | `services/compact/compact.ts`, `sessionMemoryCompact.ts` | | Sleep consolidation (cf. J5) | autoDream — idle-triggered background consolidation | `services/autoDream/autoDream.ts` |
not in v1.1
v1.2 · 2.5 Industrial Convergence — Evidence from the Claude Code Source ExposureTwo teams with no contact arriving at the same three-tier structure is evidence that the structure is demanded by the problem, not chosen by taste. The leaked code also resolves several questions MYELIN left open — cache-pinned micro-compaction (B1/B6), forked-agent cache sharing (B4), and a diminishing-returns budget tracker (Section 4) — each now grounded in shipping code rather than projection. We thread these into the relevant technique descriptions below and revisit them as validation in Section 6.5.
not in v1.1
v1.2 · 2.5 Industrial Convergence — Evidence from the Claude Code Source ExposureOne caveat on provenance: this is leaked code, not documentation Anthropic stands behind, and a few figures (notably 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.
··· 4 unchanged paragraphs folded ···
v1.1 · 3. Taxonomy of Budget Prompting Techniques| # | Technique | Category | Status | Est. Savings | |---|-----------|----------|--------|--------------| | A1 | Model routing by complexity | Model Routing | ✅ | 25–40% automated | | A2 | Extended thinking control | Model Routing | ✅ | $5–10/day equiv. | | A3 | Cross-model delegation | Model Routing | ✅ | Variable | | B1 | System prompt caching | Context Econ. | ✅ | $8–10/day | | B2 | Aggressive session management | Context Econ. | ✅ | 2–4× per turn | | B3 | Memory search over bulk loading | Context Econ. | ✅ | 80–95% context | | B4 | Context compaction | Context Econ. | ✅ | 60–80% context | | B5 | Frozen snapshot injection | Context Econ. | 🔲 | CHR 65%→90%+ | | B6 | Surgical tool output pruning | Context Econ. | 🔲 | 30–40% context | | B7 | Iterative summary compression | Context Econ. | 🔲 | 5–15K tokens | | B8 | Rolling window + vector retrieval | Context Econ. | 🔲 | Fixed context cap | | B9 | Mid-context reinjection | Context Econ. | 🔲 | Indirect | | C1 | Silent reply (NO_REPLY) | Output Econ. | ✅ | $5–8/day | | C2 | Thinking control (output) | Output Econ. | ✅ | (see A2) | | D1 | Cron priority tiers | Temporal Amort. | ✅ | 15–20% automated | | D2 | Background review agent | Temporal Amort. | 🔲 | 80% reflection | | D3 | Dual-account staggering | Temporal Amort. | ✅ | Eliminates outages | | D4 | Token bucket pacing | Temporal Amort. | ✅ | Prevents lockouts | | E1 | Batch API for non-interactive | Billing Arbitrage | ✅ | 50% on batch work | | E2 | Sub-agent fresh context | Billing Arbitrage | ✅ | $1–3/delegation | | F1 | Security scanning on mem writes | Security | 🔲 | Indirect |
v1.2 · 3. Taxonomy of Budget Prompting Techniques| # | Technique | Category | Status | Est. Savings | |---|-----------|----------|--------|--------------| | A1 | Model routing by complexity | Model Routing | [Y] | 25–40% automated | | A2 | Extended thinking control | Model Routing | [Y] | $5–10/day equiv. | | A3 | Cross-model delegation | Model Routing | [Y] | Variable | | B1 | System prompt caching | Context Econ. | [Y] | $8–10/day | | B2 | Aggressive session management | Context Econ. | [Y] | 2–4× per turn | | B3 | Memory search over bulk loading | Context Econ. | [Y] | 80–95% context | | B4 | Context compaction | Context Econ. | [Y] | 60–80% context | | B5 | Frozen snapshot injection | Context Econ. | [ ] | CHR 65%→90%+ | | B6 | Surgical tool output pruning | Context Econ. | [ ] | 30–40% context | | B7 | Iterative summary compression | Context Econ. | [ ] | 5–15K tokens | | B8 | Rolling window + vector retrieval | Context Econ. | [ ] | Fixed context cap | | B9 | Mid-context reinjection | Context Econ. | [ ] | Indirect | | C1 | Silent reply (NO_REPLY) | Output Econ. | [Y] | $5–8/day | | C2 | Thinking control (output) | Output Econ. | [Y] | (see A2) | | D1 | Cron priority tiers | Temporal Amort. | [Y] | 15–20% automated | | D2 | Background review agent | Temporal Amort. | [ ] | 80% reflection | | D3 | Dual-account staggering | Temporal Amort. | [Y] | Eliminates outages | | D4 | Token bucket pacing | Temporal Amort. | [Y] | Prevents lockouts | | E1 | Batch API for non-interactive | Billing Arbitrage | [Y] | 50% on batch work | | E2 | Sub-agent fresh context | Billing Arbitrage | [Y] | $1–3/delegation | | F1 | Security scanning on mem writes | Security | [ ] | Indirect |
··· 6 unchanged paragraphs folded ···
v1.1 · A1. Model Routing by Task Complexity```yaml routing: interactive: claude-sonnet # User-facing, personality-critical cron-high: claude-sonnet # Morning briefing, security scans cron-low: claude-haiku # Log rotation, cleanup tasks sub-agent: claude-haiku # Delegated rote work review: gpt-4o # Cross-model second opinion batch: claude-haiku # Nightly consolidation via batch API ```
v1.2 · A1. Model Routing by Task Complexity``` routing: interactive: claude-sonnet # User-facing, personality-critical cron-high: claude-sonnet # Morning briefing, security scans cron-low: claude-haiku # Log rotation, cleanup tasks sub-agent: claude-haiku # Delegated rote work review: gpt-4o # Cross-model second opinion batch: claude-haiku # Nightly consolidation via batch API ```
··· 1 unchanged paragraph folded ···
v1.1 · A1. Model Routing by Task Complexity**Status:** ✅ Implemented. In production since February 2026.
v1.2 · A1. Model Routing by Task Complexity**Status:** [Y] Implemented. In production since February 2026.
··· 5 unchanged paragraphs folded ···
v1.1 · A2. Extended Thinking Control**Status:** ✅ Implemented. Sub-agents default to `thinking: low`. Cron jobs default to `thinking: off` unless the task is flagged as requiring reasoning.
v1.2 · A2. Extended Thinking Control**Status:** [Y] Implemented. Sub-agents default to `thinking: low`. Cron jobs default to `thinking: off` unless the task is flagged as requiring reasoning.
··· 5 unchanged paragraphs folded ···
v1.1 · A3. Cross-Model Delegation**Status:** ✅ Implemented. The `oracle` CLI wraps ChatGPT API calls. Used primarily for cross-model code review and document analysis.
v1.2 · A3. Cross-Model Delegation**Status:** [Y] Implemented. The `oracle` CLI wraps ChatGPT API calls. Used primarily for cross-model code review and document analysis.
··· 6 unchanged paragraphs folded ···
v1.1 · B1. System Prompt Caching**Status:** ✅ Implemented. Configuration: ```yaml cacheRetention: "long" ```
v1.2 · B1. System Prompt Caching**Status:** [Y] Implemented. Configuration: ``` cacheRetention: "long" ```
··· 2 unchanged paragraphs folded ···
not in v1.1
v1.2 · B1. System Prompt Caching**Production validation — the dynamic boundary.** The leaked Claude Code source implements exactly this prefix-discipline. `constants/prompts.ts` defines a `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` sentinel: everything before it is globally cacheable (shared across sessions when `shouldUseGlobalCacheScope()` is on), and per-session content goes after. Cache-breaking sections are not just placed correctly — they are *named to be dangerous*: the helper that emits an uncacheable section is literally `DANGEROUS_uncachedSystemPromptSection()` (`constants/systemPromptSections.ts`). Making "this breaks the cache" explicit in the API is the same discipline MYELIN argues for in Section 8.1; seeing it enforced by naming in shipping code is good evidence the principle is load-bearing, not aesthetic.
··· 5 unchanged paragraphs folded ···
v1.1 · B2. Aggressive Session Management**Status:** ✅ Implemented. OpenClaw supports manual session restart via `/new`, and the agent is prompted to suggest new sessions when topics shift.
v1.2 · B2. Aggressive Session Management**Status:** [Y] Implemented. OpenClaw supports manual session restart via `/new`, and the agent is prompted to suggest new sessions when topics shift.
··· 4 unchanged paragraphs folded ···
v1.1 · B3. Memory Search over Bulk Loading**Status:** ✅ Implemented. 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()`
v1.2 · B3. Memory Search over Bulk Loading**Status:** [Y] Implemented. 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()`
··· 4 unchanged paragraphs folded ···
v1.1 · B4. Context Compaction**Status:** ✅ Implemented. OpenClaw's built-in feature. Triggered manually via `/compress` or automatically when context approaches limits.
v1.2 · B4. Context Compaction**Status:** [Y] Implemented. OpenClaw's built-in feature. Triggered manually via `/compress` or automatically when context approaches limits.
··· 1 unchanged paragraph folded ···
not in v1.1
v1.2 · B4. Context Compaction**Two distinct operations, not one.** Our v1.1 taxonomy conflated two things that the Claude Code source treats separately, and the distinction is worth importing. *Summarization* (lossy, comprehensive) 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.
not in v1.1
v1.2 · B4. Context Compaction**Forked-agent cache sharing.** Claude Code's session compaction (`services/compact/compact.ts`) spawns a forked agent (`runForkedAgent`, `CacheSafeParams`) whose prompt cache is shared with the parent: the summary agent does not pay to re-read the conversation it is summarizing. It strips images first (`stripImagesFromMessages`) so they don't waste the summary budget, and on the way back restores up to 5 most-relevant files at ~5K tokens each plus skills under a 25K budget (`POST_COMPACT_MAX_FILES_TO_RESTORE`, `POST_COMPACT_MAX_TOKENS_PER_FILE`, `POST_COMPACT_SKILLS_TOKEN_BUDGET`). The cache-sharing trick makes compaction nearly free in cache terms and is the clearest argument that compaction should reuse, not rebuild, the prefix. It likely requires API-level support our current stack does not expose; we flag it as a target rather than a shipped technique.
··· 8 unchanged paragraphs folded ···
v1.1 · B5. Frozen Snapshot Injection (Prefix Stabilization)``` ALGORITHM: FrozenSnapshotInjection(session_start) ───────────────────────────────────────────────── On session_start: snapshot ← {} for each file f in memory_hierarchy: snapshot[f.path] ← read(f) system_prompt ← build_prompt(snapshot) cache(system_prompt) # stable prefix for entire session staging ← {} # empty write buffer
v1.2 · B5. Frozen Snapshot Injection (Prefix Stabilization)``` ALGORITHM: FrozenSnapshotInjection(session_start) ------------------------------------------------- On session_start: snapshot ← {} for each file f in memory_hierarchy: snapshot[f.path] ← read(f) system_prompt ← build_prompt(snapshot) cache(system_prompt) # stable prefix for entire session staging ← {} # empty write buffer
··· 2 unchanged paragraphs folded ···
v1.1 · B5. Frozen Snapshot Injection (Prefix Stabilization)**Status:** 🔲 Designed, not implemented. Requires changes to OpenClaw's memory injection pipeline.
v1.2 · B5. Frozen Snapshot Injection (Prefix Stabilization)**Status:** [Designed], not implemented. Requires changes to OpenClaw's memory injection pipeline.
··· 5 unchanged paragraphs folded ···
not in v1.1
v1.2 · B6. Surgical Tool Output Pruning**Production validation — MicroCompact.** Claude Code ships exactly this technique, and more surgically than our v1.1 design. Its `microCompact.ts` compacts only specific tool results — `FileRead`, `Bash`, `Grep`, `Glob`, `WebSearch`, `WebFetch`, `FileEdit`, `FileWrite` (eight tool types, confirmed in the imports). Old results are replaced in place with a stub — the literal constant is `TIME_BASED_MC_CLEARED_MESSAGE = '[Old tool result content cleared]'` — and clearing is time-gated (a configurable gap threshold; see `timeBasedMCConfig.ts`). Two refinements over our design are worth adopting: (1) restrict pruning to tool types whose output is large and rarely re-referenced, rather than pruning all messages; and (2) **cache-pinning** — the cleared stubs are kept at the *original positions* in the message list so the prompt-cache prefix up to that point still matches. This is the production answer to the cache-vs-pruning tension B6 raises in the abstract: you can prune content without moving anything, so the cache survives. Note `microCompact.ts` deliberately runs cached MC only on the main thread, to avoid forked agents corrupting the shared cache state — a subtlety our design had not anticipated.
not in v1.1
v1.2 · B6. Surgical Tool Output Pruning**Approach comparison.** Our proposed B6 is embedding/summary-based (replace old output with an LLM-generated 2–3 sentence summary); Claude Code's is stub-replacement (replace with a fixed marker, no LLM call). The stub approach is free and cache-safe but loses the content entirely; ours preserves a gist at the cost of a cheap Haiku call. The right design is probably staged: stub-replace first (free, cache-pinned), summarize only the survivors under budget pressure — which is the two-stage pipeline B6 already describes.
v1.1 · B6. Surgical Tool Output Pruning**Status:** 🔲 Designed, not implemented. Currently we use blunt `/compress` which summarizes *everything*, not just tool outputs.
v1.2 · B6. Surgical Tool Output Pruning**Status:** [Designed], not implemented. Currently we use blunt `/compress` which summarizes *everything*, not just tool outputs.
··· 9 unchanged paragraphs folded ···
v1.1 · B7. Iterative Summary Compression**Status:** 🔲 Designed, not implemented. Requires modification to OpenClaw's compaction logic.
v1.2 · B7. Iterative Summary Compression**Status:** [Designed], not implemented. Requires modification to OpenClaw's compaction logic.
··· 6 unchanged paragraphs folded ···
v1.1 · B8. Rolling Window + Vector Retrieval**Status:** 🔲 Designed, not implemented (part of the continuous compaction project). Requires embedding pipeline and vector store integration.
v1.2 · B8. Rolling Window + Vector Retrieval**Status:** [Designed], not implemented (part of the continuous compaction project). Requires embedding pipeline and vector store integration.
··· 6 unchanged paragraphs folded ···
v1.1 · B9. Mid-Context Reinjection**Status:** 🔲 Designed, not implemented. Requires SyncScore monitoring integration.
v1.2 · B9. Mid-Context Reinjection**Status:** [Designed], not implemented. Requires SyncScore monitoring integration.
··· 8 unchanged paragraphs folded ···
v1.1 · C1. Silent Reply (NO_REPLY / HEARTBEAT_OK)**Status:** ✅ Implemented. Sentinel tokens are recognized by the gateway and produce minimal API round-trips.
v1.2 · C1. Silent Reply (NO_REPLY / HEARTBEAT_OK)**Status:** [Y] Implemented. Sentinel tokens are recognized by the gateway and produce minimal API round-trips.
··· 8 unchanged paragraphs folded ···
v1.1 · D1. Cron Priority Tiers```yaml cron-tiers: critical: # Morning briefing, security scan model: claude-sonnet thinking: low skip-when-budget: never standard: # Email check, calendar sync model: claude-haiku thinking: off skip-when-budget: >85% weekly utilization background: # Log rotation, memory cleanup model: claude-haiku thinking: off skip-when-budget: >70% weekly utilization ```
v1.2 · D1. Cron Priority Tiers``` cron-tiers: critical: # Morning briefing, security scan model: claude-sonnet thinking: low skip-when-budget: never standard: # Email check, calendar sync model: claude-haiku thinking: off skip-when-budget: >85% weekly utilization background: # Log rotation, memory cleanup model: claude-haiku thinking: off skip-when-budget: >70% weekly utilization ```
··· 2 unchanged paragraphs folded ···
v1.1 · D1. Cron Priority Tiers**Status:** ✅ Implemented. Priority tiers defined in cron configuration.
v1.2 · D1. Cron Priority Tiers**Status:** [Y] Implemented. Priority tiers defined in cron configuration.
··· 6 unchanged paragraphs folded ···
v1.1 · D2. Background Review Agent (Amortized Reflection)**Status:** 🔲 Designed, not implemented. Currently, the agent reflects inline — every turn includes some self-monitoring overhead.
v1.2 · D2. Background Review Agent (Amortized Reflection)**Status:** [Designed], not implemented. Currently, the agent reflects inline — every turn includes some self-monitoring overhead.
··· 7 unchanged paragraphs folded ···
v1.1 · D3. Dual-Account Pool Staggering**Status:** ✅ Implemented. Flat-rate subscriptions with staggered resets. Gateway tracks utilization per account.
v1.2 · D3. Dual-Account Pool Staggering**Status:** [Y] Implemented. Flat-rate subscriptions with staggered resets. Gateway tracks utilization per account.
··· 6 unchanged paragraphs folded ···
v1.1 · D4. Token Bucket Pacing**Status:** ✅ Implemented. Gateway tracks per-account token consumption and enforces pacing.
v1.2 · D4. Token Bucket Pacing**Status:** [Y] Implemented. Gateway tracks per-account token consumption and enforces pacing.
··· 7 unchanged paragraphs folded ···
v1.1 · E1. Batch API for Non-Interactive Work**Status:** ✅ Implemented. Nightly consolidation jobs use the batch API. A queue system stages work during the day for batch processing overnight.
v1.2 · E1. Batch API for Non-Interactive Work**Status:** [Y] Implemented. Nightly consolidation jobs use the batch API. A queue system stages work during the day for batch processing overnight.
··· 5 unchanged paragraphs folded ···
v1.1 · E2. Sub-Agent Fresh Context**Status:** ✅ Implemented. OpenClaw's sub-agent spawning creates clean context by default.
v1.2 · E2. Sub-Agent Fresh Context**Status:** [Y] Implemented. OpenClaw's sub-agent spawning creates clean context by default.
··· 7 unchanged paragraphs folded ···
v1.1 · F1. Security Scanning on Memory Writes**Status:** 🔲 Designed, not implemented. Currently relies on the agent's own judgment to avoid writing suspicious content to memory.
v1.2 · F1. Security Scanning on Memory Writes**Status:** [Designed], not implemented. Currently relies on the agent's own judgment to avoid writing suspicious content to memory.
··· 9 unchanged paragraphs folded ···
v1.1 · 4.2 Budget Pressure Cascade``` ALGORITHM: BudgetPressureCascade(utilisation, task) ───────────────────────────────────────────────────── Input: utilisation ∈ [0, 1] (7-day rolling average across all accounts) task: {type, priority, model_preference, thinking_budget} Output: routed_task: {model, thinking, should_execute}
v1.2 · 4.2 Budget Pressure Cascade``` ALGORITHM: BudgetPressureCascade(utilisation, task) ----------------------------------------------------- Input: utilisation in [0, 1] (7-day rolling average across all accounts) task: {type, priority, model_preference, thinking_budget} Output: routed_task: {model, thinking, should_execute}
··· 3 unchanged paragraphs folded ···
v1.1 · 4.2 Budget Pressure Cascadeelif utilisation < 0.95: # RED — degrade interactive routed_task.model ← SONNET if task.type = "interactive" else HAIKU routed_task.thinking ← LOW if task.type = "interactive" else OFF routed_task.should_execute ← task.priority ≥ "standard"
v1.2 · 4.2 Budget Pressure Cascadeelif utilisation < 0.95: # RED — degrade interactive routed_task.model ← SONNET if task.type = "interactive" else HAIKU routed_task.thinking ← LOW if task.type = "interactive" else OFF routed_task.should_execute ← task.priority >= "standard"
··· 16 unchanged paragraphs folded ···
not in v1.1
v1.2 · 4.5 Knowing When to Stop — Budget Triggers from the Claude Code Source### 4.5 Knowing When to Stop — Budget Triggers from the Claude Code Source
not in v1.1
v1.2 · 4.5 Knowing When to Stop — Budget Triggers from the Claude Code SourceMYELIN's budget cascade (4.2) decides *how* to process a request. The leaked Claude Code source adds a dimension we under-modeled: *when to stop generating at all*. Two mechanisms are worth importing.
not in v1.1
v1.2 · 4.5 Knowing When to Stop — Budget Triggers from the Claude Code Source**Diminishing-returns detection.** `query/tokenBudget.ts` tracks token consumption per agent turn and stops continuing when the agent stalls. The constants are explicit: `COMPLETION_THRESHOLD = 0.9` (stop when 90% of the token target is reached) and `DIMINISHING_THRESHOLD = 500` (when successive continuations each produce under 500 tokens, treat it as diminishing returns and stop). The continuation message even reports percentage used and instructs the agent to keep working rather than summarize prematurely. This is a *productivity* trigger, orthogonal to the token-count triggers in B4/B6: compact or stop not only when context is large, but when each additional turn is buying little. It is cheap — it reads counters already being tracked — and it directly attacks the wasted-call problem from Section 1. We recommend adding a diminishing-returns counter alongside MYELIN's existing size thresholds.
not in v1.1
v1.2 · 4.5 Knowing When to Stop — Budget Triggers from the Claude Code Source**Output-token capping (slot reservation).** Requesting a large `max_tokens` is not free: the server reserves output slots up front, so an over-large cap reduces throughput even when the actual response is short. The Claude Code analysis reports a conservative default output cap (on the order of 8K tokens, against a p99 actual output near 5K) with a single clean retry at a larger ceiling when the cap is hit; the source confirms a `MAX_NON_STREAMING_TOKENS = 64_000` constant and per-model resolution via `getMaxOutputTokensForModel()` for that escalation path. (The 8K *default* figure itself is from secondary analysis of the dump, not a line we verified, so we report it as such.) The principle is sound regardless of the exact number: start the output cap conservative, escalate on demand. This belongs in MYELIN's output economics (Category C) as a complement to thinking control — A2 limits reasoning tokens, output capping limits the reservation.
··· 39 unchanged paragraphs folded ···
not in v1.1
v1.2 · 6.5 Industrial Convergence as Validation### 6.5 Industrial Convergence as Validation
not in v1.1
v1.2 · 6.5 Industrial Convergence as ValidationWe have no controlled ablation, so the strongest evidence available short of one is convergence: a second team, working independently at the lab that sets the pricing we are optimizing against, built the same architecture. The March 2026 Claude Code source exposure provides that evidence point by point.
not in v1.1
v1.2 · 6.5 Industrial Convergence as Validation| MYELIN claim | Claude Code shipping equivalent | Status of our claim | |---|---|---| | Three-tier compaction is the natural architecture (Sec 2.5) | MicroCompact / Session Compact / autoDream | Independently confirmed | | Cache stability over a static prefix is the core lever (B1, 8.1) | `SYSTEM_PROMPT_DYNAMIC_BOUNDARY`, `DANGEROUS_uncached…` | Confirmed, enforced by API naming | | Prune tool outputs without breaking cache (B6) | Cache-pinned MicroCompact, in-place stubs | Confirmed, more surgical than ours | | Compaction can reuse the parent cache (B4) | `runForkedAgent` + `CacheSafeParams` | Confirmed; we had only theorized it | | Stop spending when returns diminish (4.5) | `DIMINISHING_THRESHOLD = 500`, `COMPLETION_THRESHOLD = 0.9` | New; we under-modeled this | | Background consolidation gated cheaply (cf. J5, D2) | autoDream gates: time 24h → 5 sessions → lock | Confirmed gate ordering |
not in v1.1
v1.2 · 6.5 Industrial Convergence as ValidationThis 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. We treat this as the next best thing to replication, and a direct prompt to run the ablations in Section 9.2.
not in v1.1
v1.2 · 6.5 Industrial Convergence as ValidationA note on consolidation, relevant to our J5 line of work: autoDream's consolidation prompt (`services/autoDream/consolidationPrompt.ts`) runs an information *diet* we found instructive — "grep narrowly, don't read whole files," "look only for things you already suspect matter," convert relative dates to absolute, delete contradicted facts at the source, and keep the memory index under a hard line/byte cap with one-line entries. This is a precision-first stance (read little, write little) where MYELIN's embedding-based retrieval is recall-first. Neither is strictly better: grep-narrow risks missing context it didn't suspect; embedding-broad risks pulling in noise. A consolidation pass that uses embeddings to *find candidates* and grep to *verify exact facts* would combine the two.
··· 21 unchanged paragraphs folded ···
not in v1.1
v1.2 · 7.8 The Claude Code Source Exposure (March 2026)### 7.8 The Claude Code Source Exposure (March 2026)
not in v1.1
v1.2 · 7.8 The Claude Code Source Exposure (March 2026)The most directly comparable system is Anthropic's own Claude Code agent, whose source became visible through the March 2026 source-map exposure (`@anthropic-ai/claude-code@2.1.88`, ~512K lines of TypeScript). It is not published research and was not meant to be read, so we cite it as primary-source code analysis rather than literature. Its relevance is unusual: most related work describes a different design; Claude Code describes a *parallel* one, built independently against the same billing constraints. Sections 2.5, 4.5, and 6.5 fold the specific findings — MicroCompact, the dynamic-boundary prefix discipline, forked-agent cache sharing, diminishing-returns budgeting, and autoDream's consolidation diet — into the relevant techniques. We treat it throughout as convergent evidence for the architecture, with the standing caveat that a few quoted figures come from secondary analysis of the dump rather than verified source lines.
··· 5 unchanged paragraphs folded ···
v1.1 · 8.1 The Surprising Dominance of CachingThis is fundamentally at odds with how most agent frameworks are designed. They inject dynamic context (current time, recent events, user presence status) into the system prompt because it's convenient. Each dynamic injection breaks the cache. Budget Prompting argues that dynamic context should be injected as user-role messages *after* the cached prefix, not *within* it.
v1.2 · 8.1 The Surprising Dominance of CachingThis is fundamentally at odds with how most agent frameworks are designed. They inject dynamic context (current time, recent events, user presence status) into the system prompt because it's convenient. Each dynamic injection breaks the cache. Budget Prompting argues that dynamic context should be injected as user-role messages *after* the cached prefix, not *within* it. Claude Code's `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` (Section 2.5) is the same argument made in production code: there is a literal marker dividing the cacheable prefix from per-session content, and the only function that writes past it is named `DANGEROUS_uncached…`. When the principle is correct, the implementation has to draw that line somewhere; it's reassuring that two systems drew it in the same place.
··· 14 unchanged paragraphs folded ···
v1.1 · 8.5 Limitations**No controlled ablation.** We haven't done rigorous ablation studies. Per-technique attribution is estimated, not measured.
removed in v1.2
not in v1.1
v1.2 · 8.5 Limitations**No controlled ablation.** We haven't done rigorous ablation studies. Per-technique attribution is estimated, not measured. The industrial-convergence evidence (Section 6.5) validates the *architecture* but not the *savings magnitudes* — two independent designs can agree on structure and still both misjudge cost.
not in v1.1
v1.2 · 8.5 Limitations**Leaked-source provenance.** The Claude Code findings rest on code that was exposed by accident, not documentation Anthropic endorses. We verified the cited constants and file paths directly, but a small number of quoted figures (the ~250K daily-waste number, the 8K default output cap) come from secondary analysis of the dump and are marked as such. Anthropic may change any of this without notice.
··· 27 unchanged paragraphs folded ···
v1.1 · Appendix A: Technique Summary Table| # | Technique | Category | Status | Est. Savings | |---|-----------|----------|--------|--------------| | A1 | Model routing by complexity | Model Routing | ✅ Impl. | 25–40% automated | | A2 | Extended thinking control | Model Routing | ✅ Impl. | $5–10/day equiv. | | A3 | Cross-model delegation | Model Routing | ✅ Impl. | Variable | | B1 | System prompt caching | Context Econ. | ✅ Impl. | $8–10/day | | B2 | Aggressive session management | Context Econ. | ✅ Impl. | 2–4× per turn | | B3 | Memory search over bulk loading | Context Econ. | ✅ Impl. | 80–95% context | | B4 | Context compaction | Context Econ. | ✅ Impl. | 60–80% context | | B5 | Frozen snapshot injection | Context Econ. | 🔲 Designed | CHR 65%→90%+ | | B6 | Surgical tool output pruning | Context Econ. | 🔲 Designed | 30–40% context | | B7 | Iterative summary compression | Context Econ. | 🔲 Designed | 5–15K tokens | | B8 | Rolling window + vector retrieval | Context Econ. | 🔲 Designed | Fixed context cap | | B9 | Mid-context reinjection | Context Econ. | 🔲 Designed | Indirect | | C1 | Silent reply (NO_REPLY) | Output Econ. | ✅ Impl. | $5–8/day | | C2 | Thinking control (output) | Output Econ. | ✅ Impl. | (see A2) | | D1 | Cron priority tiers | Temporal Amort. | ✅ Impl. | 15–20% automated | | D2 | Background review agent | Temporal Amort. | 🔲 Designed | 80% reflection | | D3 | Dual-account staggering | Temporal Amort. | ✅ Impl. | Eliminates outages | | D4 | Token bucket pacing | Temporal Amort. | ✅ Impl. | Prevents lockouts | | E1 | Batch API for non-interactive | Billing Arbitrage | ✅ Impl. | 50% on batch work | | E2 | Sub-agent fresh context | Billing Arbitrage | ✅ Impl. | $1–3/delegation | | F1 | Security scanning on mem writes | Security | 🔲 Designed | Indirect |
v1.2 · Appendix A: Technique Summary Table| # | Technique | Category | Status | Est. Savings | |---|-----------|----------|--------|--------------| | A1 | Model routing by complexity | Model Routing | [Impl.] | 25–40% automated | | A2 | Extended thinking control | Model Routing | [Impl.] | $5–10/day equiv. | | A3 | Cross-model delegation | Model Routing | [Impl.] | Variable | | B1 | System prompt caching | Context Econ. | [Impl.] | $8–10/day | | B2 | Aggressive session management | Context Econ. | [Impl.] | 2–4× per turn | | B3 | Memory search over bulk loading | Context Econ. | [Impl.] | 80–95% context | | B4 | Context compaction | Context Econ. | [Impl.] | 60–80% context | | B5 | Frozen snapshot injection | Context Econ. | [Designed] | CHR 65%→90%+ | | B6 | Surgical tool output pruning | Context Econ. | [Designed] | 30–40% context | | B7 | Iterative summary compression | Context Econ. | [Designed] | 5–15K tokens | | B8 | Rolling window + vector retrieval | Context Econ. | [Designed] | Fixed context cap | | B9 | Mid-context reinjection | Context Econ. | [Designed] | Indirect | | C1 | Silent reply (NO_REPLY) | Output Econ. | [Impl.] | $5–8/day | | C2 | Thinking control (output) | Output Econ. | [Impl.] | (see A2) | | D1 | Cron priority tiers | Temporal Amort. | [Impl.] | 15–20% automated | | D2 | Background review agent | Temporal Amort. | [Designed] | 80% reflection | | D3 | Dual-account staggering | Temporal Amort. | [Impl.] | Eliminates outages | | D4 | Token bucket pacing | Temporal Amort. | [Impl.] | Prevents lockouts | | E1 | Batch API for non-interactive | Billing Arbitrage | [Impl.] | 50% on batch work | | E2 | Sub-agent fresh context | Billing Arbitrage | [Impl.] | $1–3/delegation | | F1 | Security scanning on mem writes | Security | [Designed] | Indirect |
··· 5 unchanged paragraphs folded ···
v1.1 · References- Kwon, W., et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. *SOSP '23*. - Lewis, P., et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. *NeurIPS 2020*. - Madaan, A., et al. (2023). Self-Refine: Iterative Refinement with Self-Feedback. *NeurIPS 2023*. - Packer, C., et al. (2023). MemGPT: Towards LLMs as Operating Systems. *arXiv:2310.08560*. - Rajbhandari, S., et al. (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. *SC '20*. - Serra, O. (2026a). TOTAL RECALL: Persistent Memory Architecture for Stateless AI Agents. *TinkerClaw Working Papers, J1*. - Serra, O. (2026b). SYNAPSE: Identity Persistence Across Sessions in Persistent Memory Agents. *TinkerClaw Working Papers, J4*. - Serra, O. (2026c). CEREBELLUM: Structured Nightly Prompting for Emergent Intelligence. *TinkerClaw Working Papers, J5*. - Sheng, Y., et al. (2023). FlexGen: High-Throughput Generative Inference of Large Language Models with a Single GPU. *ICML 2023*. - Wei, J., et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. *NeurIPS 2022*. - Yao, S., et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. *ICLR 2023*.
v1.2 · References- Anthropic (2026). Claude Code source analysis. Internal codebase exposed via npm source map, `@anthropic-ai/claude-code` v2.1.88; ~512,000 lines of TypeScript. Compaction and budget code (`services/compact/`, `services/autoDream/`, `query/tokenBudget.ts`, `constants/prompts.ts`) analyzed April 2026. Cited as primary-source code, not endorsed documentation. - Kwon, W., et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. *SOSP '23*. - Lewis, P., et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. *NeurIPS 2020*. - Madaan, A., et al. (2023). Self-Refine: Iterative Refinement with Self-Feedback. *NeurIPS 2023*. - Packer, C., et al. (2023). MemGPT: Towards LLMs as Operating Systems. *arXiv:2310.08560*. - Rajbhandari, S., et al. (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. *SC '20*. - Serra, O. (2026a). TOTAL RECALL: Persistent Memory Architecture for Stateless AI Agents. *TinkerClaw Working Papers, J1*. - Serra, O. (2026b). SYNAPSE: Identity Persistence Across Sessions in Persistent Memory Agents. *TinkerClaw Working Papers, J4*. - Serra, O. (2026c). CEREBELLUM: Structured Nightly Prompting for Emergent Intelligence. *TinkerClaw Working Papers, J5*. - Sheng, Y., et al. (2023). FlexGen: High-Throughput Generative Inference of Large Language Models with a Single GPU. *ICML 2023*. - Wei, J., et al. (2022). Chain-of-Thought Prompting Elicits Reasoning in Large Language Models. *NeurIPS 2022*. - Yao, S., et al. (2023). ReAct: Synergizing Reasoning and Acting in Language Models. *ICLR 2023*.
··· 3 unchanged paragraphs folded ···
v1.1 · References*MYELIN v1.1 — TinkerClaw Working Papers, J12* *© 2026 Oscar Serra, Jarvis. All rights reserved.*
v1.2 · References*MYELIN v1.2 — TinkerClaw Working Papers, J12* *© 2026 Oscar Serra, Jarvis. All rights reserved.*
Changed paragraphs in the same form, for scripts: JSON
· Markdown