DEV Community

Oleh Yudin
Oleh Yudin

Posted on Originally published at Medium AI-assisted

I Built a Memory System for Claude Code That Knows How to Update

Part 1 of a two-part series on building practical long-term memory for coding agents.

Four stages of the hook-based workflow: observe, propose provisional claims, reinforce after later corroboration, and suggest reuse in a skill with user approval. A separate track handles aging, correction, and explicit forgetting.

Original illustration. The goal is a governed lifecycle, not a growing transcript archive.

A coding session without relevant persistent context begins with a small act of amnesia.

The model can read the repository again. It can inspect CLAUDE.md, search Git history, and ask me questions. But without persistent context, it may miss a preferred package manager, a failed release procedure, or the environment setting behind a strange test error.

The obvious solution is to save everything. It is also the wrong solution.

A transcript archive grows without bound, mixes durable knowledge with temporary noise, and eventually makes retrieval harder rather than easier. Useful memory needs selection, confidence, correction, decay, and deletion.

I built my Claude Code memory system around that idea:

Agent memory should not be a permanent transcript. It should be a small, inspectable collection of claims that can strengthen, fade, be corrected, become a reusable skill, or be forgotten.

The first version is a set of local Claude Code hooks and agent skills. Markdown files remain the source of truth. SQLite, local embeddings, and a small knowledge graph make those files searchable. A session-end distiller proposes new memories, while a promotion gate keeps one-off guesses away from future sessions.

This article explains the design, the tradeoffs, and what I learned from using memory as an engineering system rather than a chat feature.


Memory is not one thing

I use five conceptual kinds of memory because they have different jobs and should not have the same retention policy.

  • Preference: how I like work to be done. Long-lived.
  • Procedural: a workflow that succeeded. Very long-lived.
  • Fact: durable project knowledge not already in code or docs. Long-lived.
  • Episodic: what happened in a particular task. Short-lived.
  • Trace: a compact timeline of prompts and tool activity. Very short-lived.

A preference might say, “Use uv, not pip, for Python environments.”

A procedural memory might say, “To release this package, update the version, create the tag, and then run the release target.”

An episodic memory is different. It records a goal, decisions, what changed, and open work from one session. It is valuable when resuming a task, but it should not remain equally important forever.

A trace is different again. It is operational evidence: commands, paths, tools, and clipped errors. It supports distillation and recovery, but it is never injected directly as long-term memory.

Treating all of these as interchangeable “memories” creates bad incentives. A successful procedure should survive longer than a session summary. A trace should expire even if it was once useful. A user preference deserves more weight than an inference made from one interaction.

The split is not new. CoALA (Sumers et al., 2023, arXiv:2309.02427) describes language agents with working, episodic, semantic, and procedural memory; I added traces and preferences because a coding assistant needs them.

The implementation has two more specialized tiers. Ideas never fade with age. Rules are never archived either: when a rule outlives its time constant, maintenance flags it for re-verification against current documentation instead of letting it quietly fade.


The lifecycle is built from Claude Code hooks

There is no resident memory service in this version. Claude Code hooks connect the pieces to the session lifecycle.

Claude Code lifecycle hooks: session start maintains and briefs; each prompt records and retrieves; tool results record outcomes; session end launches detached distillation into an episode and candidates.

Each hook has one narrow job. Distillation uses a Claude call; the storage and retrieval layers run locally.

The distinction between the start-of-session brief and per-prompt recall matters.

The brief carries broadly applicable context: preferences, procedures, strong facts, and recent episodes. It is a selection, not a full dump: the hook shares a budget of eight entries across sections. Per-prompt recall is narrower. It asks, “Which existing memories are relevant to this particular request?” It returns short pointers, at most three per prompt, and avoids reinjecting the same memory within a session.

The hook scripts are fail-open. If memory maintenance or retrieval fails, Claude Code should still work. Errors go to a local log instead of blocking the coding session.

That choice is important. Memory is an enhancement, not a dependency that should be able to take down the agent. The supplied hook commands still assume a POSIX shell and local paths; detached distillation uses fork and setsid. This is not an unchanged Windows installation recipe.


Plain Markdown is the source of truth

Each durable memory is a small Markdown file with simple frontmatter. For example:

---
name: prefer-uv-for-python
description: "Use uv rather than pip for Python dependency management"
metadata:
  tier: preference
  confidence: 0.7
  reinforced: 0
  last_reinforced: 2026-10-13
  created: 2026-10-13
---

Use `uv` for environments and dependency installation.

**Why:** It is faster and keeps the workflow consistent.
**How to apply:** Prefer `uv venv`, `uv sync`, and `uv run`.
Enter fullscreen mode Exit fullscreen mode

I chose files as the authority for several reasons:

  1. They are inspectable. I can read what the agent believes.
  2. They are editable. A wrong claim does not require a database console.
  3. They are portable. Files can be backed up or moved with ordinary tools.
  4. They degrade gracefully. If the database disappears, the memories still exist.
  5. They discourage opaque state. The agent cannot hide important knowledge inside an inaccessible vector store.

