Home/Reference/Pattern Index

Pattern Index

Complete catalog of 80 named patterns across all ClaudePedia pages, searchable by domain, tags, and keyword.

This index catalogs named patterns across ClaudePedia's 13 content pages. Each entry identifies the pattern, the page that explains it in depth, a one-sentence description, and tags for filtering. Pages are identified by their id field — match that against the filename in v2/core/, v2/advanced/, or v2/quickstart.md.

Quickstart

PatternPageDescriptionTags
Messages List as MemoryquickstartUsing the conversation messages array as the agent's working memory — the model sees the full list on every turn, so appending tool results is how the agent learns.messages, memory, state, beginner
Termination via Absence of Tool CallsquickstartEnding the agent loop when the model produces a response with no tool_calls — the agent doesn't announce completion, it simply stops requesting tools.termination, loop, control-flow, beginner
Schema as InterfacequickstartTreating the tool's metadata (name, description, parameter types) as the contract the model reasons about, while the function body remains invisible plumbing.schema, tools, interface, beginner

Agent Loop

PatternPageDescriptionTags
Two-State Machineagent-loopThe core agent loop alternates between two states: awaiting a model response and dispatching tool calls.state-machine, loop, control-flow
Generator Patternagent-loopUsing an async generator as the loop body so callers can observe each turn without coupling to the loop's internals.async-generator, streaming, composable
State Struct Patternagent-loopCarrying all mutable loop state in a typed struct replaced wholesale at every continue site, with auditable continuation reasons.state, immutability, auditability
Three-Path Abortagent-loopHandling abort signals at three distinct phases: mid-streaming (Path A), post-stream pre-dispatch (Path B), and mid-execution (Path C).abort, cancellation, correctness
Synthetic Tool Result Emissionagent-loopEmitting error tool_result messages for every outstanding tool_use before aborting, to keep conversation history valid for the next API call.abort, tool-result, correctness
Diminishing-Returns Budget Checkagent-loopStopping token budget loops when three consecutive continuations each produce fewer than 500 new tokens, not just at a percentage threshold.token-budget, termination, production
Tombstone Patternagent-loopMarking orphaned partial assistant messages for targeted removal from history and rendering, rather than truncating surrounding context.orphaned-messages, history, fallback
Reactive Compact Guardagent-loopA session-scoped boolean that prevents reactive compaction from triggering more than once per session, surviving stop hook re-entries.compaction, session-state, guard

Tool System

PatternPageDescriptionTags
Typed Function With Metadatatool-systemDefining a tool as a function body plus a schema, concurrency class, and behavioral flags — the metadata is the design, not the function body.schema, metadata, design
Concurrency Classestool-systemClassifying tools as READ_ONLY, WRITE_EXCLUSIVE, or UNSAFE to determine whether parallel dispatch is safe for a given invocation.concurrency, dispatch, safety
Partition-Then-Gathertool-systemSplitting tool calls into consecutive safe/unsafe batches, running batches sequentially while parallelizing within each safe batch.dispatch, concurrency, batching
Two-Phase Validationtool-systemRunning schema validation (shape/types) followed by semantic validation (business logic) as two distinct, always-both-running phases.validation, schema, correctness
Fail-Closed Defaultstool-systemDefaulting every unset safety flag to the most restrictive value, so missing declarations default to safe rather than permissive.safety, defaults, correctness
Dynamic Tool Setstool-systemUsing a refresh_tools callback to update the available tool list between turns while keeping it immutable within a single turn.dynamic, refresh, lifecycle
Sibling Aborttool-systemUsing a child abort controller to cancel all concurrently running tools in a batch when one fails, without affecting the parent session.abort, concurrency, batch
Result Size Offloadtool-systemPersisting oversized tool results to a temp file and sending the model a preview, preventing large outputs from consuming the context window.context, offload, size-limit

Memory and Context

