Skip to main content

Documentation Index

Fetch the complete documentation index at: https://www.aidonow.com/llms.txt

Use this file to discover all available pages before exploring further.

Executive Summary

Autonomous agent systems operating with Claude Code have access to a built-in memory mechanism — a set of structured files that persist independently of the session context window. This mechanism is powerful but bounded: memory files survive context compaction but not session termination, and no memory stored exclusively in /tmp survives beyond the process boundary. This analysis examines the full persistence stack available to Claude Code agents, documents the structural /tmp durability gap that leads to silent log loss at session end, and presents a three-layer architecture (in-session log, session-end notification, nightly wiki write) that closes the gap completely. It further defines the verification discipline required when memory files name specific code artifacts — functions, files, or configuration paths — and establishes the escalation logic that determines whether a given piece of state belongs in a memory file, in CLAUDE.md, or in a permanent external knowledge base.

Key Findings

  • Claude Code’s built-in memory system survives context compaction but not session termination. Files written to the designated memory path persist across context resets within a session; they do not survive after the agent process exits.
  • The /tmp durability gap is a structural constraint of the tool runtime, not a defect. Session-scoped scratch space is by design; the failure mode arises from conflating temporary writes with durable persistence.
  • Memory files that name specific functions, files, or configurations are claims about a past state of the codebase — they must be verified against the current repository before acting on them; a memory written two weeks ago about a function that has since been renamed is an active source of incorrect behavior.
  • A three-layer architecture — in-session log, session-end notification, nightly wiki write — fully closes the /tmp durability gap without requiring changes to the tool runtime or per-session manual intervention.
  • Multi-agent memory consistency requires a single authoritative source per category of state. When multiple agents read from overlapping memory files, contradictions compound silently unless a clear ownership hierarchy is established.
  • The escalation from ephemeral memory to permanent artifact is a decision, not a default. Most operational state should not be escalated; the criteria for escalation are specificity, durability requirement, and cross-session or cross-agent reuse value.

1. The Claude Code Memory Architecture: Four Tiers, One Index

Claude Code exposes a structured memory system consisting of typed files organized under a user-specific memory directory. The system’s design separates concerns by type: user preferences live in one file, project decisions in another, external references in a third, and accumulated feedback in a fourth. A central index file — MEMORY.md — lists what exists and provides a one-line summary of each entry, allowing the agent to retrieve relevant context without loading every memory file on every session start. The four standard memory file types are:
  • User preference files — behavioral preferences, communication style, tool choices, formatting conventions that apply across all projects for a given user
  • Project memory files — decisions, constraints, and context specific to a given repository or workflow
  • Feedback files — corrections and quality feedback accumulated across sessions, particularly useful for calibrating agent output to reviewer expectations
  • Reference files — external URLs, documentation links, API specifications, and other stable references the agent would otherwise need to re-fetch
The MEMORY.md index is the entry point. An agent starting a session reads the index, identifies which typed files are relevant to the current task, and loads only those. This selective loading is important: the index itself is cheap to read; the typed files may be large.
The 5-minute cache TTL on memory files means that edits made to a memory file during a session may not be visible to the agent until the cache expires. In high-frequency autonomous workflows where memory files are updated programmatically, this TTL is a design constraint to account for when reasoning about when a write becomes readable.
The critical boundary in this architecture is session termination. Context compaction — the mechanism by which Claude Code summarizes and truncates the active context window when it grows too large — does not affect memory files. Files written to the memory path are on disk; they survive compaction. Session termination, however, ends the process. Any state that was not written to a durable path before the process exited is gone.

2. The /tmp Durability Problem: Structural Loss at Session Boundaries

The /tmp filesystem in most Unix environments is ephemeral by design. Its contents survive process restarts in the same session but are not guaranteed to survive reboots, and in containerized or sandboxed execution environments, /tmp is frequently scoped to the process lifetime itself. Claude Code agents operating autonomously over long tasks commonly write intermediate state to /tmp: session logs, task progress notes, error summaries, and scratch computations. This is reasonable within a session — /tmp writes are fast and require no path management. The failure mode arises when this pattern is extended to anything that must survive the session boundary. The practical consequence is silent log loss. An agent that maintains a detailed session log in /tmp/session-log.md and assumes the log will be available for review at session end will, in most deployment configurations, produce a log that exists nowhere after the process exits. The human expecting to review the log, or the next agent expecting to read the prior session’s output, finds nothing.
Do not treat /tmp writes as a substitute for memory file writes when the information has cross-session value. The write will succeed — there is no error — but the data will not survive the session boundary. The failure is silent: no exception, no warning, no indication that the write was semantically ephemeral. The only signal is the absence of the file at next session start.
This is not a defect in Claude Code or in the operating environment. It is a correct application of the principle that temporary storage is temporary. The failure mode is architectural: organizations deploying autonomous agents without a session-end persistence protocol accumulate an invisible debt of lost operational history.

