Knowledge Bases & Memory9 min readยท

Persistent Memory for Coding Agents: How Memory and Live-Docs Tools Work and What They Cost in Tokens

On Monday your coding agent learns that the payments service retries idempotently. On Tuesday it asks again, or it writes code against a Next.js API that was renamed in the latest release.

On Monday your coding agent learns that the payments service retries idempotently. On Tuesday it asks again, or it writes code against a Next.js API that was renamed in the latest release. Persistent memory tools fix the first problem and live-docs tools fix the second. Claude-Mem records what happens in each session and gives the next session a short index of it. Context7 fetches current library documentation when the agent asks. Both cost tokens, and neither shares your team's decisions. Sanity Context fills that gap by serving versioned team knowledge to agents over a hosted MCP endpoint.

How context loads makes a big difference to cost. Anything loaded up front is paid for on every request, whether or not the model uses it. Claude-Mem's own docs compare a 35,000-token up-front dump, of which about 2,000 tokens were relevant, with an 800-token index of 50 observations. If you load context the wrong way, you pay for noise and the model loses track of the task.

This guide treats memory as a retrieval problem with a token budget. It covers how each pattern spends tokens, where each one fails, and how to choose between local memory files, MCP-served docs, and a shared context layer with an owner.

What is persistent memory for a coding agent?

Persistent memory for a coding agent is any context that lasts beyond a single session and goes back into the model's context window when it's useful again. Coding agents such as Claude Code and Cursor run long tasks inside sandboxed harnesses, and every new session starts with an empty context window. Without persistent memory, the agent has to rediscover the same build quirks, conventions, and architecture decisions every morning.

Two patterns are common today. Session memory records what the agent saw in past sessions and replays it later. Claude-Mem is the best-known example. Lifecycle hooks record what the agent does, a second AI worker compresses those records into observations, and the next session starts with a short index of them. Live-docs retrieval pulls current third-party documentation into the context window when needed. Context7, from Upstash, is the best-known example: a hosted index of library docs that agents query through two MCP tools.

The two patterns answer different questions. Session memory answers "what did we learn last time in this repo?" Live-docs retrieval answers "what does this library's API look like in the version we use?" Neither answers "what has the team decided?", and that third question causes most of the confusion in production.

It helps to sort context by how long it lasts and who owns it. Static instructions belong to whoever defines how the agent behaves. Per-turn state belongs to the application. Retrieved content belongs to the people who write it, such as a docs or platform team. Agent-authored notes are memory the agent writes for its own future self. Session memory tools fall in the last group and live-docs tools in the retrieved-content group. If you treat all four as one bucket, three of them usually end up underbuilt, because each needs its own rules: who can change it, how it goes out of date, and who notices when it's wrong.

How does Claude-Mem capture and replay session memory?

Claude-Mem captures session memory with lifecycle hooks, compresses it with a second AI worker, and replays it through progressive disclosure. The next session gets a short index instead of the full history. Progressive disclosure means loading a cheap summary first and fetching details only when the model asks for them.

Claude-Mem's own documentation says the SessionStart index for 50 observations costs about 800 tokens, and one fetched observation costs about 120 tokens. The same docs compare this with a traditional up-front dump of 35,000 tokens, of which about 2,000 tokens (roughly 6%) were relevant to the task.

Retrieval runs in layers over a local stdio MCP server. A compact `search` tool returns an index at about 50 to 100 tokens per result. A `timeline` tool adds context in time order. `get_observations` returns full details for selected IDs, and a fourth layer exposes the raw tool calls. The vendor claims about 10x token savings from filtering before fetching. Memory Atlas, which tracks these tools, notes that these are vendor claims and haven't been independently reproduced. One r/ClaudeCode thread is titled "claude-mem was eating 58% of my tokens" and describes a multi-agent setup. That's one user's anecdote, not a measurement, but it's a reminder that the compression worker and repeated lookups cost tokens too.