PatternPageDescriptionTags
Hierarchy of Forgettingmemory-and-contextA four-level memory model (in-context → summary → long-term → forgotten) where each level trades fidelity for space.memory, hierarchy, levels
Compaction Pipelinememory-and-contextRunning context interventions in cost order: trim tool results → drop old messages → session memory compact → LLM summarize.compaction, cost-order, pipeline
Autocompact Circuit Breakermemory-and-contextDisabling compaction after N consecutive failures to prevent infinite API hammering on irrecoverably large contexts.circuit-breaker, compaction, resilience
Forked-Agent Extractionmemory-and-contextRunning a background sub-agent after each turn to extract facts, sharing the parent's prompt cache but with restricted tools and a hard turn budget.extraction, sub-agent, background
Closed Taxonomymemory-and-contextLimiting long-term memory to a fixed set of four types (user, feedback, project, reference) to prevent memory from becoming a junk drawer.taxonomy, classification, memory
Extraction Cursormemory-and-contextTracking which messages have been processed by the extractor via a UUID cursor that advances only on successful runs.cursor, at-least-once, extraction

Prompt Architecture

PatternPageDescriptionTags
Two-Zone Modelprompt-architectureSplitting the system prompt into a static zone (identical for all users/sessions/turns) and a dynamic zone (per-session or per-turn content).static-dynamic, caching, zones
Section Registryprompt-architectureRegistering each prompt section with explicit cache intent (cached vs volatile) rather than concatenating strings directly.registry, caching, sections
Cache-Intent Two-Function APIprompt-architectureUsing register_cached_section and register_volatile_section with a mandatory reason argument to make cache intent explicit and auditable.caching, api-design, intent
Five-Level Priority Chainprompt-architectureResolving the effective system prompt through five ordered levels: override → coordinator → agent → custom → default.priority, prompt-assembly, modes
Append-Tail Patternprompt-architectureInjecting content at the end of the assembled prompt outside the priority chain, without modifying any chain level or fragmenting cache keys.injection, tail, flexibility
Numeric Calibrationprompt-architectureUsing explicit numeric constraints in the system prompt (max sentences, confidence thresholds) rather than vague adjectives that the model interpolates.calibration, numeric, precision

Error Recovery

PatternPageDescriptionTags
Escalation Laddererror-recoveryA four-rung failure response ordered by cost: retry (latency) → fallback (quality) → degrade (capability) → fail (task).escalation, tiered, recovery
Circuit Breakererror-recoveryTracking failure rates and blocking calls to a failing service, preventing retry storms against dependencies that are known to be down.circuit-breaker, failure-rate, protection
Retryability Classificationerror-recoveryInspecting each error's status and headers before entering the retry loop to avoid retrying unfixable errors or amplifying capacity events.classification, retry, http-status
Tool Error Pipelineerror-recoveryConverting every tool execution failure into a tool_result message with is_error: true rather than an exception, keeping the conversation valid.tool-error, pipeline, messages
Query-Source Partitioningerror-recoveryRouting foreground operations through full retry logic while failing background operations fast during capacity events, preventing amplification.partitioning, foreground-background, retry
Adaptive Max-Tokenserror-recoveryParsing exact token counts from a context overflow error and adjusting max_tokens for the retry rather than guessing or giving up.context-overflow, tokens, adaptive
Persistent Retry Modeerror-recoveryReplacing fixed retry counts with a time-capped (6-hour) unlimited retry loop with heartbeat sleep-chunking for unattended automation sessions.persistent, automation, unattended

Safety and Permissions

