Pattern Matrix/White Paper/P1

ADPS Agent Design Pattern White Paper

P1 · Context Triage

When the total volume of candidate information exceeds the context window budget, decide what gets in first, what waits outside the door, and what is not preloaded at all.

Coordinate Perception × Route
Cost Medium (one lightweight priority judgment, no extra reasoning chain)
Pattern group Perception patterns
Summary When the total volume of candidate information exceeds the context window budget, decide what gets in first, what waits outside the door, and what is not preloaded at all.

Problem

Production agents routinely draw on source code, conversation history, tool output, and enterprise knowledge. The combined material can exceed the model's effective window. Truncating by filename or chronology may preserve stale material while dropping decisive evidence, leaving the agent to reason from an incomplete record.

Context triage turns this into an engineering process: it divides all candidate information into four levels, P0/P1/P2/P3, and loads from high to low until the token budget runs out. It governs window allocation for a single request, with the goal of guaranteeing that the most critical information is not drowned out.

Classification: Perception × Route

  • Vertical axis · Perception: Triage decides what the Agent looks at and what it ignores; it is attention management on the perception side. It handles the stage before information enters reasoning, not the adjustment of output format and not cross-session memory.
  • Horizontal axis · Route: Information of different priorities takes different processing paths—high priority enters context, medium priority is compressed into a summary, low priority is only attached as a handle to be pulled on demand. This is a single routing decision based on the characteristics of the information, not a chained sequence and not a looped iteration.

Solution and mechanics

A single triage layers the candidate information by priority, then uses the token budget to allocate a quota to each layer:

Level Typical content Loading strategy
P0 always loaded system prompt, safety rules, current task, business identity (tenant_id) reserve capacity first; ordinary material cannot displace it
P1 loaded if space allows current file, recent tool results, error stack load according to importance for the current task
P2 loaded after compression conversation history, background documents summarize first, then use the remaining budget
P3 handle only resources accessible but not preloaded keep outside the prompt and retrieve through tools on demand

Priority can come from human rules or an algorithm. Claude Code's CLAUDE.md hierarchy is an example of human triage: a team can place safety rules at P0 and preferences at P2. Aider's RepoMap is algorithmic triage: it extracts symbols with tree-sitter and scores them through a code graph. Error stacks need cross-tier protection because repair and regression checks depend on that feedback. Each triage decision should also produce a trace so operators can distinguish information that was never discovered from information that was found but deferred or dropped.

Applicability

  • Multi-tenant SaaS customer-service Agent: One agent serves multiple tenants whose knowledge bases cannot fit in one window. tenant_id must be a hard P0 constraint, with the remaining knowledge triaged across the four levels.
  • Code Agent facing an unfamiliar codebase: The user supplies a different repository each time, and you cannot require everyone to write a CLAUDE.md, so you must take the route of automatic algorithmic symbol extraction.
  • Engineering Agent serving the same team long term: The team can use CLAUDE.md to state safety rules, project constraints, and loading priorities, then let an algorithm handle dynamic triage.
  • Long-running Agent connected to a file system or knowledge base: Explicit triage is needed whenever candidate material may exceed the effective window.

Known failure modes

  • Priority misjudgment: If a critical file is marked P3, the agent must retrieve it midway through reasoning, adding tool calls and increasing the risk of cascading errors. When uncertain, raise its priority temporarily and use re-read traces to tune the rule.
  • Over-aggressive triage: Capping the budget too tightly to save tokens suspends the whole critical dependency chain, and the Agent repeatedly says "I need to read this file again." The re-read ratio climbs, and the tokens saved are spent again on re-reading.
  • Vague P3 handle naming: A name like doc://manual-page leaves the agent unsure whether to fetch it. Handles should carry a clear “what is this” signal, for example scope + topic + time.
  • Cross-tenant data leakage: A P3 handle fetching the wrong tenant's data into the context is a data-breach incident. A resource with a tenant prefix must be force-validated against the P0 tenant_id at load time.
  • Trace sampled away: Low-rate random sampling can miss a boundary problem concentrated in a small set of tenants. Triage decisions involving tenant isolation or safety should be retained as structured records.

Verification and metrics

  • re-read ratio: The share of deferred material that the agent later requests during reasoning. A sustained increase against the local baseline suggests over-aggressive triage or unclear handle descriptions.
  • Long-tail distribution of dropped_count: Means hide requests in which most candidate material is discarded. Inspect the tail alongside task type and failure traces.
  • p3_hit_rate: The share of P3 handles later retrieved. Persistently low use suggests an overly broad handle pool; persistently high use suggests frequent material was misclassified. Calibrate thresholds on local workloads.

Reference implementation

Sort candidate information by priority (P0 > P1 > P2 > P3, with additional protection for error stacks):
                逐条塞入:
                    P3            → add to the handle pool; do not preload
                    其余 + 未超预算 → 进 context,累加 token
                    其余 + 超预算   → 丢弃(但错误堆栈强制保留)
            返回 (进 context 的, 挂句柄的, 一条 TriageDecision)
            TriageDecision 留下:时间戳 / 预算 / selected / deferred / dropped / tokens_used
            

Production implementations should use the real model tokenizer, extend error detection for the business domain, and emit TriageDecision records to an observability system. Review dropped_count and retrieval traces at a cadence set by task risk and operating policy.

Illustrative scenario

Consider a loan-review agent receiving current financial statements, a collateral valuation, historical registration material, and correspondence. If the system truncates by filename, it may drop the current valuation while keeping stale registration documents. Four-level triage protects current financials, collateral evidence, and anomaly or missing-data markers; older material is downgraded by recency, with traceable handles for anything not loaded. The first question is whether the input set is complete enough for a decision, before evaluating the model's reasoning.

Related patterns

  • Semantic Compression (P2): Complementary and often paired. Triage governs "which information enters context" (future tokens), and compression governs "how what has already entered is compressed without losing the key parts" (past tokens). The P2-level "loaded after compression" is exactly where the two connect.
  • Progressive Discovery (P3): Naturally coupled. The P3 handle from triage is precisely the object that progressive discovery pulls on demand—one is selected passively, the other is sought actively.
  • Layered Memory (Memory module): Shares the same handle-naming convention, but with different TTLs. Handles for code and documents always point to the current version and belong to triage; handles for user preferences and conversation state evolve through versions and belong to memory. It is recommended to mark P3 handles in two classes, immutable:// and versioned://.

Design conclusion

Context triage is not prompt tuning; it is an echo of operating-system process scheduling in the LLM era—the context window is scarce CPU time, and the triage algorithm is the scheduler that keeps the most important process from being starved.

Suggested citation: ADPS, P1 Context Triage, Agent Design Pattern White Paper v0.3, 2026-07-13. Catalog · runnable code catalog · CC BY 4.0

Document status: This is a public review draft. Illustrative scenarios explain the mechanism and are not presented as verified enterprise cases. See the case library for attributed practice. ADPS welcomes case contributions with sources, measurement methods, and publication approval.