All data stays on the local machine. Sessions and observations live in SQLite under ~/.claude-mem, and Chroma embeddings support hybrid semantic and FTS5 keyword search. The project is Apache-2.0 and free to self-host. Cloud sync is opt-in and paid: Memory Atlas lists CMEM Pro at $30 per month and Team Cloud at $333 per seat per month, based on sources fetched in November 2026. Independent audits in February and March 2026 rated the unauthenticated local worker API on port 37777 as HIGH risk. That matters if you run it on a machine that holds production credentials.

Illustration for Persistent Memory for Coding Agents: How Memory and Live-Docs Tools Work and What They Cost in Tokens
Illustration for Persistent Memory for Coding Agents: How Memory and Live-Docs Tools Work and What They Cost in Tokens

How does Context7 bring live library docs into the context window?

Context7 brings live library documentation into the context window through two MCP tools. `resolve-library-id` matches a library name to an ID, and `query-docs` returns relevant snippets from Upstash's hosted documentation index. The server runs at https://mcp.context7.com/mcp. Context7 can also run as a CLI plus a skill, with no MCP at all.

The token cost has been measured. In an October 2026 test by octomind of @upstash/context7-mcp 4.1.1, using the o200k_base tokenizer, the two tool schemas cost 1,058 tokens (646 for `resolve-library-id` and 410 for `query-docs`), plus 126 tokens of server instructions. A resolve call cost 537 tokens. An unpinned `query-docs` call cost 1,881 tokens and a version-pinned one cost 2,482, so a full lookup comes to about 2,400 tokens. The tool descriptions allow up to three calls of each tool per question, so a hard question can make six calls. In the unpinned answer, 16% of the text was a duplicated code block.

Two settings change the bill. First, passing a library ID such as `/vercel/next.js` directly skips the resolve step. Second, tool loading. Claude Code defers MCP tool loading by default through tool search, but clients that load every tool up front send the 1,058 schema tokens with each request, even if the agent never looks up a library. In most harnesses, tool descriptions are part of the prompt, so a server that's installed but idle still costs money.

The free API key covers 1,000 calls a month. The backend, parser, and crawler are private, and the project's disclaimer says the library docs are community-contributed with no guarantee of accuracy. Context7 covers public third-party libraries. It doesn't know your team's private conventions, your internal services, or why you pinned a particular dependency.

What are the failure modes of coding agent memory?

Coding agent memory fails in three predictable ways. It goes out of date or contradicts itself, it bloats the context window, and it stays stuck with the person who created it.

Staleness is the least visible failure. Context7 shows it clearly: an unpinned library ID answers for the newest release. In octomind's October 2026 test, a Next.js query returned canary snippets that use `proxy`, which was renamed in Next.js 16. That code would be wrong for a Next.js 15 project. The fix is to put the version in the library ID. Session memory goes stale in a different way. Say an observation recorded in March notes that the team uses a certain logging library. The agent still replays it in June after the team has migrated, and nothing in a local SQLite file knows the two observations conflict.

Context bloat is the expensive failure. A large context window tempts teams to load everything. But overfilling it can cause the model to lose track of what it's doing, and it's slow and expensive. Memory files that keep growing, tool schemas loaded up front, and lookups repeated six times per question all push the same way. For production agents, cost per conversation is usually the second metric to watch after success rate, and evals alone can multiply usage.

Isolation is the team failure. Session memory saved to ~/.claude-mem on one laptop helps one developer. A teammate's agent starts from zero, relearns the same lessons, and may learn different ones. Paid cloud sync moves the files, but syncing isn't the same as governing them. Nobody owns the decision about which memory is true when two developers' agents disagree.

These failures make each other worse. The worst case is a stale memory that only one person holds, injected into a crowded context window. It's wrong, it's expensive, and the rest of the team can't see it.

The cheaper Context7 lookup gave the wrong answer

In octomind's October 2026 measurement, an unpinned query-docs call cost 1,881 tokens and a version-pinned call cost 2,482. The cheaper call returned Next.js canary code that uses proxy, which was renamed in Next.js 16 and would be wrong for a Next.js 15 project. Pinning costs about 600 more tokens per lookup, which is far less than debugging code written against the wrong major version.

How do you keep memory and docs lookups cheap in tokens?

The cheapest token is one you never send. Every technique that keeps memory affordable either delays what enters the context window or shrinks it: summaries, progressive disclosure, and retrieval on demand.