PatternPageDescriptionTags
Six-Source Permission Cascadesafety-and-permissionsEvaluating tool permissions through six ordered policy sources (policy → project → local → user → CLI → session) with first-match wins and fail-closed default.cascade, policy, permissions
Bypass-Immune Checkssafety-and-permissionsRunning scope bounds and critical checks before the cascade so they cannot be overridden by any policy source, mode, or rule.bypass-immune, scope, safety
Five Permission Modessafety-and-permissionsProviding a global semantic override on the cascade: default, plan (auto-deny writes), acceptEdits, bypassPermissions, and dontAsk (silent deny).modes, global-override, permissions
Graduated Trustsafety-and-permissionsAssigning authority levels to instruction sources: system prompt > user turn > tool result > sub-agent output.trust, hierarchy, authority
Denial Trackingsafety-and-permissionsCounting consecutive and total classifier denials and escalating to user dialog at thresholds, preventing silent infinite rejection loops.denial-tracking, escalation, thresholds
Shadow Rule Detectionsafety-and-permissionsDetecting at write time that a new allow rule can never fire because a broader deny or ask rule will always be checked first.shadow-rules, detection, correctness
Racing Four Resolution Pathssafety-and-permissionsIn interactive sessions, running hooks, classifier, bridge response, and channel relay concurrently so fast paths pre-empt slow ones before the dialog renders.racing, concurrency, resolution

Multi-Agent Coordination

PatternPageDescriptionTags
Delegation Patternmulti-agent-coordinationThe coordinator decides WHAT, workers decide HOW — synthesis happens at the coordinator, never relay of raw worker output to the user.delegation, synthesis, roles
Synthesis Over Relaymulti-agent-coordinationMaking a dedicated LLM call to combine, resolve conflicts between, and integrate worker results into a single coherent answer.synthesis, coordinator, llm-call
Tool Partitioningmulti-agent-coordinationGiving the coordinator only coordination tools (spawn, send, stop) and workers only domain tools, preventing coordinator bypass.partitioning, tools, roles
Context Isolationmulti-agent-coordinationStarting every worker with a fresh message history so errors, confusion, and untrusted inputs are quarantined per worker.isolation, context, security
File-Based Mailboxmulti-agent-coordinationUsing a directory of atomic message files as the universal inter-agent communication channel across all executor backends.mailbox, files, communication
Session Reconnectionmulti-agent-coordinationPersisting team identity (agent name, team name, leader ID) in the session transcript so crashed workers rejoin without manual intervention.reconnection, persistence, resilience
Three Executor Backendsmulti-agent-coordinationSupporting in-process, multiplexer-based, and native terminal executors behind a single interface so the coordinator is backend-agnostic.backends, executor, abstraction

Streaming and Events

PatternPageDescriptionTags
Discriminated Union Event Modelstreaming-and-eventsDefining the event contract between producer and consumer as a typed discriminated union (TextDelta, ToolDispatch, Complete, etc.).discriminated-union, typed-events, contract
Producer-Consumer Pipelinestreaming-and-eventsThe agent loop as producer yielding typed events; consumers subscribing and handling event types they care about at their own pace.producer-consumer, decoupling, pipeline
Bounded Bufferstreaming-and-eventsAllowing the producer to run ahead by up to N events before blocking, balancing throughput with memory use and consumer crash-safety.buffer, backpressure, bounded
Event Priority Schedulingstreaming-and-eventsDispatching discrete events (keystrokes) synchronously and batching continuous events (resize, scroll) to prevent input lag under load.priority, scheduling, latency
Capture-Bubble Dispatchstreaming-and-eventsTwo-phase event routing in component trees: capture walks root-to-target (intercept), bubble walks target-to-root (react after).capture-bubble, event-delegation, phases
Screen Diffingstreaming-and-eventsRendering to a screen buffer, diffing against the previous frame, and emitting only changed cells — not streaming text directly to the terminal.screen-diff, rendering, terminal

Command and Plugin Systems

