Domain 5 · 15% of exam
Context Management & Reliability cheat sheet
The idea this domain hangs on
Every task here defends against one enemy: information silently disappearing.
| Where information is lost | The defence |
|---|---|
| Progressive summarisation | Persistent case-facts block (5.1) |
| The middle of a long input | Key findings first, headed sections (5.1) |
| Verbose tool results | Trim to the relevant fields before they enter history (5.1) |
| An agent that gives up or carries on quietly | Explicit escalation criteria (5.2) |
| An error reduced to "failed" | Structured error context: type, attempt, partial results, alternatives (5.3) |
| A long exploration session | Subagent delegation + scratchpad files (5.4) |
| A 97% aggregate accuracy figure | Accuracy by document type and field + stratified sampling (5.5) |
| A synthesis step | Claim-source mappings (5.6) |
| Two conflicting statistics | Both values kept, each with its source (5.6) |
- An option that destroys information (picks one of two values, returns empty on failure, summarises numbers into adjectives, drops a source) is wrong. One that keeps it in structured form is probably right.
5.1 — Context window management
| Model | Context window | Max output |
|---|---|---|
| Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2 (and earlier 5.x), Opus 4.6–4.8, Sonnet 4.6 | 1,000,000 tokens (default, no beta header) | 128k (300k via Batches beta on Opus 5.5/5, Sonnet 5.5/5, Haiku 5.5, Opus 4.6–4.8, Sonnet 4.6) |
| Opus 4.5, Sonnet 4.5, Haiku 4.5 | 200,000 tokens | 64k |
- 1M windows bill at standard pricing, except Haiku 5.5: prompts over 100,000 tokens cost more.
- Counts toward the window: system prompt + every message (incl. tool results/images/docs) + tool definitions + output (incl. thinking). Cached tokens still count — caching changes cost, not window usage.
- Overflow: input alone > window → 400 invalid_request_error. Input + max_tokens > window (Claude 4.5+) → request accepted, stops with stop_reason: "model_context_window_exceeded". Use the token counting API (
/v1/messages/count_tokens, free) to stay under limits. - Context rot: accuracy/recall degrades as tokens grow — driven by a limited "attention budget" and n² pairwise attention stretching thin. Curate, don't just expand.
- Context awareness (Sonnet 5/4.6/4.5, Haiku 4.5): models auto-track remaining token budget via API-injected tags — nothing to enable.
- Compaction = summarise a conversation nearing the limit, reinitiate with the summary. Risk: over-aggressive compaction loses subtle context that matters later. Lightest-touch form = tool result clearing. API side: context editing (beta: tool result clearing, thinking block clearing) and server-side compaction (beta, Claude 4.6+).
- Progressive summarisation trap: destroys amounts/dates/IDs. Fix = persistent case facts block, outside summarised history, never summarised, rebuilt by your code from current state on every request (not a session-start snapshot, not model memory).
- Request layout: case facts block → (summarised) history → newest turn. Aggregated input: key findings summary (with the numbers) → headed detail per source → task at the end.
- Lost in the middle: models handle beginning/end reliably, miss the middle. Fix is structural — key findings summary FIRST, then detailed sections with headers. Not a prompt reminder.
- Lost in the middle (position in one input → reorder + headers) ≠ attention dilution (too many targets in one pass → split into passes, Task 1.6/4.6).
- Tool result trimming: strip 40+ field lookups to the 5 relevant fields before they enter history; once in, a result is re-sent every turn until something clears it. Trim by task relevance, not size; one field list per intent.
| Where the trim runs | Verdict |
|---|---|
PostToolUse hook replacing the result via updatedToolOutput | Best general answer: covers every tool; keep the tool's output shape |
| Inside the tool / MCP server | Fine if you own it and every caller wants the same fields |
Your own loop, before appending the tool_result | Fine for a hand-written loop |
| Clean-up after append, at summarisation time, or after the run | Too late: already sent and counted |
- API is stateless — every request needs full conversation history; dropping turns breaks coherence (contradictions, re-asking, forgotten commitments). Compress by restructuring, not by deleting: summarise the narrative, keep the facts verbatim.
- Upstream agents return structured findings (claim, source, relevance) with dates, source locations and method — not raw pages plus reasoning. Compact findings without that metadata = the summarisation trap one agent downstream.
5.2 — Escalation & ambiguity resolution
Three valid triggers: explicit human request (escalate immediately, zero investigation, any phrasing, any point) · policy gap or exception request (policy silent or ambiguous, or the customer asks for an exception; a clear "no" the customer accepts is just explained) · inability to make progress (after a genuine attempt).
Two unreliable triggers: sentiment/frustration detection (doesn't correlate with complexity) · self-reported confidence (poorly calibrated — confident on hard cases, hedges on easy ones).
Not triggers either: multi-part request (decompose, escalate only the stuck item) · money involved (a threshold gate in a hook, Task 1.5) · high turn or tool-call count (effort, not authority).
Frustration nuance:
| Situation | Action |
|---|---|
| Frustrated + resolvable issue | Acknowledge, offer resolution once, don't escalate |
| Customer then asks for a human | Now escalate — no second offer |
| "I want a human" from the start | Escalate immediately, no investigation |
- Ask or escalate: unsure of a fact the customer can supply → ask a clarifying question · unsure of policy → escalate.
- Silent is not prohibited: refusing a request policy doesn't address invents policy as much as granting it.
- Ambiguous customer match (multiple records): ask for an identifier that partitions the candidates (order number, postcode, card last four). Never select by recency/activity heuristic, never read the candidates out — privacy risk. The tool returns every match; retrying the lookup changes nothing.
- Proportionate first fix: explicit escalation criteria + 2–4 few-shot examples with reasoning in the system prompt, before classifiers or sentiment models. At least one example must resolve; don't let tone carry the decision.
- Deterministic enforcement: PreToolUse hook > prompt instruction, when escalation/compliance must be guaranteed.
permissionDecision:allow/deny/ask/defer.canUseToolfires only when the flow falls through to a prompt — auto-approved calls skip it. - Hook priority: deny > defer > ask > allow; a deny blocks even under
bypassPermissions. - Structured handoff must include: customer ID, root cause analysis, recommended action (+ amount) — the human has no transcript access.
5.3 — Error propagation in multi-agent systems
Four structured error elements: failure type · what was attempted · partial results · alternative approaches. Design test: the coordinator's next action is derivable from the error alone.
Four failure types: transient (retry locally with backoff) · validation (correct the input, never resend unchanged) · business (don't retry; explain the refusal, customer-friendly, and take the permitted alternative, often escalation) · permission (propagate at once, resource named). Learn four, not more.
- Field names (
failureType,errorCategory,isRetryable) are illustrative;errorCategory/isRetryableare an application convention, not MCP spec fields. Whether validation is "retryable" is unsettled — answer by behaviour. - Access failure (timeout/connection error) → consider retry. Valid empty result (query ran, found nothing) → this IS the answer, no retry. Report wording: "No sources found on X" vs "X not covered: retrieval failed". State it by status, not by
nullvs[]convention. is_error: trueintool_resultcontent = client-tool failure signal. Server tools (web_search, code_execution, etc.) — Anthropic handles their errors; you don't needis_errorfor them.- Invalid/malformed tool call → Claude auto-retries 2-3 times with corrections before apologising.
- Anti-pattern 1 (worst): silent suppression — empty results marked success; invisible, coordinator never retries. Logging first doesn't help: the log reaches an operator, not the coordinator.
- Anti-pattern 2: workflow termination — killing the whole pipeline on one failure, discarding completed work.
- Correct pattern: subagents attempt local recovery for transient failures only; propagate unresolved errors with what-was-attempted + partial results. Partial results always travel and accumulate across attempts.
- Sample Q8 option B pattern: correct + fatal — local backoff retry is right, the generic "search unavailable" status afterwards is wrong. Read every clause.
- Coverage annotations: a status per topic (well-supported · limited · gap) with the reason; a gap entry ends with an explicit no-claim. Not one blanket caveat, not extrapolated estimates.
- Agents are stateful — errors compound; you can't just restart from scratch. Fix = resume-from-failure / durable execution. One bad step can send an agent onto an unpredictable trajectory (the "prototype-to-production gap").
5.4 — Codebase exploration & context degradation
- Rule: anything that must survive the session must live outside the session (scratchpad, manifest, distilled summaries).
- Context degradation: model starts saying "typical pattern" instead of citing the specific class/file it found earlier; inconsistent answers; vague names; re-reading files; no
file:line. Not a token-limit problem — a bigger window buries the specifics deeper. - Degradation (a long session, over time) ≠ attention dilution (one pass over too many items, e.g. 14 files → focused passes, Task 4.6).
- Scratchpad files = structured note-taking / "agentic memory" (Anthropic's term). Best fit: iterative work with clear milestones. Set up from the start; write exact names and
file:lineafter each discovery, read back before the next step. Written but never read = a log, not a mitigation. - Subagent delegation: primary value is context isolation, not parallelisation. Subagent may burn 10k+ tokens exploring, returns only a condensed structured summary (not transcripts or raw files). Fresh context at spawn — only the Agent tool's prompt string passes in, so the question must be self-contained.
- Explore subagent (Claude Code): built-in, read-only, runs on the parent's model (isolation, not a stronger analyst), starts without CLAUDE.md.
- Summary injection between phases: inject Phase 1's findings into Phase 2 subagent prompts; prevents waste (cold-start duplication) and incoherence (contradicting Phase 1).
/clear— empty context, previous conversation saved, resumable via/resume./compact [instructions]— replaces history with a (optionally focused) summary, e.g./compact Focus on the API changes. Scratchpad first, then compact (a summary is lossy); run it during the session, not at the limit.- After
/compact: project-root CLAUDE.md re-injected from disk; nested CLAUDE.md andpaths:rules reload when a matching file is next touched; conversation-only instructions survive only as far as the summary keeps them. - Checkpoints: auto-created per prompt;
/rewindrestores code/conversation/both — "local undo," not git. Blind spot: a file that only Bash commands changed isn't tracked; Bash changes to a file Claude's file tools already edited are rewound. - Crash recovery manifest: explored paths + key findings + phase + next steps, written after every significant step (not per phase, on shutdown or at a context threshold). On resume: skip complete phases, re-delegate pending items, inject phase outputs + scratchpad path.
- Manifest ≠
--resume:--resumerestores one conversation with its (possibly stale) tool results; a manifest restores structured state across many agents.
| Symptom in the stem | Technique |
|---|---|
| Verbose discovery filling the main context | Subagent delegation (Explore) |
| Answers drift to "typical patterns" | Scratchpad, re-read before answering |
| Notes accurate but answers still generic | Add the missing read-back |
| Context well filled mid-session | Write the scratchpad, then /compact |
| Phase two redoes or contradicts phase one | Phase summaries injected into prompts |
| Long run died partway | Manifest-based crash recovery |
5.5 — Human review & confidence calibration
- Aggregate metrics trap: 97% overall can hide 40-60%+ error rates on specific document types (handwritten receipts, international formats). The headline is a volume-weighted mean: a small segment barely moves it and can still own most of the errors. Always validate by document type AND field together — either cut alone is still an average.
- Decide per segment (partial automation): automate what clears the bar; keep failing document types and failing fields in review. Not all-or-nothing.
- Validation sequence: measure by type+field → calibrate confidence (labelled validation sets) → set thresholds → stratified sampling → only then reduce review.
- Stratified sampling must include high-confidence extractions — that's the automated blind spot where novel error patterns go undetected. A flat or proportional draw follows volume (200 draws at 2% ≈ 4): guarantee a minimum per stratum, draw at random inside it.
- Raw confidence ≠ calibrated confidence. 0.90 on dates might mean 94% accuracy; 0.90 on amounts might mean 82%. Calibration requires ground-truth comparison.
- Thresholds per field and per document type; a pooled calibration curve is the same mistake as one global threshold. Confidence is field-level, not document-level.
- Labelled validation set: labelled by domain experts, stratified to over-represent rare types, held out from prompt tuning and few-shot examples.
- Recalibrate when the model, prompt/schema or document mix changes, when sampling shows drift, and on a schedule. A new document type with no labels → full review.
- Routing triggers: low calibrated confidence or an ambiguous/contradictory source (
conflict_detected, an"unclear"value, a validation failure retry couldn't fix). - 5.2 vs 5.5: a raw self-reported score as a decision rule is the anti-pattern; a per-field score calibrated on labels is the design.
- LLM-as-judge template: one call, one prompt, 0.0-1.0 score + pass/fail grade — found "the most consistent and aligned with human judgements" (an analogy for field confidence, not the same task).
- Evaluation rubric dimensions (transferable to validation design): factual accuracy, citation accuracy, completeness, source quality, tool efficiency.
- Human testing stays essential even with automated evals — it catches edge cases evals miss.
detected_patternfield: tags what triggered a finding, enabling systematic dismissal-pattern analysis instead of one-off review.- False positives eroding trust (4.1): category-level fixes — temporarily disable the noisy category while improving its prompt, explicit criteria instead of confidence filtering, severity levels with concrete examples.
- Reviewer capacity: route highest-uncertainty items first (calibrated, not raw), re-sorted dynamically — never spread capacity evenly.
- Strict schema for confidence:
additionalProperties: falserequired;minimum/maximumnot supported, so check the 0–1 range in code.
5.6 — Information provenance & multi-source synthesis
Claim-source mapping fields (all required): claim · source URL · document name · relevant excerpt · publication date (+ data-collection date where it differs).
- Two dates: published (release) and collected (period measured); a 2026 report can carry 2023 data. Neither is when your pipeline retrieved the page. Dates explain a difference, they don't rank sources.
- Get the shape at the source: schema-bound structured output (fields required,
tool_choiceforcing the tool), not prose parsed later. A post-hoc "find a source for this claim" step manufactures provenance. - Attribution most often dies at synthesis (step 3) — compression/paraphrasing drops the mapping unless explicitly preserved. Citation requirement binds per claim: "mention sources" or a bibliography fails it; counting markers isn't checking them.
- CitationAgent pattern: a dedicated post-synthesis stage whose only job is locating citations — routes around the synthesis attribution-loss risk.
- Source quality heuristics: guard against SEO content farms outranking authoritative sources — correct claim-source mapping to a bad source is still misleading.
- Artifact/filesystem output pattern: large subagent outputs bypass the coordinator, preserving fidelity and cutting token overhead from repeated copying.
- Conflicting sources: annotate BOTH values with attribution — never arbitrarily pick, average, or prefer "more recent", larger sample or bigger name.
- Who reconciles: analysis annotates both values · coordinator decides before synthesis · synthesis renders the decision with attribution. A "recommended value" from analysis is still analysis resolving it.
- Detect conflicts by measure, period and population, not by wording.
- Temporal awareness: different publication/collection dates can explain different numbers as a trend, not a contradiction — dates are required in structured outputs.
conflict_detectedboolean: distinguishes "genuinely in conflict" from "simply absent/null."- Report sections: well-established · contested · coverage gaps ("no claim is made about this area"). Source hedges preserved: "suggests" never becomes "shows".
- Content-appropriate rendering: financial data → tables · news → prose · technical findings → structured lists. Decide by what the content is, not by characters in it. Never flatten to one format.
- Preserve attribution across agent hand-offs by keeping content and metadata (source URL, doc name, page) as separate structured fields, not blended prose.