Summaries replace raw history with a compressed version. Claude-Mem's AI worker turns tool calls into observations, which is why, by the vendor's count, a 50-observation index fits in about 800 tokens. The tradeoff is that compression is itself a model call, and a summary can drop the detail that mattered.

Progressive disclosure loads an index first and details later. It works when the index is small enough to keep for the whole session and specific enough that the model knows what to fetch. Claude-Mem's layered `search`, `timeline`, and `get_observations` tools follow this pattern. So does any system that serves an outline with one-line summaries before the full entries.

Retrieval on demand fetches only when the task needs it. Context7 works entirely this way: nothing about Next.js enters the context window until the agent asks. Each lookup costs about 2,400 tokens in octomind's measurement. That's fine for occasional questions, but it adds up when the agent makes six calls for one question.

A practical token budget for a coding agent follows from these patterns:

- Keep always-loaded instruction files short and limited to rules that apply to every task.
- Pin library versions in lookups so the expensive call returns the right answer the first time.
- Prefer clients that defer MCP tool loading, since otherwise the schemas go out with every request.
- Keep the tool list small. A model routes better between ten focused tools than fifty overlapping ones.
- Measure cost per task, not per call. A cheap call that triggers three retries isn't cheap.

None of these techniques solves ownership. They lower what memory costs, but they don't decide whether a memory is still true or who else should see it.

How do you choose between local memory files, MCP-served docs, and a shared context layer?

Choose based on who owns the knowledge and how often it changes. Local memory files suit rules a repository needs on every task. MCP-served docs such as Context7 suit public libraries that change with each release. A shared context layer with clear ownership suits team decisions that several people and agents need to agree on.

Local memory files such as CLAUDE.md, AGENTS.md, and Cursor rules load at the start of every session. You can version them in git and review them in pull requests, which gives them basic governance. They have no conflict detection and no retrieval on demand, so their token cost grows with the file. They work best when kept short.

Session memory tools like Claude-Mem give one developer continuity: what their agent tried yesterday. They're the only option here that captures memory automatically, but the result stays on the local machine by default.

Live-docs tools like Context7 keep third-party APIs accurate, as long as lookups are pinned to the version in your lockfile. Context7 is a good default for public frameworks that ship breaking changes. It's the wrong place to look for anything your team decided.

The gap is team knowledge: the architecture decision, the deprecated internal endpoint, the convention that changed last quarter. That knowledge needs an owner, version history, a way to resolve conflicts, and a way to reach every agent on the team, not just one machine. That's the case for a shared context layer.

Most teams end up combining all four: a short instruction file for rules that never change, session memory for each developer's continuity, pinned live-docs lookups for libraries, and a shared layer for decisions that have to hold for everyone. The mistake is making one tool do another's job, like growing CLAUDE.md into a wiki or treating a memory store on one laptop as the team's source of truth.

Where does Sanity Context fit in a coding agent's memory stack?

Sanity Context is the shared, governed layer in this stack. It serves structured, versioned team knowledge to coding agents over a hosted MCP endpoint, so knowledge the whole team needs isn't stuck on one machine. Sanity is the AI Content Operating System, the intelligent backend for companies building AI content operations at scale. Sanity Context gives agents structured, governed access to that content. It has three parts: an MCP endpoint, a knowledge base, and an ingest path.

Context MCP is a hosted, read-only endpoint that any agent loop can connect to, including the harnesses coding agents run in. It retrieves content in two modes. GROQ mode queries the dataset at request time. It returns exact results across hundreds of thousands of records, with no build step and nothing to keep in sync. With dataset embeddings turned on, one GROQ query can combine structured filters with `text::semanticSimilarity()`. That function only works inside `score()`, because semantic search ranks results rather than filtering them.

Knowledge Base mode applies progressive disclosure to team knowledge. A Knowledge Base is a prebuilt index over sources you choose. Its outline lists every entry path with a one-line summary. The outline is small enough for an agent to keep in context for a whole conversation, and the `initial_context` tool serves it. The agent fetches full entries only when it needs them, and each entry cites its sources.