3. The Three-Layer Architecture: Closing the /tmp Gap

A three-layer architecture fully closes the /tmp durability gap. Each layer has a distinct role; together they ensure that nothing of operational value is lost at session boundaries. Layer 1: In-session log. The agent maintains a structured log file during the session. The log records decisions made, tasks completed, errors encountered, and notable state changes. The critical requirement is that this log is written to a durable path — either the memory directory or a project-specific notes path under version control — not to /tmp. The log may be verbose; verbosity at this layer is a feature. Layer 2: Session-end notification. At session end, the agent fires a structured notification containing a summary of the session log. This notification goes to the human operator or to a monitoring system. The notification does not need to contain the full log — a paragraph summary with a pointer to the full log location is sufficient. The purpose of this layer is to close the gap between the agent’s knowledge of what happened and the human’s awareness of it. Without this layer, the human learns what the agent did only by reading through memory files, which may not be timely or reliable. Layer 3: Nightly wiki write. A scheduled workflow, separate from any individual agent session, reads the accumulated session logs and memory file updates from the past 24 hours and writes a structured summary to an external knowledge base — a wiki, a project tracker page, or a documentation system. This layer converts ephemeral operational history into permanent institutional knowledge. It is the only layer that writes to a system outside the agent’s filesystem scope, making it the definitive persistence guarantee.
# Example: nightly knowledge-capture workflow trigger (generic scheduler format)
schedule: "0 2 * * *"   # 2:00 AM daily
job:
  name: knowledge-capture
  steps:
    - name: collect-session-logs
      command: "find ~/.claude/projects/ -name '*.md' -newer /var/run/last-capture -type f"
    - name: summarize-and-write
      command: "agent --task summarize-logs --output wiki://knowledge-base/daily-log"
    - name: update-capture-marker
      command: "touch /var/run/last-capture"
The nightly wiki write is most valuable when it is idempotent — writing the same summary twice should produce no duplicates and no errors. Structure the write as an upsert keyed on the date, not as an append operation. This allows the workflow to re-run safely after failure without generating duplicate records.
The three layers address different failure modes: Layer 1 prevents in-session state loss; Layer 2 prevents the human awareness gap; Layer 3 converts session history into permanent institutional knowledge. An organization with only Layer 1 retains state within the agent’s filesystem but loses awareness. An organization with Layers 1 and 2 maintains human awareness but loses long-term institutional memory when memory files are eventually pruned. All three layers are required for full closure.

4. Persistence Tiers: Comparison Across Durability, Scope, and Verification Requirements

The following table characterizes the four persistence tiers available to Claude Code agents. Selecting the correct tier for a given piece of state is the central decision in memory architecture.
TierDurabilityScopeVerification RequiredWhen to Use
In-session contextSession lifetime onlySingle agent, single sessionNo — data is currentIntermediate computation, scratch state, current task progress
Memory files (typed)Survives compaction; lost at session end without explicit writeSingle user or projectYes — names of code artifacts must be verified against current repoUser preferences, accumulated feedback, project decisions, external references
CLAUDE.mdPermanent — version-controlled in gitAll agents in the repositoryNo — always-read at session startBehavioral constraints, workflow rules, identity systems, incident-derived rules
External wiki / trackerPermanent — outside agent filesystemCross-project, cross-team, cross-timeNo — treated as authoritative external recordHistorical session summaries, architectural decisions, incident postmortems, knowledge that must survive repository changes
The scope column is the primary selection criterion. State that is relevant only to the current session belongs in in-session context. State that the same user needs across sessions but that is not broadly relevant belongs in typed memory files. State that constrains behavior for all agents operating in a repository belongs in CLAUDE.md. State that must outlast the repository or be accessible to humans outside the agent workflow belongs in an external knowledge base.