A generated MEMORY.md acts as a ranked catalog. It is useful for Claude Code and for human inspection, but it is not authoritative.

SQLite is a derived index over the files. It stores parsed metadata, text, local embedding vectors, entity mentions, graph edges, and links such as “contradicts” or “supersedes.” Graph entities and relations live in JSON sidecars alongside the Markdown; keep those files too when backing up or rebuilding the index.

This source-of-truth boundary is one of the strongest decisions in the project: files own the knowledge; the database only accelerates access.


New inferences must earn promotion

A coding agent frequently observes patterns that might be useful later:

  • “The user probably prefers compact pull requests.”
  • “This repository may require a particular test command.”
  • “That failure appears to come from an environment variable.”

Some of those observations are right. Others are accidents of one task.

Writing every inference directly into active memory creates a feedback loop: the agent guesses, stores the guess, reads it in a later session, and treats its own repetition as evidence.

My system therefore separates explicit knowledge from inferred candidates.

  • A preference stated directly by the user can become active immediately.
  • A candidate inferred by the session distiller starts provisional with low confidence.
  • Provisional memories are hidden from normal briefs and recall.
  • A matching observation from a later session reinforces and activates the memory.

For each eligible distillation attempt, the session-end distiller makes a headless Claude Haiku call by default; failed attempts can be retried. It receives a trimmed user/assistant transcript, a trace summary, and the names and descriptions of existing memories. It returns an episodic summary and at most three candidate memories.

Near-duplicates are detected using description-token overlap. A match from an earlier session increases confidence, increments a reinforcement counter, resets the decay date, and can promote a provisional memory to active status.

This is a lightweight gate: corroboration, not proof. Current code, documentation, and the user still outrank memory.


Corrections should supersede, not overwrite

Long-term memory needs a correction model.

Suppose an old memory says:

Deploy the service with make deploy.

The process later changes:

Deploy by pushing a version tag; CI performs the release.

Silently editing the old file erases useful history. Keeping both active creates a contradiction. Deleting the old one makes it harder to understand why earlier work behaved differently.

The replacement memory therefore points to the old memory with contradicts: <old-file>.

If the replacement is provisional, nothing happens yet. It must first be corroborated. Once active, maintenance marks the old memory as superseded and moves it to an archive with its body intact.

This provides three useful properties:

  • normal recall sees only the current claim;
  • the old claim remains available for audit;
  • an uncertain correction cannot retire established knowledge.

Archive is not the same as forgetting. When I explicitly ask the agent to forget something, the file, graph sidecar, archived copy, and index entry should be deleted. In this hook version, that cleanup is an agent workflow, not a dedicated forget API; it does not erase the original transcript, distillation audit files, or external backups.


Useful memories strengthen; unused memories fade

Every active memory has confidence and a decay anchor. Its score declines exponentially with age and rises when reinforced. Here, “confidence” is a heuristic weight assigned by defaults or the agent—not a calibrated probability that a claim is true.

The hook version's time constants are e-folding times rather than true half-lives: exp(-age / τ) leaves about 37% after one interval, not 50%. The MCP version in Part 2 fixes that.

The behavioral idea is straightforward:

memory score = confidence × age decay
Enter fullscreen mode Exit fullscreen mode

Generative Agents (Park et al., 2023, arXiv:2304.03442) ranks memories by recency, importance, and relevance, with an exponential recency decay. My score uses the same idea with a separate rate for each kind.

Different kinds decay at different rates. Procedures are expected to remain useful much longer than episodes. Low-scoring memories are moved to an archive rather than deleted. Pinned items can be exempted.

Reinforcement should represent evidence, not exposure. Per-prompt recall does not automatically strengthen everything it returns. Otherwise frequently retrieved memories would become permanent merely because they were already winning the ranking.

A memory is reinforced when it proves useful, is confirmed by the user, or is independently observed again.

This small distinction avoids a rich-get-richer retrieval loop.


Recall combines words, meaning, and relationships

No single retrieval method works well for coding memory.

Keyword search is excellent for file names, commands, ticket IDs, and exact errors. Semantic vectors are better when two phrases mean the same thing but share few words. A graph helps when the prompt names an entity connected to another relevant entity.

On every prompt, the recall hook ranks memories with all three signals, fuses the rankings, weights them by each memory's decayed score, and injects at most three short pointers. Part 2 walks through the same pipeline, step by step, in the MCP version.

If embeddings are unavailable, recall continues with keyword and graph search. If the index fails, it falls back to keyword matching. Memory should fail softly.


A memory can graduate into a skill

One of the more useful consequences of separating memory kinds is that repeated procedural knowledge can become executable guidance.

A remembered rule only helps when it reaches the agent’s context. A Claude Code skill can contain a fuller workflow, and its description helps the agent decide when to load it.

At session start, another script looks for active procedural or preference memories with sufficient confidence or at least one reinforcement. It compares their descriptions with my own installed skills using local embeddings and suggests one of two actions:

  • update an existing skill;
  • create a new skill.

The promotion is advisory. The agent must show me the proposed rule and wait for approval. It never rewrites skills automatically.