Knowledge Bases also deal directly with stale and conflicting facts. Say a help center says returns are accepted within 30 days and a product page says 45. A build flags this as an issue, shows both claims with their sources, and a person picks the ground truth. Instructions record which source to trust and retire automatically when those sources change. Nobody can edit entries by hand. The index belongs to an organization and can draw on more than one project. Content written in the Studio also gets version history, scheduled publishing, rollback, and role-based edits.

โ„น๏ธ

What Sanity Context does not do

Context MCP is read-only, and Sanity Context doesn't automatically capture coding sessions the way Claude-Mem's lifecycle hooks do. Use it for the team knowledge every agent should share, and keep session memory for each developer's continuity. Knowledge Bases are in Beta and opt-in: an org admin turns them on in Manage.

Coding agent memory and docs tools compared

FeatureSanityClaude-MemContext7 (Upstash)Local memory files
What it remembersTeam knowledge from sources you choose, served as Knowledge Base entries that cite their sources, plus structured content queried directly in GROQ modeSession observations, captured automatically: lifecycle hooks record agent activity and an AI worker compresses it into observations for later sessionsDocumentation for public third-party libraries from a hosted, community-contributed index. It doesn't cover your team's private conventions or decisionsWhatever a developer writes into CLAUDE.md, AGENTS.md, or Cursor rules: repo rules, conventions, and setup notes, kept as plain text
What loads up frontKnowledge Base outline served by `initial_context`: entry paths plus one-line summaries, small enough to keep for a whole conversation, with entries fetched on demandA SessionStart index of 50 observations at about 800 tokens, per the vendor's docs. Each fetched observation costs about 120 tokens1,058 tokens of tool schemas plus 126 of server instructions when the client loads tools up front. Claude Code defers tool loading by defaultThe whole file, every session, on every task. The token cost grows with the file because there's no retrieval on demand
Cost per lookupGROQ mode queries the dataset at request time with exact filters, so the agent fetches only matching records instead of a broad dump of contextLayered `search` at about 50 to 100 tokens per result before `get_observations`. The vendor claims about 10x savings, which hasn't been independently reproducedAbout 2,400 tokens per full lookup in octomind's October 2026 test. The tool descriptions allow up to six calls for a hard questionNo lookup cost because nothing is fetched. Instead, you pay up front on every request, whether or not the agent needs the facts
Stale and conflicting factsKnowledge Base builds flag conflicting facts as issues with their sources side by side. Instructions retire automatically when their sources change (Beta, opt-in)Observations stay in local storage until pruned. The documented retrieval layers focus on finding memories, not on resolving conflicts between themUnpinned IDs answer for the newest release, so a Next.js 15 project can get Next.js 16 canary code. Putting the version in the library ID fixes itOutdated lines stay until someone edits them. Git history and code review show changes, but nothing detects contradictions automatically
Sharing across a teamThe index belongs to an organization and can draw on several projects. Every agent connects to the same hosted, read-only Context MCP endpointStored locally in ~/.claude-mem. Team sharing goes through opt-in, paid CMEM Cloud, which Memory Atlas lists at $333 per seat per month for Team CloudShared by default because the index is hosted and public. That suits libraries but leaves your team's private knowledge out of scopeShared through the repository and pull requests, so everyone gets the same file, but only for that one repo
Governance and securityThe Studio provides version history, scheduled publishing, rollback, and role-based edits. Knowledge Base entries cite their sources and can't be edited by handApache-2.0 and self-hosted. Independent audits in Feb-Mar 2026 rated the unauthenticated local worker API on port 37777 as HIGH riskThe backend, parser, and crawler are private. The disclaimer says the docs are community-contributed with no guarantee of accuracyGit versioning and review give you attribution and rollback. Access control is limited to repository permissions, and there's no eval gate by default
Automatic session captureNot automatic. Sanity Context doesn't capture coding sessions, and Context MCP is read-only. Pair it with session memory for each developer's continuityAutomatic. Lifecycle hooks capture agent activity without anyone writing notes, and it works with Claude Code, Codex, Cursor, OpenCode, and moreNot applicable. It serves documentation instead of recording sessions, and the agent pulls docs through `query-docs` when neededManual, though agents can be told to append notes. Quality depends on who edits the file and how often it gets reviewed