5. Memory Staleness: Every Named Artifact Is a Claim About Past State

A memory file entry that reads “the authentication logic lives in src/auth/session_manager.rs” is not a fact about the current codebase. It is a claim about the codebase as it existed when the memory was written. Files are renamed. Functions are extracted or inlined. Modules are restructured. The memory entry does not update automatically when the code changes. This distinction — between memory as record and memory as current truth — is the single most important operational discipline in memory hygiene. An agent that acts on a stale memory without verification will navigate to a path that no longer exists, call a function that has been renamed, or apply a constraint that was superseded by a subsequent architectural decision. The failure mode is not an error; it is confident incorrect behavior. The verification pattern is consistent regardless of what the memory claims:
  1. Retrieve the memory entry.
  2. Identify all named artifacts: file paths, function names, module names, configuration keys.
  3. For each artifact, verify existence and current state using the repository directly: git log --follow -- <path> for paths, git grep <function_name> for functions, direct filesystem inspection for configuration.
  4. If verification fails — the artifact has moved, been renamed, or been deleted — update the memory entry before proceeding. Do not act on a stale memory.
# Pattern: verify a memory-referenced file path before using it
# Memory claims: "authentication handler at src/auth/session_manager.rs"

git log --oneline --follow -- src/auth/session_manager.rs
# If no output: file no longer exists at this path
# Locate current position: git log --oneline --diff-filter=R --find-renames -- src/auth/session_manager.rs

git grep -l "session_manager\|SessionManager" -- src/
# Locate the function in its current location
The principle extends beyond file paths. A memory entry claiming “the team uses X library for HTTP client operations” may have been superseded by a dependency migration. A memory entry claiming “the deployment environment is Kubernetes 1.28” may be outdated. Any memory that names a specific version, location, or configuration is subject to staleness.
Git log and git blame are more authoritative than memory files for answering questions about recent repository state. Memory files are appropriate for preferences, decisions, and context that git history does not capture — not for facts about code structure that git does capture. When in doubt, query the repository rather than relying on memory.

6. Multi-Agent Memory Consistency: Avoiding Contradictions at Scale

In workflows where multiple agents operate across the same repository — a coordinator agent, a builder agent, a review agent, a monitoring agent — each agent reads from the same memory files. This shared read is a feature: all agents benefit from accumulated context. It also creates a consistency risk: if two agents write to the same memory file with different assumptions about current state, the result is a contradiction that neither agent can detect. Three patterns address this risk: Ownership assignment. Each memory file category has a designated writer. The coordinator agent owns project memory files. The builder agent does not write to project memory — it reads from them and writes to a separate execution log that the coordinator later synthesizes. This prevents concurrent writes and eliminates the class of contradiction that arises from two agents updating the same record simultaneously. Append-and-date over overwrite. When a memory entry must be updated, do not overwrite the existing entry. Append the new entry with an ISO 8601 datestamp and mark the previous entry as superseded. This preserves the history of how a decision evolved and allows any agent reading the file to reason about temporal ordering.
<!-- Example: dated append pattern in a project memory file -->

## Authentication Pattern

**2026-03-10:** Team uses JWT with RSA-256 signing. Keys stored in secrets manager.
**2026-04-22 (supersedes above):** Migrated to opaque session tokens. JWT deprecated
in all new code. Existing JWT-authenticated endpoints maintained for backward
compatibility through 2026-Q3.
Divergence detection on read. Before a coordinator agent writes a synthesis of subagent outputs back to a memory file, it reads the current state of the file and verifies that no conflicting entry was written since it last read. If a conflict is detected, it resolves the conflict explicitly before writing, logging the resolution decision. Silent overwrite of a concurrent write is not acceptable.

7. Escalation Logic: What Belongs Where

Not everything an agent learns in a session warrants persistence. Persisting too aggressively degrades memory quality: files grow large, signal is buried in noise, and the cognitive load of maintaining memory accuracy increases. The escalation logic below applies to every candidate piece of state before it is written to any persistent tier. Do not persist:
  • Code conventions that are already enforced by the repository’s linter, formatter, or CLAUDE.md — these are already persistent and will be read automatically
  • Git history — the repository already stores this with authorship, timestamps, and diffs; memory duplicates are lower quality
  • Debugging session conclusions where the conclusion is “the bug was fixed” — the fix is in the code; the memory adds nothing
  • Ephemeral task state that is only relevant to the current in-progress task and has no future reuse value
