# Context Tuning
<!--
ref: @protocol/context-tuning
tags: [context, tuning, periodic, base-context, memory, token-budget, hierarchy, memory-tree, agent-authoring, groom-op]
triggers: [time for a context tune-up, periodic context cleanup, my memory file is huge, context is bloated before I start, agent loads too much at boot, MEMORY.md keeps growing, deconstruct my CLAUDE.md, too many MCP tools, build a memory hierarchy, memory tree, what should stay always-loaded]
trigger_prompt: When an agent's session starts already heavy — a long CLAUDE.md, a memory index that grew past a screen, a wall of MCP tool schemas — and you need to decide what genuinely must load every turn versus what should become fetchable knowledge in a hierarchy.
category: core
complements: [@protocol/information-tree, @protocol/memory-routing, @protocol/tighten-bootstrap-token-budget, @protocol/progressive-context, @protocol/context-quality, @protocol/harvest-project]
audience: [agent-author, claude-code-user, openclaw-user]
version: 8
updated_at: 2026-10-24T21:10:39.841Z
-->

Audit everything that loads before the user types, keep only what fails without it, and deconstruct the rest into a fetchable tree — root index, domain branches, leaf entries — so the base stays flat while the knowledge keeps growing.

Run this when context is bloated before you start, when MEMORY.md keeps growing, when the agent loads too much at boot, when there are too many MCP tools, or when it is simply time for a periodic context tune-up.

**This is a tune-up, not a migration.** You will run it again. Every session that saves something useful adds a little weight to the base, and that is the system working — the drift is a by-product of doing the work, not a failure of discipline. So treat this the way you treat any periodic maintenance: run it on a cadence, expect to find mess, fix the mess, and do not moralise about how it got there. A base that never drifts is a base nobody is learning into.

## The asymmetry that makes this worth doing

Context comes in two kinds, and they are priced completely differently.

- **Base context** — the harness config, the memory index, tool schemas, skill listings. Loaded before the user types, re-sent on **every turn of every session, forever.**
- **Working context** — files read, commands run, protocols fetched. Paid **once**, in the session that needed it.

A fact in the base is charged `sessions × turns`. The same fact in a protocol is charged *only in the sessions that fetch it*. So a 5,000-token memory index that any given session actually needs three lines of is not "5,000 tokens" — it is 5,000 tokens times every turn you will ever run, to deliver about 200 tokens of value.

This is why base bloat survives so long: each addition is individually cheap and locally justified. Nobody adds 5,000 tokens. Sixty people add eighty.

> Sibling protocols work the other side of this line. [`@protocol/context-quality`](@protocol/context-quality) treats pollution *inside* a running session; [`@protocol/progressive-context`](@protocol/progressive-context) picks which context a task should pull. **This protocol is about what you are charged for before the session starts.** Neither of those will ever catch base bloat, because by the time they run you have already paid.

## The four surfaces

Audit all four. Most people audit only the first and wonder why the number barely moves.

| # | Surface | Where it lives | Typical failure |
|---|---|---|---|
| 1 | **Harness config** | global + project `CLAUDE.md` or `AGENTS.md`, `.cursorrules`, system prompt | Accretes rules that apply to one project, or one bad afternoon |
| 2 | **Memory index** | the harness memory store's index file | Grows one line per session, never shrinks — usually the largest surface |
| 3 | **Tool schemas** | MCP servers, built-in tools | Full JSONSchema per tool; a chatty server can cost more than every doc combined |
| 4 | **Listings** | skills, slash commands, agent types | Each entry carries a description sized for a human browsing, not an agent routing |

Whatever your bootstrap include list renders is part of surface 1. Audit it with the rest — and if that composed bootstrap is itself the heavy part, [`@protocol/tighten-bootstrap-token-budget`](@protocol/tighten-bootstrap-token-budget) is the specific four-pass audit for it (demote `full` includes, retire unread ones, swap repo includes for named protocols, tune section limits). Do that pass rather than re-deriving it here.

## Measure first — always

Never cut from intuition. The surface that *feels* bloated is rarely the one that costs.

```bash
# Surfaces 1 & 2 — bytes ÷ 4 ≈ tokens, close enough to rank by
for f in ~/.claude/CLAUDE.md ./CLAUDE.md ~/.codex/AGENTS.md ./AGENTS.md <memory-index>; do
  [ -f "$f" ] || continue
  printf '%-40s ~%s t\n' "$f" "$(( $(wc -c < "$f") / 4 ))"
done
```

