Four Rules for Coding Agent Memory That Stays Honest
Storing more notes won't fix coding agent memory. Four rules keep it honest: visible staleness, fail-closed redaction, loud truncation and kept constraints.
This article is published in English.
Sources: Your Coding Agent Has a Memory Problem. Storing More Won’t Fix It.
Open a second chat window and your coding agent knows nothing. Not less than before, but nothing. The decision from forty minutes ago about why the queue-based approach was rejected is gone. So is the constraint that the client's security team will never approve a new database, and so are the three dead ends you already explored so nobody would have to walk them again. Context doesn't survive a window.
Hence the routine: paste in the old chat, type up whatever you recall, and explain again what you can't dig out. That's easily ten to fifteen minutes per switch, and premium requests burned on conclusions you've already bought once.
Nothing in the platforms closes that gap, since each memory feature is scoped to the very thing you're trying to leave. One developer's answer was to build a memory layer on their own: roughly 2,600 lines of Node, no runtime dependencies, serving GitHub Copilot, Claude Code and Codex. Almost at once it hit the part nobody warns about.
Storing more makes things worse
The real failure of a memory system isn't forgetting. It's remembering wrong, with confidence.
Picture a note saying "auth uses JWT", written when that was true and retrieved four months after the codebase moved to server-side sessions. It doesn't fade into uncertainty. It gets retrieved, trusted and built on, and you end up with an agent that is specifically, confidently wrong and can even cite a source. That's strictly worse than an agent saying "I don't know how auth works here", because that agent asks you and the confident one ships.
Storage, then, isn't where the clever engineering is, since it amounts to a folder and a schema. The hard part is guaranteeing that saved knowledge stays truthful while the code underneath it moves. The design landed on four guarantees, each needing little code and a good deal of self-control.
Who writes the notes
The author is a language model, and almost every design choice follows from that. Its input can't be trusted, though not because anyone is malicious: it comes out of a conversation that might have included an API key, a connection string or someone's email address. Its output format can't be taken for granted, and each correction round trip uses up a real request.
The last point shows up somewhere unexpected: the validator reports every problem at once instead of stopping at the first.
export function validateNode(input) {
const e = [];
// ...every check pushes onto e instead of throwing...
if (e.length) throw new ValidationError(e);
return n;
}
Failing fast is the reflex, and here it's wrong. A model fixing its own output can repair everything in one round trip instead of finding faults one by one, each costing a premium request. A small change, but it separates one retry from five.
Notes come in four types, which matters shortly: system, decision, convention and constraint.
Rule 1: make staleness visible when the note is used
You can't prevent the JWT-versus-sessions problem. A note can be accurate on Monday and wrong by March whatever the design. The thing within reach is displaying a note's age at the instant someone is about to rely on it, which is the only moment anyone can act.
Each note records the repository HEAD at which it was captured:
id: auth-service
type: system
title: Auth uses server sessions
scope: repo
confidence: observed
captured_sha: a1b2c3d # repo HEAD at capture
repos: [orders-api]
edges:
- rel: depends-on
dst: postgres-primary
On retrieval that turns into a commit count:
captured 47 commits ago — verify before trusting
There's no model involved, no scheduled job and no background scanner judging freshness. A single git rev-list --count <sha>..HEAD does it, and it's deterministic and cheap enough to run inline.
Three small details turned out to matter more than the main idea.
A rewritten history is a different answer. When the commit can't be reached any more, because of a rebase or a prune, printing zero commits would be a falsehood in the reassuring direction. The tool says "history rewritten, verify" instead. Unknown and fresh are different answers, and they must stay separate.
Notes are annotated only in a repo they claim. A commit count measured against unrelated history is noise wearing the costume of a signal. A note scoped to orders-api and retrieved while you work in billing-api is left alone, not flagged as rewritten.
if (Array.isArray(node.repos) && node.repos.length &&
!node.repos.includes(here)) return null;
There's a floor. Below ten commits, staleness isn't mentioned at all, because a warning that fires constantly is decoration and not a warning. The threshold is configurable. A second, higher one at 100 commits drives a doctor command that lists notes worth a deliberate review, so you can go hunting instead of being told one note at a time.
Rule 2: redaction fails closed
The store sits as plaintext on a corporate desktop, and the model wrote its contents from conversations that might have contained anything. So no write reaches disk without a scan. Fourteen pattern families catch things like AWS keys, GitHub and Slack tokens, private keys, JWTs, bearer tokens, database connection strings, session cookies, private-range IPs and internal hostnames, plus email addresses, and every hit is swapped for <redacted:kind> before writing.
"Fail-closed" does specific work, visible in the first lines of the function:
export function redact(text, opts = {}) {
if (typeof text !== 'string') {
throw new TypeError('redact() requires a string; refusing to write unscanned content');
}
Give it something it can't scan and it doesn't skip the scan and carry on. It aborts the write. A redaction pass has to fail toward "nothing gets written" and never toward "this one slipped through". There's no bypass flag either, because a bypass flag is something you'll eventually use at six on a Friday evening.
Two choices inside it are worth defending.
Connection strings go whole. A URI such as postgres://user:hunter2@db.internal:5432/orders carries its credential inline, so the entire URI is replaced and not only the password inside. A half-redacted URI still hands a reader the host, port, database name and username.
Secrets in assignment form must prove themselves. A naive rule for password: <something> would also swallow a sentence like "the password rotation policy is 90 days", so the rule insists on quotes or a long unquoted run:
{
kind: 'assigned-secret',
re: /\b(?:api[_-]?key|secret|password|token|client[_-]?secret|
access[_-]?key)\b\s*[:=]\s*(?:"[^"\n]{6,}"|'[^'\n]{6,}'|[^\s"'`,;)]{12,})/gi,
}
Redaction that mangles ordinary prose gets switched off, and then it protects nothing. The whole module has exactly one exception: your own git identity survives, since it's already stamped on every commit you've pushed, and hiding it would only make notes harder to read.
Rule 3: truncation is never silent
A depth-2 request on a well-connected node can return fifty notes and overrun the very context window the design protects. Hence a byte budget, 8 KB by default, and pruning once it's exceeded. None of that is surprising. The important part is what happens after pruning:
3 nodes omitted for budget: legacy-batch-job, vendor-sftp-quirk,
old-retry-policy
Every omitted id gets printed, with no exceptions. This rule carries the most conviction, because silent truncation is the failure that looks like success. Given eight of eleven notes and no sign that three are missing, an agent assumes it sees everything and replies as confidently as that implies. The missing three are probably the ones it needed: they were dropped as peripheral to the query, and a surprising constraint often sits at the edge.
Pruning goes deepest-first, then least-connected:
.sort((a, b) => b.depth - a.depth || a.degree - b.degree || ...)
Depth means distance from what was actually asked, and a low degree suggests a node nobody needed as a hub. Breaking final ties by id gives identical bytes for the same query every time, so the reindex determinism test checks something real.
Rule 4: constraints are never dropped
Not at any cap, in either tier, with no exceptions.
const removable = nodes.filter((n) => n.depth > 0 && n.type !== 'constraint');
Two things escape pruning: the root note you requested and every constraint. The logic is about cost, not taste. A constraint says things like the client won't sign off on a new database, a service can't reach the public internet, or the platform team already rejected Kafka. It is exactly the note that keeps an agent from spending a dozen requests heading toward an approach doomed from the start. Cutting one to save four hundred bytes swaps a cheap cost for an expensive one: bytes are inexpensive, a dead-end build isn't.
This produces a case the code has to be upfront about. If the root plus the constraints already exceed the budget, the budget gives way:
Note: 9,412 bytes returned, over the 8,192 budget, because constraints
are never dropped.
It's reported and not fixed, because the fix would be dropping what's worth keeping.
The store is markdown, and the index is disposable
One structural choice supports all four rules: notes are ordinary markdown files with YAML frontmatter, and index.db is a cache that can be deleted whenever you like.
~/.agents/memory/
notes/<type>/<id>.md the source of truth
notes/archive/ superseded and decayed notes; never deleted
index.db disposable SQLite cache
ROUTING.md generated map of everything known
A single index command regenerates the database from the notes, byte for byte. The database is there because walking a graph in SQL is quick while walking a directory of files is slow. The engine is a recursive CTE with a depth limit and UNION in place of UNION ALL, so a contradicts loop can't recurse until SQLite quits. No separate graph layer exists on top of SQLite; the CTE does the job.
Nothing of value is kept solely in the index. Corrupt SQLite and you've lost a cache. Remove the tool and a folder of legible markdown remains, useful with nothing installed. Knowledge ought to outlast whatever indexes it, and a proprietary binary store fails that on the first day.
This is also what lets it install in a locked-down setting, the original goal. Node has shipped node:sqlite in core since 22.5, so the index requires no package, no service and no network. On a managed desktop, proposing a Node script and proposing a new database lead to very different conversations and results.
What was deliberately left out
Nothing is captured automatically: you trigger it, or the handoff skill does. That's a deliberate limit. A background process watching your session and choosing what to keep is the feature everyone requests, and the one likeliest to flood the store with confident noise. All the honesty rules above get weaker as low-quality notes pile up. Ten good notes in a week are worth more than four hundred, which is what you get when a model picks on its own.
Team sharing, multi-machine sync and an MCP server are also postponed. An MCP server would read the same store, so it's an addition and not a rewrite.
One claim is still unproven. The test that counts is a cold read: a new chat, in a repo untouched for a month, replying correctly from the routing digest alone. That takes real elapsed time and can't be simulated in a test suite. Seventy-one tests pass across Linux, macOS and Windows on Node 22 and 24, but none of them shows what you really want to know.
The part worth borrowing
Anyone building memory into an agent workflow, their own or one they ship, can apply these four rules beyond this project:
- Put age in front of the reader where the knowledge gets used, not on a dashboard nobody opens.
- Let the sanitiser fail by writing nothing, and don't add a bypass flag.
- Print what you dropped, because silent truncation reads as full coverage.
- Settle what can never be dropped before the budget gets tight, because decisions made under pressure are worse.
None of these is hard to implement. All four are easy to skip and invisible when they work, which is exactly why they're worth writing down.