Last reviewed: 2026-06-06
Direct answer
A coding agent’s “memory” is not a database — it is the set of files it reads before starting work: instruction files like AGENTS.md or CLAUDE.md, project-level rule files, and any context injected at task launch. When those files go stale, contradict each other, or grow beyond the agent’s effective attention window, the agent drifts silently. Memory hygiene is the practice of keeping those files current, minimal, and verifiably loaded.
The core practice has four steps:
- Audit instruction files. Identify every file the agent reads automatically — AGENTS.md, .claude/CLAUDE.md, .github/copilot-instructions.md, or tool-specific equivalents. Remove contradictions and stale constraints.
- Keep each file focused. An instruction file that covers setup, security, review rules, coding style, and deployment policy in one block is harder for an agent to weight correctly than a short file that covers one concern.
- Rotate context before long task chains. When a task chain spans many turns or sessions, explicitly re-state current constraints at the start of each major phase rather than relying on distant earlier turns.
- Verify the agent read the right rules. Ask the agent to summarize the constraints it is operating under before it begins work. Compare that summary to your current instruction files.
Who this is for
This article is for engineers who:
- Run autonomous coding agents on multi-session tasks (refactors, feature builds, CI repair loops) and notice the agent behaving as if older instructions are still active.
- Maintain shared AGENTS.md or equivalent instruction files for a team and need a process for keeping them current as the project evolves.
- Want a repeatable pre-task checklist that confirms the agent is working from the right memory state before a long run.
If you are just starting with coding agents and want a setup baseline, see AI Coding Agent Setup, Security, and Model Routing first. The present article assumes an agent is already running and focuses on keeping its memory state healthy over time.
Key takeaways
- An agent’s effective memory is bounded by its context window and by which files it actually reads at task launch. Files outside that window are silent.
- AGENTS.md (OpenAI Codex), .claude/CLAUDE.md or CLAUDE.md (Claude Code), and .github/copilot-instructions.md (GitHub Copilot) are the canonical per-repo instruction files for their respective tools. Verify the exact file paths and loading behavior in the linked source documentation before relying on them.
- Instruction file conflicts are a leading cause of inconsistent agent behavior. Maintain a single authoritative file per concern rather than duplicating rules across multiple files.
- Long task chains accumulate context drift. Re-anchoring constraints at the start of each major phase is cheaper than debugging drift after the fact.
- A quick pre-task verification — asking the agent to state the rules it is operating under — catches stale memory before it causes damage.
- Agents running through a shared API gateway benefit from consistent context injection at the routing layer. Verify exact gateway contract fields in the linked CometAPI documentation before relying on that approach in production.
Understanding how coding agents load memory
Instruction files are the primary memory surface
Most coding agents do not maintain persistent memory across sessions by default. Their “knowledge” of your project comes from:
- Repository instruction files read automatically at task start (path and precedence vary by tool — verify in the tool’s own documentation).
- Conversation or task history within the current session or context window.
- Explicitly injected context provided in the task prompt or via tool configuration.
When a session ends, anything that was only in the conversation buffer is lost unless it was written to a persistent file. This means your instruction files are the only durable memory surface you control.
Context window boundaries
Even within a session, an agent working through a long task chain may not have full access to instructions set early in the session. The effective attention window is finite and varies by model. The safe assumption is: if a constraint matters, it should be in a file the agent reads at the start of each task phase, not only in an early turn.
Tool-specific instruction file locations
Each major tool has its own canonical location and loading rules. The exact behavior — whether the file is always read, only read on explicit invocation, or merged with other rule sources — must be verified in the tool’s own documentation. Key starting points:
- Claude Code: The memory documentation at https://code.claude.com/docs/en/memory describes how CLAUDE.md and related files are loaded and prioritized.
- OpenAI Codex (Codex CLI / cloud agents): The AGENTS.md documentation at https://github.com/openai/codex/blob/main/docs/agents_md.md explains the instruction file convention used by Codex-based agents.
- GitHub Copilot: Repository-level custom instructions are documented at the GitHub Copilot docs page linked in the Sources section below. The canonical file is .github/copilot-instructions.md as of the last check date, but verify the current path.
- Cursor: Cursor Agent documentation is listed as a testing-status source; consult https://docs.cursor.com/agent for its current rule-file location.
Do not assume that a file that works for one tool will be read by another. If your team uses multiple agents on the same repository, you may need multiple instruction files.
Memory hygiene workflow
Step 1: Inventory your instruction files
Before a long task run, list every file your agent reads automatically:
Example audit — adapt paths to your tool
ls AGENTS.md CLAUDE.md .claude/CLAUDE.md .github/copilot-instructions.md 2>/dev/null git log –oneline -5 – AGENTS.md CLAUDE.md .github/copilot-instructions.md
Record the last-modified date for each file. If any file was last modified more than two weeks ago and your project has changed significantly, review it for stale constraints.
Step 2: Resolve conflicts
Common conflicts to look for:
- Scope overlap: Two files both define coding style, test requirements, or security rules differently.
- Stale tool references: A file mentions a model ID, endpoint, or CLI flag that no longer exists.
- Phase mismatch: A file still contains setup-phase constraints (e.g., “do not merge to main”) that are no longer appropriate now that the project is in active development.
Keep one file responsible for each category of rule. Cross-reference files only by explicit mention, not by duplication.
Step 3: Trim file length
Agent instruction files have a practical length limit. Beyond a certain size, later sections receive less attention. Guidelines that have proved useful:
- Keep each instruction file under approximately 200–300 lines as a general heuristic (verify your tool’s actual behavior with a short test).
- Move detailed background context to a separate reference file and link to it from the instruction file rather than embedding it inline.
- Use concrete, imperative sentences. “Do not commit .env files” is clearer than a paragraph explaining why environment variables matter.
Step 4: Rotate context at phase boundaries
For multi-session or multi-phase task chains:
- At the start of each major phase, include a brief constraints reminder in the task prompt: “Operating rules for this phase: [key items].” This re-anchors the agent even if early context has scrolled out of the window.
- After a significant project change (new tooling, new security policy, restructured directories), update the instruction file and then start a fresh session rather than continuing an existing one.
Step 5: Pre-task verification
Before a long autonomous run, ask the agent to summarize its current operating constraints:
“Before you begin, list the key rules from the project instruction files you have loaded. Include any constraints on file writes, test requirements, and commit behavior.”
Compare the agent’s summary against your current instruction file. Discrepancies indicate either that the file was not loaded or that the content is ambiguous. Resolve them before the run begins.
Smoke-test workflow
Use this workflow to confirm that your instruction files are being read correctly before committing to a long autonomous run.
Setup assumptions:
- You have at least one instruction file in the repository.
- The agent tool is configured and authenticated.
- You are running in a branch or worktree, not directly on main. See Use Git Worktrees to Keep Parallel Coding Agents Isolated for isolation setup.
Happy-path check:
- Open a new agent session (do not reuse a session that has prior context).
- Ask: “What project-level rules are you operating under? List the source file for each rule.”
- Verify the response mentions your current instruction file by name and lists at least the key constraints you care about.
- Ask the agent to make a trivial scoped change (e.g., add a comment to a test file) and confirm it respects any constraints about commit behavior or file scope.
Error-path check:
- Temporarily rename your instruction file to something the agent will not load automatically (e.g., AGENTS.md.bak).
- Repeat the happy-path check. The agent should either report no project rules or report only defaults.
- Restore the file. Confirm the agent detects it again on the next fresh session.
Minimum assertions:
- The agent names the instruction file correctly.
- The agent’s stated constraints match the current file content.
- A constrained action (e.g., “do not write to src/generated/”) is actually refused or flagged when attempted.
The smoke test must not assert:
- Specific model IDs, context window sizes, or token counts — these vary by configuration and are not guaranteed by the instruction file.
- Availability or pricing of any specific model at the gateway — verify those separately in the gateway documentation.
Sanitized log record template:
date: YYYY-MM-DD agent_tool: [tool name, e.g. claude-code | codex-cli | copilot] instruction_file_path: [path, e.g. AGENTS.md] instruction_file_sha: [first 8 chars of git hash] agent_stated_rules_match: [yes | no | partial] constrained_action_respected: [yes | no | not-tested] notes: [any discrepancy or follow-up action]
Record this log for each major task run so you have a trail of which instruction file version was active.
Using a model gateway for consistent context injection
If your team runs agents through a shared model gateway, you can inject a standard context header at the routing layer so every request arrives with a baseline instruction set — without relying on each developer’s local file state.
This approach requires verifying the gateway’s request field contract before implementing it. For agents routing through CometAPI, the relevant contract areas to check in the documentation are:
- Whether the chat completions endpoint (/api/text/chat) or Responses endpoint (/api/text/responses) supports a system-message or instruction-injection field at the gateway layer.
- Whether any field in the request shape accepts per-call or per-route instruction content.
- How that content interacts with the model’s own context window.
The exact field names and availability of this feature must be verified in the current CometAPI documentation before relying on it. Do not assume that a gateway supports instruction injection based on OpenAI API compatibility alone — field availability varies. See the Contract details to verify section below.
To get started with CometAPI for agent model routing, visit Start with CometAPI.
Failure modes
- Evidence gap: the agent cannot inspect the failing log, source page, pull request, or local command output. The safe action is to stop and record the missing evidence instead of guessing.
- Scope drift: the agent edits files that are not connected to the observed failure. Keep the repair tied to the failing signal and leave unrelated cleanup for a separate task.
- Environment mismatch: the local check uses different versions, credentials, feature flags, or runtime settings than the hosted path. Record the mismatch before treating the result as proof.
- Unreviewed fallback: the agent changes models, endpoints, permissions, or retry behavior to make a run pass without preserving the review boundary. Treat access and provider failures as operational blockers, not topic failures.
- Weak handoff: the final note says the issue is fixed but omits the command, result, changed files, and remaining uncertainty. That makes the next operator repeat the investigation.
Sources checked
Claude Code memory documentation - accessed 2026-06-06; purpose: verify project memory and instruction-file context for agent workflows.
OpenAI Codex AGENTS.md guidance - accessed 2026-06-06; purpose: verify repository instruction-file context for coding agents.
OpenAI Codex cloud documentation - accessed 2026-06-06; purpose: verify hosted coding-agent workflow context.
GitHub Copilot repository instructions documentation - accessed 2026-06-06; purpose: verify repository instruction guidance.
CometAPI documentation root — accessed 2026-06-06; purpose: gateway context for model-routing and instruction-injection framing.
CometAPI chat completions endpoint reference — accessed 2026-06-06; purpose: identify relevant contract areas for context/instruction injection via chat API.
CometAPI models overview — accessed 2026-06-06; purpose: gateway model availability framing; exact model IDs must be verified at source.
Contract details to verify
| Area | What to verify | Source URL | Accessed | Safe candidate wording |
|---|---|---|---|---|
| Claude Code instruction file path | Current canonical path(s) for CLAUDE.md and whether sub-directory files are auto-loaded | https://code.claude.com/docs/en/memory | 2026-06-06 | “Verify the current file path in the Claude Code memory documentation before relying on a specific path.” |
| Codex AGENTS.md loading scope | Whether AGENTS.md in the repo root vs. subdirectories follows a hierarchy, and which takes precedence | https://github.com/openai/codex/blob/main/docs/agents_md.md | 2026-06-06 | “Consult the Codex AGENTS.md documentation for current loading order and precedence rules.” |
| GitHub Copilot instruction file path | Current canonical path for .github/copilot-instructions.md and whether it applies to all Copilot surfaces | https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/add-custom-instructions/add-repository-instructions | 2026-06-06 | “Verify the current file path and scope in the GitHub Copilot custom instructions documentation.” |
| CometAPI system message / instruction injection | Whether the /api/text/chat or /api/text/responses endpoint supports a gateway-layer system-message override field | https://apidoc.cometapi.com/api/text/chat | 2026-06-06 | “Check the current CometAPI chat completions documentation for available request fields before implementing gateway-layer instruction injection.” |
| CometAPI Responses endpoint instruction support | Whether /api/text/responses supports an equivalent instruction or system field for agent routing | https://apidoc.cometapi.com/api/text/responses | 2026-06-06 | “Verify in the CometAPI Responses endpoint documentation whether instruction fields are supported.” |
Reader next step
Compare the workflow against Start with CometAPI .
Use AI Coding Agent Setup, Security, and Model Routing as the next comparison point. Keep Triage CI Failures With a Coding Agent Without Losing the Evidence nearby for setup and permission checks.
FAQ
Q: My agent keeps ignoring rules I added to AGENTS.md. What should I check first?
First confirm the agent is actually reading the file by asking it to state its current rules before starting work. If it cannot name the file, check that the file is in the location the tool expects — the exact path varies by tool and is documented in each tool’s own memory or instruction-file documentation. Second, check that the file is committed to the repository (not only staged or gitignored). Third, if the file is very long, consider whether the relevant rule appears late enough in the file that it receives reduced attention.
Q: We use both Claude Code and GitHub Copilot on the same repo. Do we need two instruction files?
Generally yes. Claude Code and GitHub Copilot look for instructions in different file locations with different loading semantics. Sharing content is reasonable, but the canonical file path for each tool should be set up separately. Check both tools’ documentation for the current paths, then decide whether to maintain separate files or use one as a primary and the other as a stub that references it.
Q: How often should we review and rotate instruction files?
A practical cadence is: after any significant project phase change (new architecture, new tooling, new security policy), after a post-incident review where agent behavior contributed to a problem, and on a routine schedule no longer than monthly for active projects. The smoke-test workflow above can be run in under ten minutes and catches most stale-constraint issues before they cause damage.
Q: Can a model gateway inject instructions so individual developers do not have to manage local files?
Some gateways support injecting a system-level message at the routing layer, which would effectively provide a shared instruction baseline to every agent request. Whether the CometAPI gateway supports this for your target endpoint and use case must be verified in the current endpoint documentation — field availability is not guaranteed by OpenAI API shape compatibility alone. See the contract details table above.
Q: What happens to instructions set at the start of a very long session?
Instruction content set early in a long session may fall outside the active attention window as the conversation grows. The safe practice is to re-state critical constraints at the beginning of each major task phase and to maintain those constraints in a file the agent reads at session start — not only in a prior turn.
Q: Is there a way to test that an agent will respect a new constraint before running a long autonomous task?
Yes — the smoke-test workflow above covers this. The key step is the “constrained action” check: ask the agent to attempt something the new rule prohibits, and confirm it refuses or flags the action before proceeding. Run this in a short session before committing to a long autonomous run.