For surfaces 3 and 4, count entries and multiply by a typical schema size — an MCP tool schema runs 150–400 tokens, a listing line 20–60. If your harness supports **deferred tools** (names surfaced, schemas fetched on demand), that single switch usually beats every other cut available on surface 3.

Then rank by the number that actually matters:

> **Cost × (1 − hit rate).** How much it costs every turn, times how often it is *irrelevant*.

A 300-token block every session needs is cheaper than a 5,000-token index where each session uses three lines. Rank by waste, not by size.

### Then measure the after-state — this is the step everyone skips

A shrunken base is not the result. **Cost-per-use across every layer** is the result, and it is easy to make the first number fall while the second rises. [`@protocol/information-tree`](@protocol/information-tree) names this the **silent move**: the core's numbers drop, and nothing is actually cheaper to use.

The specific way it bites here: you cut a 5,000-token index, and a session that needs one decision now fetches a 6,000-token branch. You reported a 90% saving and delivered a regression.

So after cutting, compute both:

- **Base delta** — what every session stopped paying. The easy number.
- **Fetch delta** — for the three or four most common tasks, what does the session now pull that it previously had resident? Multiply by how often that task runs.

If a branch is large and frequently needed whole, it is a **shadow core** — knowledge wearing the wrong label. Promote it back into the base, or split it so the common path fetches only its part. Reporting only the base delta is how a tune-up becomes theatre.

## The keep test

For each item in the base, ask three questions. **Keep it only if all three are yes.**

1. **Unprompted** — would the agent get this *wrong* without knowing it in advance? Not "is it useful" — useful is not the bar, everything is useful. The bar is: on meeting this topic cold, would the agent do the wrong thing rather than go look? If it would naturally search, it does not belong in the base.
2. **Universal** — does it apply across most sessions? A rule that binds one subsystem belongs with that subsystem.
3. **Un-pointable** — is it genuinely unreachable via a one-line pointer plus one fetch? Almost nothing survives this one, and that is the point.

Three shapes reliably pass: **identity** (who the user is, how they work), **environment facts true only of this machine**, and **routing** (where knowledge lives and how to reach it).

Three shapes reliably fail and are the usual bulk: **decision records** ("we chose X over Y in March"), **domain doctrine** (scoring rules, install patterns, pricing behavior), and **incident learnings** (the bug, the trap, the fix).

## The second axis: scope

Altitude — base or fetchable — is only half the sort. The other half is **scope: does this apply to every project, or to one?** The two axes are independent, and an item can pass the keep test and still be in the wrong place.

|  | **Global scope** | **Project scope** |
|---|---|---|
| **Base** | Global config — identity, universal working style, one routing block into the global tree | Project config — what this project is, one routing block into the project tree |
| **Fetchable** | Global / personal repo tree | Project repo tree |

Four misroutes, in rough order of how much damage they do:

1. **Universal fact stranded in a project store** — invisible from every other project, so it gets re-learned, re-worded, and re-saved elsewhere. The most expensive misroute, and the least visible.
2. **Project rule sitting in global config** — every unrelated session pays for it, and worse, it can *misfire* on a project it was never written for.
3. **Fetchable knowledge in either base** — the ordinary bloat the keep test catches.
4. **Project knowledge in the global tree** — reachable, but anchored to nothing; nobody thinks to look.

### The shattering diagnostic

Most harnesses give you **per-project memory and no global tier at all.** That absence is not neutral. It forces every universal fact into whichever project happened to be open when you learned it — so one subject fragments across many stores, each fragment partial, none authoritative, and none aware the others exist.

Check for it directly. Pick subjects that cannot possibly be project-specific — your writing voice, your shell, your tooling, a client that spans projects — and count the stores they appear in:

```bash
for pat in voice tooling shell <client> <recurring-topic>; do
  hits=$(find <stores-root> -path '*/memory/*' -name "*${pat}*.md")
  n=$(echo "$hits" | grep -c .)
  [ "$n" -gt 1 ] && { echo "### '$pat' -> $n files"; echo "$hits"; }
done
```

**Any universal subject appearing in more than one store is shattered.** The fix is not to pick a winner — each fragment usually holds something the others lack. Reconcile them into one entry in the global tree, note the contradictions the merge exposes (there will be some, and they are the valuable part), and leave one pointer where each fragment was.

Do this **before** the migration, not after. Migrating shattered knowledge just relocates the fragmentation into the tree, where it is harder to see.

## The pointer contract

Everything displaced leaves behind **exactly one line**: a trigger condition and a ref.

```markdown
- Scoring, probes, AEO doctrine → search `@project/domain-a` before changing score math
```

**Not this:**

