Use when deciding what an LLM sees on each call: context assembly, history, summaries and compaction, prompt caching, progress or memory across sessions, context-window limits of local or hosted models, and diagnosing lost, repeated or contradictory context.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Agent Context And State?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/lehoanganhtai13-agent-context-and-state)
---
name: agent-context-and-state
description: "Use when deciding what an LLM sees on each call: context assembly, history, summaries and compaction, prompt caching, progress or memory across sessions, context-window limits of local or hosted models, and diagnosing lost, repeated or contradictory context."
---
# Context and state management
Context and state management decides what information is available to each model call, where it comes from, what survives, and what loss means. It is a logical responsibility, not necessarily a service. A single request may need only its input; a long task may need durable history, a validated continuation, and a checkpoint that the execution host can restore. Shared storage or one process does not merge ownership: the harness selects the next step; this component owns information and state semantics; the host owns scheduling and liveness. Trust and privacy cut across these boundaries.
**Scope.** Use this skill to design, build, debug or review the agent system named by the current task. Component rules describe that target system; reading routes and engineering procedures guide your work on it. This separates product requirements from session instructions: actions remain governed by the current task and permissions, including when your own agent or harness is the target.
When deciding how information should steer the next step, use the [behavior-steering instinct map](../agent-harness-model-and-tools/SKILL.md#behavior-steering-instinct-map), then follow its carrier links for provenance, composition and lifetime requirements.
## Context and state instinct map
Choose what may be lost before reducing input; compare continuity, total cost and the delay experienced by the user.
For capability design or problem-solving with a human counterpart, first use supported research or established practice to describe effective human performance, connect it to an option/check, and test transfer against agent differences; carry over only applicable human limits and label unsupported explanations as hypotheses; skip routine use and purely technical mechanisms without a counterpart ([design rule](../agent-system-engineering/references/engineering-process.md#design)).
| Need | Lever and trade-off | Build it as |
|---|---|---|
| The next call is crowded with old material | **Context editing or clearing** avoids a new summary call but loses old detail and may break affected cache reuse; first trim eligible material, protect required state and keep a valid selection stable before reaching for compaction. Capability plugins preserve isolation, removability and parallel development through an explicit contribution contract, declared ordering and a core-owned common module. [Reduction choices](references/context-decisions-and-failures.md#conditional-decisions-and-rejected-shortcuts) | Capability plugin middleware: before-model middleware editing a request copy, or the route's native context-editing option where supported and verified; state field holding stable selected message identifiers. |
| A long task must keep going within a smaller input | **Compaction** reduces repeated input but loses detail and costs generation, validation and affected cache rewarming; inline work puts that delay on the waiting end user. Use after acceptable trimming cannot economically stretch the run, or for required fit, comparing future replay with compaction, rewarming and required-fact preservation. Capability plugins preserve isolation, removability and parallel development through an explicit contribution contract, declared ordering and a core-owned common module. [Compaction](references/context-and-state-management.md#compaction-and-reconciliation) | Capability plugin middleware: before-model size-admission middleware invoking a compaction function, or the route's native compaction where supported, with a checkpoint validator either way. |
| Users repeatedly wait during long conversations | **Off-path preparation** can move compaction latency away from the answer, but adds durable jobs, contention and stale-parent/join controls; use one compactor with a pre-call safety path and measure the next-turn wait too. Capability plugins preserve isolation, removability and parallel development through an explicit contribution contract, declared ordering and a core-owned common module. [Timing choices](references/context-decisions-and-failures.md#conditional-decisions-and-rejected-shortcuts) | Capability plugin middleware: after-run hook recording durable compaction intent; worker plus next-call join/adoption check. |
| Repeated calls keep paying for similar input | **Stable prefix reuse** can discount input but does not free window space; preserve correct stable content, group necessary rewrites and compare all charges before adding explicit cache resources. [Cache economics](references/prompt-cache-layout.md#usage-cost-and-break-even) | Request composer preserving prefix bytes; model adapter applying supported cache controls. |
| Important facts must remain useful later | **Explicit scoped memory saves** avoid replaying everything; extraction and recall add coverage, errors, privacy work and tokens. Start with known durable facts, then justify automation and check cleared, short-session and tail gaps. Capability plugins preserve isolation, removability and parallel development through an explicit contribution contract, declared ordering and a core-owned common module. [Memory admission](references/durable-memory.md#admission-and-provenance) | Capability plugin middleware: scoped memory-save tool and durable record store; run-start recall hook. |
| Work must resume after an interruption | **Checkpoints and authoritative working state** bound lost progress but add commit and restore obligations; omit them when loss is acceptable, otherwise establish versioned receipts before promising recovery. [Restore contract](references/context-and-state-management.md#request-and-failure-paths) | Checkpoint store and guarded commit/restore functions carrying authoritative state and receipts. |
## Route by premise
| Situation | Read | Decision to make |
|---|---|---|
| Every model call, history, context size, continuity, compaction or restart | [Context and state management](references/context-and-state-management.md) | Choose carriers, state and loss policy before the call; use persistent history and compaction only under their premises. |
| Reduction and memory choices or a continuity failure need deeper analysis | [Context and memory decision seams](references/context-decisions-and-failures.md) | Compare conditional mechanisms and previously rejected shortcuts. |
| Cache qualification, missing usage or rejected markers need diagnosis | [Cache diagnostics and alternatives](references/cache-diagnostics-and-alternatives.md) | Trace effective inputs, usage and previously deferred options. |
| A route can reuse a prefix and repeated calls justify investigation | [Prompt cache layout](references/prompt-cache-layout.md) | Compare provider-effective requests and total cost; verify correctness before measuring hits. |
| Facts or artifacts must remain useful across sessions | [Durable memory](references/durable-memory.md) | Define admission, provenance, recall, correction and erasure before retaining facts. |
| Context carrier composition, role ordering or trust provenance | [Context carriers and composition](references/context-carriers-and-composition.md) | Choose carriers and preserve source and authority through assembly. |
| Evidence from files, databases, search or an owned corpus | [Evidence and knowledge access](../agent-evidence-and-knowledge/references/evidence-and-knowledge-access.md) | Identify source, visibility, freshness and unavailable-versus-absent behavior; choose retrieval by need. |
For a long-running task, follow [system flow 2](../agent-system-engineering/references/system-flows.md) across the task boundary, harness, model and action boundaries, context, and host. The [execution host and lifecycle](../agent-runtime-and-interaction/references/execution-host-and-lifecycle.md) owns execution identity, liveness and recovery; context supplies the checkpoint's semantic content and version. Recovery must reconcile uncertain effects before retry, permit verified idempotent replay, and stop for manual reconciliation when the outcome cannot be established.
## Working method
1. Establish the task, caller authority, data visibility, expected duration, relevant model route, and what loss the user can tolerate. A fact that must survive is different from a detail that merely improves fluency. Identify the system of record for each.
2. Draw the current call from trusted instructions through current input, selected history, tool observations and output reserve. Label each carrier by authority, frequency, lifetime and source; tool output, recalled memory and quoted user text are data, not higher-priority instructions.
3. Choose the least stateful design that meets continuity needs. A bounded window can be sufficient when old context may be lost; durable raw history and compaction need explicit ownership, failure behavior and a restore contract. A cache is optional and never a reason to keep unsafe or stale data.
4. For each irreversible or externally visible effect, preserve stable logical-turn and operation identities at the host/action boundary. A summary is not evidence that an action happened; use durable receipts and reconcile ambiguity with the owner of the effect.
5. Define admission and failure before implementation: estimate the provider-effective request, reserve output, decide whether a product hard limit fails closed, and specify whether a missing page, stale version or failed reduction stops the run or permits a visibly degraded result. Never silently substitute missing data for an empty history.
6. Check real assembled requests and restored state, not merely a prompt template or a synthetic object. Trace a request and a failure path; inspect evidence and report route-specific, unmeasured behavior as such. For model-dependent measurements, define the comparison and obtain the applicable call authority first.
A useful analogy is a person's external working notes: a compact task record can free attention but may omit a qualification or preserve an obsolete claim. The analogous agent mechanism is a structured, source-linked continuation checked against authoritative state; unlike a person, the model has no reliable independent access to omitted context and a fluent summary does not prove fidelity. Preserve indispensable constraints mechanically when the task requires them rather than relying on the analogy or on a summary alone.
## Boundaries and acceptance
A context checkpoint identifies the source version and consumed boundary, continuation, required working state, and applicable policy; the host restores it only for the matching execution/session and must honor the ownership fence. An action receipt or current external state remains authoritative for side effects. A cache entry is an optimization of the model request, not an authority source or a substitute for authorization. A durable memory is a scoped, provenance-bearing data record; it must not acquire instruction authority merely because it was recalled.
Before accepting a design, demonstrate the normal call, a missing or changed source, an over-budget request, and the chosen recovery or refusal. If compaction is enabled, demonstrate a tool-call pair, a corrected fact, an indispensable constraint, repeated reductions and restore. If memory is enabled, exercise correction, forgetting and a stale producer. If caching is enabled, compare final provider-effective requests, counters and all cost components on the actual route. Optional checks drop out only when their premise is absent. Source and deterministic inspection support design claims; they do not establish provider behavior, deployed performance, quality or privacy coverage.