Four lessons have built five ways to manage the window: keep everything, trim at the boundary, clear at the ticket boundary, summarise with pinned instructions, and start each ticket fresh. Each has a cost and a way to fail. This lesson picks one with numbers, writes the decision down with its limits, and makes CI refuse a change that breaks it.
The short version: measure every candidate on the same shift, count everything it costs, check the ranking against a real model, and let a gate guard the choice. The scripted gate protects your code; a live run tests your assumptions.
By the end you will be able to:
- run every candidate policy on one shift and read window, cache, cost, tickets handled and retention side by side
- explain why the cheapest policy changed with the model and between scripted and live runs
- record a policy and its limits in
policy.jsonand gate it in CI - say what a green build proves and what it doesn't
Before you start. You need the policies from lessons 3 and 4 and the cache-hit rate from lesson 2. The companion folder adds copilot/harness.py, copilot/gate.py, pick_policy.py, policy.json, check_policy.py, scripts/simulate_regression.py, scripts/live_compare.py and ci/github-actions.yml. Everything except the two live scripts runs without an API key.
1. One shift, five policies, one report
copilot/harness.py runs each candidate on the same 24 tickets with a fresh model, and so a fresh cache, and reduces the run to one row:
async def measure(name: str, model: ModelClient, **kwargs: Any) -> PolicyReport:
r = await run_shift(model, **kwargs)
g = grade(r.tools)
# Window and cache figures are the copilot's own requests; cost counts everything,
# including summariser and compaction calls (turn -1 and 0).
own = [q for q in r.requests if q.turn >= 1]
prompt = sum(q.usage.prompt_tokens for q in own)
return PolicyReport(
name=name,
requests=len(own),
mean_window=prompt // max(1, len(own)),
final_window=own[-1].usage.prompt_tokens if own else 0,
cache_hit=sum(q.usage.cache_read_tokens for q in own) / prompt if prompt else 0.0,
cache_write_tokens=sum(q.usage.cache_write_tokens for q in own),
usd=r.usd,
handled=g.handled,
retention=g.retention,
)Two numbers decide whether a policy is acceptable at all. Tickets handled counts tickets that ended with a draft reply. Retention is the share of handled tickets on which both standing instructions held: no Corvid refund, and SHIFT-B7 at the end of every draft. Among acceptable policies, cost per shift decides, and the window and cache columns explain why.
2. Charge the summariser too
A running summary looks free in lesson 4's table, because RuleSummariser runs in code. A real summariser is a model call after every ticket. Leave it out and summary+pin looks cheaper than it is, so this lesson's run_shift charges each summary at Haiku rates, from what the summariser reads and writes:
seen = tokens(json.dumps(log.turns)) + tokens(previous or "")
u = Usage(input_tokens=seen, output_tokens=tokens(window.summary))
result.requests.append(Request(ticket["id"], -1, u, _usd(SUMMARISER_MODEL, u)))That is an estimate, not a bill. The live run below calls the summariser for real but prices each summary with this same estimate, so its summary+pin cost is part measured, part estimated.
3. Run pick_policy.py on Sonnet and Haiku
cd build-a-long-running-support-copilot/03-production/05-pick-a-policy-with-numbers
uv run python pick_policy.pyclaude-sonnet-5-5
policy mean win last win hit cache wr $/shift handled retention
raw 12226 23662 98.1% 24142 0.3099 24/24 100%
trim 6920 13256 98.1% 13736 0.2297 24/24 100%
clear 6871 13018 95.1% 35305 0.2810 24/24 100%
summary+pin 1241 1703 70.2% 38441 0.2352 24/24 100%
fresh 1065 1381 59.1% 45272 0.2445 24/24 100%
claude-haiku-5-5
policy mean win last win hit cache wr $/shift handled retention
raw 12226 23662 98.1% 24142 0.0217 24/24 100%
trim 6920 13256 98.1% 13736 0.0150 24/24 100%
clear 6871 13018 95.1% 35305 0.0174 24/24 100%
summary+pin 1241 1703 70.2% 38441 0.0171 24/24 100%
fresh 1065 1381 59.1% 45272 0.0126 24/24 100%Every policy handles all 24 tickets and keeps both instructions, so cost decides, and it decides differently on the two models. On Sonnet, trim is cheapest: it halves the window and keeps a 98% cache-hit rate, because nothing is ever rewritten. On Haiku, fresh is cheapest, even though it rebuilds the cache at every ticket.
The windows and token counts are identical on both runs; only the prices differ, and a uniformly cheaper model would change no ranking. What changes is the ratio between them. A cache read costs 0.05 times the input price on Sonnet 5.5 but 0.1 times on Haiku 5.5, while a cache write is 1.25 times on both. trim keeps a large window and reads it from the cache on every request; fresh keeps a small one and writes it again at every ticket. Where reads are relatively cheap, as on Sonnet, holding the window wins. Where they cost twice as much relative to everything else, as on Haiku, starting small wins.
Real models moved the Sonnet answer, too. Experiment 7 found fresh cheapest on both models: $0.41 a Sonnet queue against $0.47 for trim, and $0.021 against $0.026 on Haiku. A likely reason, not one experiment 7 measured: real agents write longer turns than the scripted copilot, which makes a large window more expensive to carry, as the live Haiku run's 19,640-token raw window against the scripted 12,226 suggests. So the scripted Sonnet ranking is the one result here that real-model evidence contradicts, and the live Sonnet run below confirms it.
4. Check the scripted ranking against a live run
The scripted copilot is a model of Claude. scripts/live_compare.py runs one real shift per policy and saves the numbers, stopping before any request once the run has spent its cap:
uv run python scripts/live_compare.py --model claude-haiku-5-5 --cap 2.00The committed run, on Haiku 5.5, cost $0.14 for all five:
| Policy | Mean window | Cache hit | $/shift | Handled |
|---|---|---|---|---|
| raw | 19,640 | 97.9% | $0.0292 | 24/24 |
| trim | 12,223 | 98.1% | $0.0213 | 24/24 |
| clear | 17,762 | 95.0% | $0.0431 | 24/24 |
| summary+pin | 2,686 | 68.5% | $0.0320 | 22/24 |
| fresh | 1,891 | 68.3% | $0.0175 | 24/24 |
The direction holds where it matters: fresh is cheapest and trim beats raw. Two rows moved. Live clear costs more than raw: the real copilot writes long assistant turns, so clearing tool results shrinks its window by only 10%, while the rebuild at every ticket rewrites those turns too. And summary+pin handled 22 of 24 tickets, where the scripted run handled all 24. Retention held on every ticket the copilot handled, under every policy.
The same script on Sonnet 5.5 settles the question the scripted run left open, for $1.94:
uv run python scripts/live_compare.py --model claude-sonnet-5-5 --policies trim,fresh,raw,clear,summary+pin| Policy | Mean window | $/shift | Handled |
|---|---|---|---|
| fresh | 1,951 | $0.3250 | 24/24 |
| trim | 14,700 | $0.3458 | 24/24 |
| summary+pin | 2,469 | $0.3779 | 24/24 |
| clear | 13,697 | $0.4378 | 24/24 |
| raw | 22,853 | $0.4567 | 24/24 |
Live, fresh is cheapest on Sonnet too, 6% under trim, with every ticket handled and both instructions kept. The scripted Sonnet run put trim first; the live run, experiment 7 and the live Haiku run all put fresh first. --policies runs the decisive pair first, so a cap can't cut them off.
That is what the live run is for. The scripted shift tells you how your code behaves; the live run tells you whether the model behaves the way your code assumes, and here it changed the decision.
5. What the first live run caught
The committed results are the second live run. The first, kept as results/live-claude-haiku-5-5.before-fixes.json, found a summariser that failed quietly: summary+pin handled 19 of 24 tickets and cost $0.0368. The summariser had never been given the standing instructions, so it took the SHIFT-B7 sign-off for an error and told the copilot to remove it. It counted drafts awaiting review as open work. And thinking pushed its output past max_tokens, cutting summaries off mid-text.
None of that showed in the scripted harness, because RuleSummariser can't make those mistakes. The second run used three fixes, all in ClaudeSummariser:
- Give the summariser the rules. Its prompt now includes the standing instructions, marked as pinned elsewhere and never to be treated as mistakes.
- Define finished. Its system prompt says a ticket is finished once its draft is saved, that human review is never an open item, and to give each finished ticket one line.
- Fail loudly.
max_tokensis 4,096 to leave room for thinking, and a summary that stops onmax_tokensraises instead of passing on half a summary.
6. Write the decision into policy.json and gate it
The decision is a file, so changing it is a reviewed change:
{
"policy": "fresh",
"model": "claude-sonnet-5-5",
"max_usd_per_shift": 0.27,
"min_cache_hit": 0.55,
"min_handled": 24,
"min_retention": 1.0
}fresh on Sonnet is the decision the live run supports: cheapest on real Sonnet, cheapest on real Haiku, and nothing carried between tickets to go stale. The gate replays it on the scripted shift, so the limits come from that replay, $0.2445 a shift and a 59.1% cache-hit rate, with about 10% headroom on cost. A cache-hit floor of 90% would fail a policy that rebuilds its small window at every ticket by design. The file started as trim, the scripted Sonnet winner, and changed when the live run disagreed: that history is the point of keeping the decision in a reviewed file.
copilot/gate.py turns the limits into named failures:
def failures(cfg: PolicyConfig, r: PolicyReport) -> list[str]:
out = []
if r.retention < cfg.min_retention:
held, need = f"{r.retention:.0%}", f"{cfg.min_retention:.0%}"
out.append(f"standing instructions held on {held} of tickets, need {need}")
if r.handled < cfg.min_handled:
out.append(f"{r.handled} tickets handled, need {cfg.min_handled}")
if r.usd > cfg.max_usd_per_shift:
out.append(f"${r.usd:.4f} per shift, budget ${cfg.max_usd_per_shift:.4f}")
if r.cache_hit < cfg.min_cache_hit:
out.append(f"cache hit {r.cache_hit:.1%}, need {cfg.min_cache_hit:.0%}")
return outThe config is a small dataclass loaded from the file, and check() replays its policy on the scripted shift and returns the report and its failures:
@dataclass(frozen=True)
class PolicyConfig:
policy: str
model: str
max_usd_per_shift: float
min_cache_hit: float
min_handled: int
min_retention: float
@classmethod
def load(cls, path: Path) -> PolicyConfig:
return cls(**json.loads(path.read_text()))
async def check(cfg: PolicyConfig, **overrides: Any) -> tuple[PolicyReport, list[str]]:
"""Run the configured policy; `overrides` lets tests inject a regression."""
kwargs: dict[str, Any] = {"policy": cfg.policy, **overrides}
report = await measure(cfg.policy, ShiftModel(model=cfg.model), **kwargs)
return report, failures(cfg, report)check_policy.py loads policy.json (its CONFIG path) and exits 1 if anything fails:
uv run python check_policy.pypolicy mean win last win hit cache wr $/shift handled retention
fresh 1065 1381 59.1% 45272 0.2445 24/24 100%
gate: passedci/github-actions.yml runs the tests and then the gate on every pull request, with no keys:
- run: uv run pytest
- run: uv run python check_policy.py # exits 1 when the chosen policy regressesflowchart LR
PR["pull request"] --> T["uv run pytest"] --> G["check_policy.py"]
P["policy.json"] --> G
G --> R["replay the scripted shift"] --> F{"limits met?"}
F -- yes --> OK["merge"]
F -- no --> X["fail, naming each limit"]7. Break it on purpose: simulate_regression.py
Three changes that look harmless in review, run through the gate:
uv run python scripts/simulate_regression.pyadd the time to the system prompt:
$0.4046 per shift, budget $0.2700
cache hit 0.0%, need 55%
switch to clear with a shorter placeholder:
1 tickets handled, need 24
switch to a summary that keeps only the work:
standing instructions held on 0% of tickets, need 100%Each failure names the limit it broke. The clock is lesson 2's silent invalidator, the placeholder is lesson 3's, and the summary is lesson 4's. None of them raises an error in the copilot itself. Only the gate notices.
8. What a green build proves, and what it doesn't
A green build proves that your code still builds the windows you decided on: the layout keeps the cache, the placeholder and summariser pass the scripted copilot, and the scripted cost per shift is within budget. It catches the regressions in your code that this tutorial has named.
It doesn't prove how Claude will behave. The scripted copilot can't misread a summary or write long turns, and both happened live; live summary+pin also handled 22 of 24 tickets where the scripted run handled 24. So re-run live_compare.py when you change the model, a prompt, a tool or the summariser. On Haiku it costs a few cents.
Nor does it say anything about context rot beyond what experiment 7 measured: no decline up to a 72–73k-token window, on one family of synthetic support tickets, with short labelled instructions and independent tickets. If your shifts grow well past that, measure quality as well as cost.
9. Exercise: record your own policy for Haiku
Write policy.haiku.json for claude-haiku-5-5, choosing the policy and limits from pick_policy.py's Haiku table. In a test, load it with PolicyConfig.load(Path("policy.haiku.json")), run report, problems = await check(cfg) and assert problems == []. To gate it in CI as well, point CONFIG in check_policy.py at your file, or add a second step that loads it. Then lower max_usd_per_shift until it fails, and read the message.
Expected result. fresh is the cheapest acceptable Haiku policy at $0.0126 a shift. With a budget of $0.014 it passes; at $0.012 the gate fails with $0.0126 per shift, budget $0.0120. Its cache-hit rate is 59.1%, so set min_cache_hit no higher than that, or the gate fails on a policy that is working as designed.
Hint. A limit is a statement about your workload. Set each one from a measurement, leave a little headroom, and write the reason next to it in the pull request.
10. Summary
- Count everything. Cost per shift includes the summariser's calls; leaving them out flatters
summary+pin. - Let the live run decide. Scripted,
trimwon on Sonnet; live,freshwon on both Sonnet and Haiku, andclearcost more thanraw. - Write the decision down.
policy.jsonholds the policy and its limits, andcheck_policy.pyturns a regression into a named failure in CI. - Keep a live check. The gate guards your code; only a live run tests the model.
That completes the copilot: a prompt laid out for the cache, a window trimmed or replaced on purpose, summaries and memory that can't fail silently, and a policy chosen and guarded with numbers.