After acceptance, the memory is marked with the skill that implements it, so the suggestion stops. The original memory remains available for recall and provenance.

Two of my own preferences took this path. One says every script must stop within a bounded time, with timeouts on network and subprocess calls. The other says multi-step plans should be written as a graph of nodes with the same card for every node. Both crossed the eligibility bar, the agent suggested a skill for each, and I approved them. They are now the script-timeouts and plan-graph skills in the public repository.

The complete path has an explicit approval boundary:

Session context and trace produce two separate outputs: an active episode summary and a provisional candidate. Later-session corroboration can activate the candidate. Eligible procedures and preferences may then become skill suggestions, applied only with user approval.

The episode and candidates are separate outputs. Not every observation reaches a skill.


What six months showed

I have used this system since late March 2026. By mid-October, my memory directories held 73 files across 18 project and global directories:

  • 12 inferred memories were still provisional: the distiller proposed them, and no later session has seen them again;
  • 8 memories had been reinforced at least once;
  • 10 were episode summaries;
  • 3 had been archived, and 1 had been superseded by a correction;
  • 2 preferences had become skills.

The provisional pile is the number I watch. Each of those twelve guesses would have been active memory in a system without the gate, injected into later sessions with nothing behind it but one conversation. Whether the gate is too strict is a fair question; six months is not long enough to answer it.


Privacy is a system property, not a slogan

The system is local in the sense that its files, SQLite index, graph, and optional embeddings live on my machine. But memory injected into a Claude Code request is sent to the configured model provider along with other context. The session distiller also calls Claude Haiku through the Claude CLI by default. Local storage and retrieval do not make this an offline or local-only inference system.

Trace events are deliberately narrow. They store short pointers such as commands, file paths, URLs, tool names, and clipped errors rather than tool output. Common credentials, tokens, JWTs, secret assignments, and credential-bearing URLs are redacted heuristically.

There are still limits worth stating plainly:

  • heuristic redaction can miss unusual secrets;
  • clipped user prompts are present in trace files;
  • transcript text is trimmed, but is not passed through the trace redactor before being sent to the distiller;
  • parsed distillation output is retained temporarily for audit and retry;
  • local files are not encrypted by this project.

The design minimizes retained data, but it does not turn arbitrary transcript content into harmless data.

Privacy claims should describe mechanisms and boundaries, not simply say “local.”


Where this sits among other memory tools

Claude Code already has memory of its own: CLAUDE.md files and an auto-memory directory, which my hooks read and manage. Basic Memory keeps Markdown files with a SQLite index behind MCP, close to the storage design here. The reference MCP memory server keeps a knowledge graph of entities and observations, and mem0 offers a memory layer you can host yourself or use as a service.

Storage is the solved part. What I cared about is the rules for trust: inferred memories stay provisional until they are seen again, recall never counts as evidence, decay depends on the kind of memory, and corrections retire old claims instead of overwriting them.


What worked—and what I would change

Several ideas proved durable:

Keep human-readable files authoritative

A rebuildable index is easier to trust than an opaque primary database. It also makes debugging much simpler.

Separate explicit statements from inference

Provisional memory is essential. Agents are persuasive enough without being allowed to cite their own guesses as history.

Do not reinforce on retrieval

Use is evidence only when the result actually helped.

Let knowledge age differently

A procedure and a session summary should not compete under identical retention rules.

Preserve corrections as history

Supersession is safer and more explainable than in-place mutation.

Make automation advisory at the skill boundary

Automatically proposing a skill is useful. Automatically rewriting agent instructions is too much authority.

I would also change parts of the original design:

  • use a mathematically correct half-life formula;
  • harden project isolation in graph traversal;
  • replace lossy scope identifiers with collision-resistant ones;
  • apply consistent secret filtering before all retained or transmitted summaries;
  • avoid POSIX-specific detached-process assumptions;
  • expose the memory system through a standard interface instead of Claude Code hooks alone.

That last point led to the next version.


From a personal Claude Code mod to a portable protocol

The hook implementation gave me automatic lifecycle integration: traces, per-prompt recall, session-end distillation, and post-compaction reinjection.

It was also tightly coupled to one client.

Cursor, Zed, VS Code, Claude Desktop, and other agents do not share Claude Code’s hook model. What they increasingly share is MCP, the Model Context Protocol.

So I extracted the durable parts of the design—typed memory, files as truth, derived search indexes, decay, reinforcement, provisional status, supersession, and explicit forgetting—into a local MCP server.

That version gives up some automatic observation in exchange for portability and a smaller trust boundary.

In Part 2, I will show how the MCP version works, what an MCP server can and cannot know, and why “explicit memory tools” may be a better abstraction than invisible transcript capture.


Examples are synthetic unless noted; the numbers in "What six months showed" come from my own memory store. Both projects are personal and not affiliated with Anthropic.

Code: the hook version described here is at https://github.com/Oleg67/claude-code-memory-hooks. The portable MCP version from Part 2 is halflife-mcp on PyPI.

Top comments (0)