How We Built Agent Memory Without a Vector Database (and Where 5 Major Labs Converge and Split)
Spend a few weeks using an AI agent across real projects and you quickly hit the same wall: raw model intelligence stops being the bottleneck. Memory becomes the bottleneck.
Without real cross-session memory, your assistant feels like a brilliant contractor with amnesia. Every morning you re-explain how your repos build, remind it not to ping you during quiet hours, and watch it repeat the exact same mistake it made yesterday.
The obvious first fix everyone tries is dropping a MEMORY.md file into a folder and injecting it at the start of every chat. That works for a weekend. Give it two weeks of real multi-project life, and three things go wrong fast:
- The file quietly bloats. Even if you cap it at 80 lines, models start packing 250-character paragraphs onto single lines—and before you notice, every fresh chat is burning thousands of startup tokens reading stale errands and duplicated summaries.
- Recent trivia crowds out core knowledge. If you naively inject the “latest N remembered facts,” a busy week of personal reminders pushes your coding conventions right off the bottom of the list—so your software-engineering subagent wakes up knowing your dentist appointment instead of how to run your test suite.
- False memories compound. When an agent writes its own end-of-turn summary (“Fixed the build” when a hidden test actually failed), future sessions treat that optimistic note as ground truth.
Across the industry, every major lab has run into these exact failure modes—and arrived at surprisingly different architectures. After building local-first memory for agy-hq (the open-source personal assistant setup I run on Google Antigravity, introduced here and here), I mapped our setup against how Anthropic, OpenAI, xAI, Meta, and Google each solve cross-session memory. Because everyone runs into the same underlying physics, several core patterns naturally converge—while single-user local constraints push a few key trade-offs in a very different direction.
Here is how the landscape compares, and how our 4-layer local memory actually works—without a single cloud server or vector database.
1. How the five major streams approach agent memory
First, it helps to draw a sharp boundary from Anthropic’s recent engineering study, “The components of agent memory”: agent memory is not model fine-tuning, and it is not chat compaction. Compaction shrinks one long conversation when it hits the context window; memory is what survives across completely independent sessions so the agent carries durable knowledge forward.
Looking across five major agent ecosystems today, everyone agrees on a few fundamentals—keep startup context lean, separate raw logs from curated notes, and don’t hoard live API state you can look up on demand—but they diverge sharply on control, scoping, write timing, and security:
- Anthropic (Claude Code / Managed Agents): Champions a clean 4-layer file hierarchy (
raw transcripts→notes→cross-linked markdown wiki→tiny startup index), paired with offline “dreaming” that cross-checks notes against raw session transcripts. Two of their benchmark results are especially revealing:- In Pokémon Red, one wrong self-written note (“Mt. Moon done”) sent an agent jumping off the same one-way ledge three times before giving up and stalling across 3,000 actions—until offline dreaming audited the raw transcript and corrected the bad memory.
- On a 350,000-file enterprise corpus (Stainless), pairing a curated Wiki + Search tool (
61%) beat both Search alone (53%) and Wiki alone (48%), while saving ~20,000 tokens per question.
- OpenAI (dots): Pairs baseline ChatGPT Memory with cloud MicroVM state and idle Proactive Research—background workers that scan connected Gmail, Slack, and Drive threads read-only to compile Private Working Notes before you ask. The cautionary trade-off: those private working notes are an opaque black box—users cannot view, edit, or delete individual notes (the only reset is deleting the entire Dot), and even read-only scans of untrusted emails writing straight into durable notes create an obvious indirect prompt-injection target.
- xAI (Grok Bot & Grok Build): Pioneered role-owned lane memory. Instead of stuffing one account-wide memory soup into every worker, a Chief of Staff bot delegates to specialist lanes (Inbox, Expenses, Research) that each own their own memory. On the developer side, Grok Build stores repo-specific build commands and conventions locally (
~/.grok/memory/) so agents remember project traps without dirtying the repo’s Git tree. - Meta (Muse): Combines a human-editable, glass-box
MEMORY.mdand a 1-commandforgetskill with a relational/vector Active Memory backend and ambient contact dossiers. It proved how much users appreciate editable memory—and its widely covered Marketplace incident (where an autonomous negotiation leaked a user’s street address from memory) proved why memory recall needs strict PII boundaries. - Google (Gemini — Personal Intelligence, Gemini CLI, Vertex): Highlights three practical primitives: fast updates—explicit
save_memorywrites in Gemini CLI alongside a rolling Working Memory Delta buffer in consumer Gemini so fresh corrections override older compressed profile summaries right away instead of waiting for midnight; App Grounding (leaving live Gmail/Calendar state in APIs rather than copying stale snapshots into static memory); and Temporary Chats so throwaway brainstorms never pollute long-term memory.
Side-by-side: Five major approaches—and where our local setup fits
Five major ecosystems on the left, our single-user local setup on the right: similar principles driven by the same failure modes, with explicit local-first trade-offs (including lexical-only BM25).
Putting our local setup next to those five systems highlights the real shape of the problem: rather than stitching together features from five products, designing from first principles for a private, zero-database local folder naturally converges on four pillars—a verifiable 4-layer markdown hierarchy, strict role and repo boundaries, dual-speed writes separating human rules from overnight agent reflection, and hard taint isolation around untrusted inputs.
2. Inside agy-hq’s 4-Layer Local Memory
Instead of running Postgres or a vector store on a personal laptop, agy-hq stores everything inside a git-ignored local/ Vault using plain Markdown and JSONL files organized into four orthogonal layers. The golden rule is Single Source of Truth: every piece of knowledge has exactly one canonical home, so startup context never pays twice for the same line.
Zero databases, four clean layers: immutable transcripts at the bottom keep memory honest, while role-scoped startup caps at the top keep every worker focused.
Partitioning “Preferences” Instead of Building One Global Soup
One subtle lesson we learned early is that “user preferences” are not one flat bucket. Dumping every preference into a global prompt makes your agent worse at everything:
- Who you are & how you talk (rare-change defaults that apply to ~100% of chats) →
USER.md(human-owned; background dreaming never rewrites it). - What you are actively juggling this week (5–8 live threads) →
MEMORY.md(strictly capped at 40 lines AND 2.2 KB—zero duplicated topic indexes, zero old completed projects). - Scoped rules & time-bound commitments (coding invariants, travel preferences, temporary deadlines) →
facts.jsonl, tagged with explicit scopes (global,repo:agy-hq,domain:writing) and optional expiry timestamps (expires_at). - How a specific repo builds, tests, and breaks → the top
## Active Playbookslice of that repo’s topic page (<= 25lines), kept safely inside your private Vault so external repositories stay clean—just like Grok Build. - Per-person quirks & communication channels →
entities/*.md(zero startup overhead; queried only when drafting a message or preparing for a meeting). - Multi-step workflows & behavioral guardrails →
skills/, gated behind human approval so background maintenance can never silently loosen your safety rules.
3. Five Design Choices That Actually Moved the Needle
1. Role-Aware Budgets (So Your Coder Never Carries Your Errands)
When we audited our own Vault after 12 days of daily use (226 conversations, 1,337 turns), two numbers jumped right off the screen: our startup injection had quietly swelled to 30.9 KB (~7,700 tokens), and a naive "load the latest 8 facts" rule for lightweight background workers had evicted 100% of our architecture (8/8) and UX (4/4) invariants while feeding unrelated personal calendar notes into code subagents. Worse, an over-stuffed MEMORY.md could eat the entire startup budget before scoped facts even loaded.
The fix mirrors xAI’s Chief of Staff vs. specialist lanes:
- Your main Front Desk chat acts as the Chief of Staff—it sees your
Active Priorities, the Topic Index, and a balanced slice across domains (capped at<= 3facts per topic so one noisy area can’t crowd out the rest), with zero repo-specific build playbooks cluttering it. - A scoped task or background subagent runs lean (
<= 4.8 KBtotal): it skips your personalMEMORY.mdpriorities altogether, loads the compact## Active Playbookfor its specific repo or domain (<= 1.2 KB), and receives only scope-matched facts + pinned global invariants.
2. Why We Ditched “Usage-Based Decay” (The Negative Guardrail Paradox)
It is tempting to build clever ML-style scoring that promotes “frequently referenced” memories and automatically demotes “unused” ones. We designed a hit-counter like that on paper—and immediately threw it out after spotting the Negative Guardrail Paradox:
Suppose you tell your assistant: “Never send external messages without showing me the exact draft first,” or “Never place market orders during the opening bell.” When your agent obeys that rule flawlessly for a month, those keywords appear zero times in its responses. A lexical hit-counter concludes the rule is “unused” and auto-demotes your most critical guardrail.
Instead of black-box hit scoring, agy-hq uses transparent, deterministic physics:
- Scope match + Pinned + Imminent Expiry (
<= 72h) always sort first. - Zero-token expiry (
expires_at): Any temporary deadline or event vanishes automatically the second its timestamp passes—no LLM needed to remember to delete old calendar notes. - Live-connector grounding: Much like Google Gemini’s App Grounding and Anthropic’s Pokémon hoarding lesson, we refuse to copy volatile inbox lists, daily calendar agendas, or open PR tables into durable memory. Store pointers and non-derivable human decisions; query live APIs when you actually need today’s state.
3. Dual-Speed Writes: Instant Human Truth, Slow Verified Experience
Two speeds for two kinds of truth—plus why usage-based hit counters accidentally delete your best safety rules.
Anthropic’s study highlights a classic tension: writing memory in the middle of a task distracts the agent and produces noisy notes, while waiting for offline nightly consolidation means a correction you gave at 10:00 AM isn’t remembered at 10:05 AM.
Splitting by who asserted the truth resolves the dilemma cleanly:
- Fast path (Human truth → instant): When you state a standing preference or correction in normal conversation (“Keep X replies casual, no links in post 1”), the agent silently records a verified timestamped fact in milliseconds. Every sibling tab sees it immediately, and a simple temporal precedence rule tells the model to trust a newer verified fact over older prose in a wiki summary until midnight cleanup reconciles them.
- Slow path (Agent experience → verified overnight): Agents never pause mid-debugging to scribble speculative theories into long-term memory. A
0-token stop hook records lightweight turn metadata (tools run, error counts, files touched, transcript pointer). At night, dreaming wakes up only if new untainted activity exists (0tokens burned on quiet nights!), runs a deterministic transcript verifier to compare claimed outcomes against raw tool errors and user corrections, and promotes only verified lessons into topic pages. - Negative constraints from rejections: Whenever you reject a staged proposal or edit an agent’s draft, that rejection feeds into nightly dreaming as an explicit negative constraint—so the agent doesn’t turn around and codify something you told it not to do.
- Ephemeral opt-out: Just like Gemini’s Temporary Chats, throwaway experiments (
--ephemeral) stay completely invisible to nightly consolidation.
4. Wiki + Fast Local Search (Zero Embeddings Required)
Anthropic’s Stainless result—that a curated Wiki plus search beats either one alone—matches our own experience. An index of 10–25 topic pages gives the agent a high-level map of what exists, while full-text search lets it pinpoint exact details across older notes, entities, and journals without stuffing everything into startup context.
To keep agy-hq a single zero-dependency Go binary (no SQLite CGo drivers, no local embedding server eating RAM), we built a lock-free BM25 search (hq memory search) directly in pure Go stdlib—the same classic keyword-ranking algorithm behind Elasticsearch and Lucene, just without running a server. It handles code identifiers (camelCase, snake_case) as well as bilingual English + Chinese text in under 15 ms, weights curated topics/ and entities/ higher than raw journal/ entries, and prints clickable file://path#Lstart-Lend citations so both you and the model can verify where a memory came from.
5. Glass-Box Control, Taint Quarantine, and a Real forget Button
This is where local-first memory earns its keep over cloud black boxes:
- Untrusted inputs never touch memory: Any session that reads an untrusted email, chat attachment, or external drop gets marked tainted monotonically for the rest of that run. Under taint,
SessionStartinjects0bytes of Vault memory andhqblocks all durable memory reads/writes—stopping a prompt-injected email from quietly planting persistent instructions like cloud background scanners risk doing. - Concurrent-write safety: Anthropic’s Harvey LAB test showed parallel agents editing one shared markdown file lost
28%of facts to overwrite races. Inagy-hq, all startup readers are lock-free over atomic file renames, while writers take a brief file lock strictly around disk updates (0600permissions). - A real
forgetbutton: Because everything lives locally,hq memory forget "<phrase>"doesn’t just hide a UI card—it scrubs matching lines across active facts, wikis, entities, notes, task handoffs, search caches, and even archived turn journals, so deleted information doesn’t ghost back into search results five seconds later.
4. Treating Memory Health Like Automated Tests
The biggest mistake I made early on wasn’t picking the wrong markdown format—it was relying on vibes to judge whether memory was working.
Now agy-hq includes a lightweight, 0-token evaluator (hq memory eval) that checks four concrete health signals in milliseconds:
- Startup footprint & overlap: Are startup files staying under both line and byte caps, and is cross-layer overlap low (currently
3.37%across our Vault) instead of repeating the same rules in three places? - Scope starvation & TTL hygiene: Are background subagents getting
100%of their repo’s facts with0%personal leakage, and how many date-bound facts are missing expiry timestamps? - Real user friction: Are approval rejections and blocked tool calls per 100 turns trending down over time—instead of counting noisy compile errors during normal coding?
- Wiki graph health: Zero broken links, zero duplicate playbook owners, zero near-duplicate topic pages, and a sanity check against what Anthropic calls Borges’s Map Trap (making sure the wiki stays much smaller than the raw notes it summarizes).
Paired with synthetic CI fixtures (testing scope isolation, auto-expiry, Front Desk caps, and private-folder search exclusion) and offline historical replay over past sessions, we can refactor memory rules without guessing whether we broke recall.
5. Honest Trade-Offs (Where Cloud & Vector Setups Still Win)
Skipping databases and cloud infrastructure isn’t free, and two trade-offs are worth naming upfront:
- Lexical BM25 misses pure semantic synonyms. If one note talks about “rate-limit throttling” and you search “quota exhaustion,” a vector embedding model connects them automatically while BM25 won’t unless both terms (or a cross-linked topic page) bridge the gap. For a personal Vault of dozens to hundreds of curated files, deterministic
<15 msspeed, zero extra daemons, and transparent citations still win for me—and nightly dreaming helps bridge terminology insidetopics/. - Inspectable memory rewards light discipline. Letting an opaque cloud service ingest everything feels effortless—right up until it hallucinates a stale belief you can’t see or delete. Keeping clear scopes and expiry dates takes a tiny bit more structure up front, in exchange for knowing exactly what your agent knows, where it learned it, and how to erase it cleanly.
If there is one takeaway from comparing all five frontier systems while building our own, it is this: good agent memory looks a lot less like an infinite vector attic and a lot more like a disciplined filing cabinet—small startup index, clear ownership by role, instant capture for human rules, ground-truth verification overnight, and strict quarantine around untrusted inputs.
Explore or borrow the pieces
Everything described above—the 4-layer Vault layout, scoped playbooks, 0-token transcript verifier, pure-Go BM25 search, taint boundary, and deterministic memory eval suite—is open source (Apache 2.0, zero external Go dependencies) at github.com/zjshen14/agy-hq.
You can spin up a synthetic --demo sandbox locally in under a minute without touching any of your personal files:
git clone https://github.com/zjshen14/agy-hq.git && cd agy-hq
./scripts/bootstrap.sh --demo
./bin/hq memory status
./bin/hq memory eval --fixtures Scan with WeChat
Scan this QR code with WeChat to read or share on mobile.