```markdown
- Score = current state, not projection. The headline field is what a client sees
  today; the hypothetical lift stays secondary. Recent refinement: quality grades the
  rendered content while the failure stays a scoped penalty → @project/domain-a/…
```

The second version re-inflates the base with the content you just paid to move, and it creates a **second source of truth that drifts** — stale the moment the entry is edited, with nothing linking the two.

**But do not over-correct into a bare link.** [`@protocol/information-tree`](@protocol/information-tree) rule 2 is the governing constraint here: a reader who cannot see the boundary of their knowledge will either re-derive it wrongly or assume completeness, which is worse. Absence must never read as nonexistence.

So the line has to do two jobs at once — say *when to look*, and say *enough that its absence is visible*:

| | |
|---|---|
| **Too little** | `- Scoring → @project/domain-a` — the agent cannot tell whether this covers its question |
| **Right** | `- Scoring, probes, what the score claims → @project/domain-a before changing score math` |
| **Too much** | restating the decisions themselves — that is the drift trap above |

The test: name the **territory and the trigger**, never the conclusions. A reader should finish the line knowing whether their question lives behind it — and not knowing the answer.

Write triggers, not titles. `"before changing score math"` routes; `"Scoring notes"` does not.

> **Note on retrieval.** If your store indexes entry *bodies* but not `triggers:` metadata — protocol.supply does exactly this — then trigger phrases in frontmatter are decorative for search. Put the words a searcher would actually type into the body text as well. Verify by searching for a phrase you expect to work; do not assume declared triggers are indexed ones. If your harness evaluates triggers to load local memory bodies mid-session, that is a separate and complementary mechanism; it governs the residue left in the local store after a tuning pass.

## The tree

**The shape is not this protocol's to define.** [`@protocol/information-tree`](@protocol/information-tree) is the governing pattern — a light core that indexes deeper layers, stubs left under the original headings, layers bound to the core by name at the moment of need, split by audience and fetch-time rather than topic size. Read it before building; it carries the four rules and the field-paid anti-patterns, and `MEMORY.md` is one of its worked instances.

What follows is only what is **specific to the session base**. Everything general belongs to that protocol.

**One tree per scope.** A global tree that every project's config points into, and a project tree per codebase. Same shape, different roots. Resist folding the global tree into a project's — that is misroute 4, and it is how a universal convention becomes invisible the moment you switch repos. This is the base-specific consequence of the scope axis above.

**Three tiers, because the base points at exactly one thing.** Addressing schemes with a path component (`@repo/path/slug`) give you this natively.

```
ROOT      @project/root              ← the ONLY thing the base points at
          ├─ what this project is (a paragraph)
          └─ index of branches, one trigger line each

BRANCH    @project/domain-a              ← a domain index
          ├─ when to fetch this domain
          └─ index of leaves, one trigger line each

LEAF      @project/domain-a/one-decision
          └─ one decision, its why, and how to apply it
```

**Sizing.** Root: one screen. 5–9 branches. 5–12 leaves per branch. One decision per leaf.

**Stop at three tiers.** A fourth means you are modeling a filesystem instead of a retrieval path. If a branch outgrows its screen, split it into two sibling branches — do not nest.

**Shape by retrieval path, not subject taxonomy.** The question is never "what is this *about*." It is **"what will the agent be doing when it needs this?"** A librarian's tree groups pricing docs with pricing docs; a retrieval tree puts the pricing-display rule next to the checkout rule because one task touches both. Taxonomy trees look immaculate in `ls` and never get fetched, because the agent's task never phrases itself as a category name.

**Split** a branch when its index stops fitting a screen. **Merge** two leaves when you have never fetched one without the other.

**If your store can fetch a single heading** (protocol.supply does, via `?section=<slugified-heading>`), the cheapest correct shape is **branch = entry, leaf = section**. You get leaf-granular retrieval without one network object per decision — which matters, because publishing is usually rate-limited and per-entry overhead is real. Keep the same discipline inside the entry: one decision per heading, headings named for the trigger. Promote a section to its own entry only when it grows past a screen or earns triggers the branch does not share.

**Every leaf must be reachable from its branch, and every branch from the root.** An entry no index points at is not stored knowledge — it is a lost file that happens to be backed up. Audit for orphans explicitly; they are silent, and they are common.

## Public / private mirrors

When a project's knowledge is partly publishable and partly commercial, mirror the tree across two repos at **matching paths** (`@project` / `@project-internal`). Then:

- The public root's branch index carries the private branches too, marked private. Discovery must not depend on already knowing the private repo exists.
- Public entries anchor back to their private counterparts by ref.
- The split runs on **sensitivity**, never on convenience. Pricing internals, cost structure, CAC, pipeline, named relationships → private. Conventions, architecture, published behavior → public.

The failure here is an invisible split: someone finds the public branch, sees no gap, and re-derives what already exists privately.

## Order of operations

Non-negotiable, because the failure is unrecoverable:

0. **Search the library first — with several phrasings.** Most of what you are about to write already exists, and a single query that returns nothing is not evidence of absence. Search the *concept* ("light core", "index deeper layers", "token budget"), not just your name for it. Skipping this is how you publish a near-duplicate of a protocol you personally wrote three weeks ago.
1. **Measure** every surface, rank by waste.
2. **Sort by scope** and reconcile anything shattered across stores — before it moves, not after.
3. **Design** the trees — write the root and branch indexes *first*, so a leaf with no home is caught before you write it.
4. **Publish** the leaves, then the branches, then the root.
5. **Verify** by fetching every ref you are about to point at. Every one.
6. **Then** cut the base down to pointers — global config to the global root, project config to the project root.
7. **Archive** displaced source — move it aside, do not delete. Recoverable beats tidy.

One trap worth naming, because it silently breaks step 4: **a store's API may not round-trip its own entries.** Fetching an entry as structured data often returns the *body* without the title and metadata header that identify it — republish that and you mint a new entry instead of updating the old one. Rebuild the header explicitly when republishing, and confirm the returned slug and version are the ones you meant to change.

Never cut before step 5 resolves clean. A pointer to a ref that 404s is strictly worse than the bloat you removed: the agent now believes knowledge exists, finds nothing, and proceeds confidently without it.

## Failure modes

| Symptom | Cause | Fix |
|---|---|---|
| Base creeps back within weeks | Pointers written as summaries | Enforce the one-line contract |
| Agent re-derives what you migrated | Trigger words don't match how tasks phrase themselves | Rewrite triggers from real prompts |
| Entries exist, never fetched | Orphaned — no index points at them | Audit reachability root → leaf |
| Public and private say different things | Mirror drift | Anchor by ref; review the pair together |
| Immaculate tree, nobody uses it | Built on subject taxonomy | Reshape by retrieval path |
| You publish a near-duplicate of existing knowledge | One shallow search, taken as proof of absence | Step 0 — search the concept in several phrasings |
| Base shrank, sessions got slower | Only the base delta was measured | Measure fetch delta too; promote shadow cores |
| Same lesson re-learned in every project | No global tier — knowledge shattered across project stores | Reconcile into the global tree, point from global config |
| A rule fires on a project it wasn't written for | Project-scoped rule living in global config | Demote to that project's config or tree |
| Agent confidently wrong post-migration | Cut the base before verifying refs | Restore from archive, redo step 5 |

## Cadence

Re-run when the base crosses **~2,000 tokens**, when any one surface passes 50% of the base, or quarterly. Between runs, hold the line at write time with [`@protocol/memory-routing`](@protocol/memory-routing) — it picks the right home *before* a fact lands in the base, which is far cheaper than moving it later.

**The two protocols are one loop.** `memory-routing` keeps the base from growing; `context-tuning` deflates it once it has. Running the second without adopting the first guarantees you run it again next quarter.

## Get an adversarial pass before you cut

The author of a tuning plan is the worst reviewer of it. Designing the tree and executing it in one unbroken context means the same assumptions that shaped the plan also grade it — and the failure modes above feel like good judgement from the inside.

Before step 6, hand the plan to a **fresh context** — a subagent, a second session, another person — with three questions and nothing else:

1. Does this duplicate something already in the library? Give them the search, not your conclusion.
2. Pick three realistic prompts. Does search actually surface the right entry? Run them; do not reason about them.
3. What did the base *gain*, not only what did it lose?

Each is cheap, and each catches a class of error that is invisible from inside the work. A tune-up nobody has checked except the person who planned it is a draft.

*Part of the grooming ecosystem: the master pass is `@protocol/grooming`; sibling operations are `/search?q=tag:groom-op`.*

---

**Onboarding?** If an onboarding impulse sent you here, log this step on it and move its cursor — the impulse, not this page, says what comes next ([`@protocol/onboarding`](/@protocol/onboarding)).

---

*Related: `@content/web/huggingface/2026-11-27-model-managed-context-nvidia-harness` · `@protocol/groom-protocols` · `@content/web/github/2026-11-26-opus-context-fills-faster-issue-112194` · `@content/web/github/2026-11-26-autodream-silently-ignored-issue-112310` · `@protocol/bootstrap-core`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*