PatternPageDescriptionTags
Metadata-First Registrationcommand-and-plugin-systemsDeclaring every command as a metadata object before any code is loaded; implementation deferred to invocation via dynamic imports.metadata-first, lazy, registration
Three Command Typescommand-and-plugin-systemsClassifying commands as local (function call), interactive (UI component), or prompt (conversation injection) via a discriminated union.discriminated-union, command-types, dispatch
Lazy Loadingcommand-and-plugin-systemsLoading a command's module only when invoked, keeping startup cost constant regardless of registry size.lazy-loading, startup, performance
Multi-Source Registry Mergecommand-and-plugin-systemsConcatenating commands from built-in skills, plugin skills, plugin commands, workflow commands, and builtins — array order IS the priority.multi-source, merge, priority
Availability vs Enabled Separationcommand-and-plugin-systemsKeeping static availability (who can ever use this) separate from dynamic enabled state (is it on now) to support post-login auth refreshes.availability, enabled, separation

Hooks and Extensions

PatternPageDescriptionTags
Four Execution Modeshooks-and-extensionsChoosing hook execution as command, prompt, agent, or HTTP based on explicit cost-capability trade-offs.execution-modes, cost, trade-offs
27-Plus Lifecycle Eventshooks-and-extensionsOrganizing extension points across six phases — session, per-turn, tool, memory, multi-agent, file system — covering the full operational surface.lifecycle-events, phases, taxonomy
Condition Syntaxhooks-and-extensionsUsing permission-rule pattern matching to gate hook execution at evaluation time, so non-matching hooks cost nothing to register.conditions, pattern-matching, cost
Error Isolation and Aggregationhooks-and-extensionsCapturing hook failures as four outcomes (success, blocking, non-blocking error, cancelled) so crashes never propagate to the main loop.isolation, aggregation, resilience
Fire-and-Forget Async Hookshooks-and-extensionsUsing async: true for audit and observability hooks so they add zero latency to the critical execution path.async, fire-and-forget, observability

MCP Integration

PatternPageDescriptionTags
Tool Bridge Patternmcp-integrationConstructing standard Tool objects from MCP server capabilities at connection time so the dispatcher treats external tools identically to built-in tools.tool-bridge, abstraction, integration
MCP Namespacingmcp-integrationNaming bridged tools as mcp__{server}__{tool} to prevent cross-server collisions and make tool ownership traceable in logs.namespacing, naming, traceability
Five Connection Statesmcp-integrationModeling server connections as connected, failed, needs-auth, pending, or disabled — all non-connected states return empty tool lists silently.connection-states, state-machine, resilience
Batched Startupmcp-integrationUsing different concurrency limits for local servers (batch=3, process spawning) vs remote servers (batch=20, TCP connections) at startup.batching, startup, concurrency
Tool Description Truncationmcp-integrationCapping tool descriptions at 2048 characters to prevent OpenAPI-generated servers from exhausting the agent's context budget on every turn.truncation, context-budget, protection

Observability and Debugging

PatternPageDescriptionTags
Three-Layer Observabilityobservability-and-debuggingRunning structured event logging, cost tracking, and session tracing as three independent layers, each answering a different debugging question.three-layers, independent, observability
Sink Queue Patternobservability-and-debuggingBuffering events in an in-memory FIFO before the logging sink is ready, draining via microtask on attachment to prevent startup log loss.sink-queue, startup-ordering, buffering
Metadata Type Restrictionobservability-and-debuggingAccepting only boolean, number, and undefined in event metadata so accidental PII logging is a compile-time error rather than a runtime incident.pii, type-restriction, safety
Four Token Typesobservability-and-debuggingTracking input, output, cache-read, and cache-creation tokens separately so prompt caching effectiveness is visible and measurable.cost-tracking, tokens, cache
Context-Local Span Propagationobservability-and-debuggingUsing async-local storage to carry the active span so deep call stacks can create child spans without threading a context parameter explicitly.spans, async-local, propagation
Orphan Span Cleanupobservability-and-debuggingUsing weak references and a background TTL sweep to end spans that were never closed due to aborted streams or unhandled exceptions.orphan-spans, weak-references, cleanup
Privacy-Default Redactionobservability-and-debuggingRedacting all prompt content from traces and event logs by default, requiring explicit per-session opt-in for development debugging.privacy, redaction, default-off