Persist to memory files:
  • User preferences and communication style that are not derivable from any file in the repository
  • Feedback and corrections that calibrate agent output to reviewer expectations
  • Decisions made in external contexts (calls, reviews, planning sessions) that are not recorded elsewhere
  • External references — documentation URLs, API specifications, useful tools — that the agent would otherwise need to re-discover
Escalate to CLAUDE.md:
  • Behavioral constraints derived from incidents — rules that, if forgotten, would allow the same failure to recur
  • Workflow rules that apply to all agents in the repository
  • Capability routing decisions — which tool handles which category of need
Escalate to external wiki or tracker:
  • Architectural decisions with lasting implications — the record of why a significant choice was made
  • Incident postmortems — what failed, the root cause, what changed
  • Session history that must outlast the current repository configuration or be accessible to humans outside the agent workflow
State CategoryMemory FileCLAUDE.mdExternal Wiki
User preferencesYesNoNo
Accumulated reviewer feedbackYesNoNo
Code conventionsNo — use linter/formatterIf incident-derivedNo
Incident-derived behavioral ruleNoYesPostmortem only
Architectural decision recordNoNoYes
Daily session summaryNoNoYes — via nightly capture
External API referenceYesNoNo

8. Recommendations

  1. Write session logs to a durable path, not to /tmp. Designate a project-specific notes directory under version control or the memory directory as the target for all in-session logging. Run a validation check at the start of any autonomous workflow that confirms the log target path is durable — a simple stat on the target directory is sufficient.
  2. Implement a session-end notification as an explicit workflow step, not an afterthought. The notification should fire as the last action before session close. Configure it to include: the session duration, the tasks completed, any errors encountered, and the path to the full session log. Use the platform’s native notification mechanism (email, Slack, webhook) so the human operator receives the summary without polling.
  3. Deploy the nightly wiki write as an independent scheduled job, separate from any agent session. Run it at a fixed time, write idempotently (upsert by date), and alert on failure. Do not rely on the agent itself to trigger the wiki write at session end — session end is unreliable as a trigger in autonomous workflows where the session may be interrupted.
  4. Treat every named artifact in a memory file as a stale claim until verified. Before navigating to a file path, calling a function, or applying a configuration value drawn from memory, verify that the artifact exists in its claimed location using git log or direct filesystem inspection. Update the memory entry immediately if verification fails.
  5. Assign ownership of each memory file category to a single agent role. Document the ownership assignment in CLAUDE.md. A builder agent should not write to the project memory file that the coordinator agent owns. Cross-role writes produce contradictions that neither agent can detect.
  6. Use the append-and-date pattern for all memory updates. Never overwrite an existing memory entry. Append new entries with an ISO 8601 datestamp and mark the superseded entry explicitly. This preserves history, enables temporal reasoning, and makes contradictions visible rather than silent.
  7. Prune memory files on a defined schedule. At minimum, review memory files every 10 sessions and remove entries that are clearly stale, superseded, or duplicated in a more authoritative location. Memory files that grow without pruning become a source of noise rather than signal.

Conclusion

The memory architecture available to Claude Code agents is sufficient for sophisticated autonomous operation, but it demands deliberate design. The built-in memory system — MEMORY.md as index, typed files as storage — provides cross-session persistence for preferences, feedback, and decisions. It does not provide durability guarantees beyond the agent’s filesystem scope, and it does not update itself when the codebase it describes changes. The three-layer architecture presented here addresses the structural /tmp durability gap without requiring changes to the tool runtime. The verification discipline for named code artifacts prevents a class of confident incorrect behavior that is otherwise difficult to detect. The escalation logic prevents memory file inflation and keeps persistent state aligned with its actual reuse value. As autonomous agent deployments grow in scale — more agents, longer-running workflows, larger teams relying on agent-produced output — the memory hygiene patterns described here will shift from advanced practice to baseline operational requirement. Organizations that establish these patterns early will find that their agents accumulate accurate institutional knowledge over time; organizations that do not will find that memory becomes a source of drift rather than a source of continuity.
All content represents personal learning from personal projects. Code examples are sanitized and generalized. No proprietary information is shared. Opinions are my own and do not reflect my employer’s views.