~15 min · prompt-caching, system-prompt, context-engine, cost
Level 0Visitor
0 XP0/44 lessons0/11 achievements
0/100 XP to next level100 XP to go0% complete
One Byte Is Enough
Every provider the engine talks to can cache a prompt it has already seen, and charges less and answers faster for the part that matches. What counts as matching differs. Z.ai, which serves the GLM brain, matches the whole system field exactly; a probe showed that one byte changing per turn forfeits about 100K tokens of cache. Anthropic, OpenAI and Google match prefixes, where a changed byte costs everything after it. Either way the rule is strict.
So since 2026-08-14 (coop #117 and #119) the engine keeps a contract: the system prompt is byte-identical across every turn of a conversation. Nothing volatile may go there, and the prefix-stability tests fail loudly if someone adds it. The contract assumes the conversation's own settings hold still; the end of this lesson shows where Master Chief bent it, what that cost, and how it stopped.
Where the Moving Parts Go
Plenty does change per turn. All of it rides the current user message instead, prepended to Dad's words in this order:
Per-turn content
Why it moves
Artifacts the message names
they belong to this message alone
The clock
minute resolution
The conversation timeline
the gaps between turns grow
Retrieved memory
shaped by this turn's words
Briefs the memory librarian finished in the background
they arrive whenever they are done (lesson 3)
Where Dad was when he sent it
the phone attached a location fix
In Master Chief: the doorway, a Current origin: line
Dad switches devices between turns
In Master Chief: the reasoning this turn really runs at, when it differs from the vessel's standing level
one doorway's composer can ask for another effort
In Master Chief: one line of what waits for Dad's decision, at most 400 characters, present only when something waits
approvals arrive and get decided
In Master Chief: the turn's notes (a client's own addendum, the app doorway's rules, a Coop escalation's brief)
each belongs to one doorway or one turn
Voice blocks
this turn was dictated, or wants a spoken reply
That slot is sent and never persisted. The stored row keeps Dad's words alone, so replaying an old turn never drags along an old clock or a stale retrieval. Voice and text switch freely inside one conversation for the same reason: the system prompt never learns which kind of turn this is.
Moving retrieval into a user position had a cost of its own. Text inside a user message reads as something the speaker just said, so the retrieved block is headed in so many words: reference material, background, not the current task. That framing helped at the end of system; in the user slot it is load-bearing.
What It Bought, Measured
The commit that moved the clock and retrieval out measured a real route on the GLM brain, with 65-second gaps so the minute ticked between turns, which used to be fatal. Turn one paid 109,071 tokens cold. Turns two and three each read 108,224 from cache, leaving about 850 uncached tokens per turn: the clock, the retrieval, and the newest history. The day before, every human-paced turn paid the whole ~100K cold.
Two Five-Minute Clocks
Don't confuse the engine's cache with the provider's. The engine keeps its vault-built base for five minutes so it does not reread hundreds of files every turn. When that expires it rebuilds, and an unchanged vault rebuilds the same bytes. An edited vault reaches the prompt within five minutes, and that one turn pays a cold prefix: a price paid on purpose, once per edit. The provider's cache lifetime is the provider's business. Anthropic's default also happens to be five minutes; coincidence, not design.
The Exception, and Its Bill
Master Chief used to bend this contract. Its route appended a system addendum to every Chief turn: the Chief's standing instructions plus one line, Current origin:, naming the doorway this turn came through (the surface and the app thread). The chat route joined that addendum onto the system prompt, so the system field changed whenever the doorway changed between turns: phone, then browser, then Telegram. The origin does have to reach the model, because app-bound tools act on this turn's doorway and nobody else's. When this quest was first written nobody had measured what the line cost, and the lesson filed it as a known trade-off.
Dad measured it without meaning to. On 2026-10-17 every brain felt slow before it started thinking, and he asked whether something volatile sat at the front of the prompt again. It did. That evening six doorway switches each re-wrote 330K to 415K tokens of the Chief's prompt with a cache read at or near zero, while consecutive turns from one doorway read 94 to 99.8 percent from cache. The cache had never broken turn to turn; only the switches broke it. The fix (2026-10-18) moved the line to where the clock already lived. The admitted turn keeps its doorway in its own task context, turn_origin_line() renders the same Current origin: line, and the context engine adds it to the per-turn block that rides the current message. The Chief's addendum is now the same bytes from every doorway, and a test says so: two doorways, one identical addendum, each doorway named in its own turn context.
One mover remains by design, and you should know it. The vessel meta block at the very top names the brain and the model this turn runs on, so a turn on another vessel (Master Chief's whole point) or a changed model rewrites the first lines, which costs a prefix matcher nearly everything. That one is accepted: a different model never shared the cache anyway. The reasoning level the block names is, in a Chief turn, the vessel's standing level; a turn that runs at another level says so in its own context. And the artifacts a message references ride that message, like the clock.
A cache contract holds only where something checks the bytes. The engine's tests guarded the base prompt. Master Chief's origin line came in at the addendum seam, which the contract's own docstring never named, and it cost six full rewrites in one evening before anyone looked. Decide what holds still, then make a test say so.
Code
Verbatim excerpts from the context engine: the contract in the build docstring, and the line where per-turn context joins the last user message·python
# from the build_system_prompt docstring
"""
PREFIX-CACHING CONTRACT (coop #117/#119, 2026-08-14): this string
must be byte-identical across every turn of a conversation.
Z.ai matches the whole ``system`` field exact (probe-verified:
one per-turn byte forfeits ~100K of cache); Anthropic/OpenAI/
Google match prefixes where the same rule holds a fortiori.
Per-turn content — the clock and the RAG retrieval — therefore
lives in ``build_turn_context`` and rides the current user
message (sent, never persisted). Do not add anything volatile
here; the prefix-stability tests fail loudly if you do.
"""
# the end of prepare_turn_messages
prepared[-1] = replace(
prepared[-1],
content=f"{turn_context}\n\n{prepared[-1].content}",
)
return prepared
Verbatim excerpts, as of 2026-10-27: the admitted turn's doorway line, the block it leads in that turn's own context, and where the context engine adds the block to the current message·python
# services/master_chief.py
def turn_origin_line(conversation_id: str | None) -> str | None:
"""The admitted Chief turn's doorway, as a line of that turn's context.
It rode the system prompt's Chief addendum until 2026-10-18 (todo #501),
where every doorway switch changed the prompt's bytes: the Chief's next
Claude turn read none of its ~400K-token cache and wrote all of it again
(six such switches on 2026-10-17, each a full re-write). The turn context
is sent with the current message only, so the prefix stays the same from
any doorway. None outside an admitted Chief turn.
"""
active = admitted_turn(conversation_id)
if active is None:
return None
return "Current origin: " + json.dumps({
"origin_surface": active.origin_surface,
"origin_conversation_id": active.origin_conversation_id,
})
def turn_context_block(conversation_id: str | None) -> str | None:
"""Everything the admitted Chief turn adds to its own context: the
doorway line, then the reasoning this turn runs at when it differs from
the system prompt's, then what waits for Dad's decision, then the turn's
notes. None outside a Chief turn."""
origin = turn_origin_line(conversation_id)
if origin is None:
return None
state = admitted_turn(conversation_id)
parts = [origin]
if state.reasoning_note:
parts.append(state.reasoning_note)
# What waits for Dad's decision, read from the last source tick: present
# only when something waits (coop #668).
from services import waiting_for_dad
waiting = waiting_for_dad.chief_line()
if waiting:
parts.append(waiting)
parts.extend(state.notes)
return "\n\n".join(parts)
# context/engine.py, prepare_turn_messages, building the per-turn context
# The Chief turn's doorway (todo #501), with the reasoning it runs at
# and its per-turn notes (review #597 M1): per turn, never in the
# system prompt, where a doorway switch re-wrote the whole cached prefix.
from services import master_chief
chief_block = master_chief.turn_context_block(conversation_id)
if chief_block:
turn_context = f"{turn_context}\n\n{chief_block}"
A minimal sketch: the system bytes hold across a minute tick while the clock rides the message, and the stored rows stay clean (runs on Python 3.9+)·python
"""A minimal sketch: a system prompt that holds still, and a turn context that does not."""
from __future__ import annotations
import hashlib
from datetime import datetime, timedelta, timezone
KST = timezone(timedelta(hours=9))
VAULT = "Identity, shared rules, core memories: the same bytes on every turn."
def system_prompt() -> str:
return VAULT # nothing volatile may enter here
def turn_context(now: datetime, retrieved: str | None) -> str:
parts = [f"[Current time: {now.astimezone(KST):%A, %B %d, %Y, %I:%M %p} KST]"]
if retrieved:
parts.append("## Retrieved Memory - Reference Material (background, NOT current task)\n\n" + retrieved)
return "\n\n".join(parts)
def prepare_turn(history: list[dict], text: str, now: datetime, retrieved: str | None):
sent = history + [{"role": "user", "content": f"{turn_context(now, retrieved)}\n\n{text}"}]
stored = {"role": "user", "content": text} # the row keeps Dad's words alone
return sent, stored
history: list[dict] = []
start = datetime(2026, 1, 5, 21, 14, tzinfo=KST)
for minute, (text, retrieved) in enumerate([("Morning plan?", None), ("And the build?", "a note about builds")]):
sent, stored = prepare_turn(history, text, start + timedelta(minutes=minute), retrieved)
digest = hashlib.sha256(system_prompt().encode()).hexdigest()[:12]
print(f"turn {minute + 1}: system sha256 {digest} | sent: {sent[-1]['content'].splitlines()[0]}")
history.append(stored)
history.append({"role": "assistant", "content": "(reply)"})
print("stored rows carry a clock:", any("Current time" in row["content"] for row in history))
In an app of yours that calls a model API, log a sha256 of the system prompt on every request for a day of normal use. List every reason the hash changed. Move each per-request item (dates, user names, retrieved snippets, feature flags) out of the system prompt and onto the newest user message, keep the stored history free of it, and compare the cached-token counts the API reports before and after.
Hint
Anthropic reports cached tokens as cache_read_input_tokens in the usage block; OpenAI reports them under prompt_tokens_details.cached_tokens. Most providers only cache prompts above a minimum length, so test with a realistically long system prompt.
Progress
Progress is local-only — sign in to sync across devices.