Long-Term Memory for Coding Assistants: A Local Small-Model Approach
A practical architecture for giving AI coding assistants long-term memory using a local small language model, human-readable file storage, and periodic summarization. This article covers the full lifecycle—capture, judgment, storage, consolidation, injection, and audit—along with entry schemas, write policies, cost logic, and a staged rollout plan. It explains why memory curation should run on local inference rather than expensive per-token API calls, and how to keep memory reliable, private, and auditable.
Long-Term Memory for Coding Assistants: A Local Small-Model Approach
1. The Problem: Smart Conversations, Forgetful Projects
In real development workflows, what gets most overestimated about AI coding assistants is the quality of a single response; what gets most underestimated is continuity across sessions. A project contains a lot of information that cannot be inferred from the current code snippet alone: why a module deliberately keeps backward-compatibility logic, why a certain API signature must not change casually, what exception-handling style the team prefers, which checks must run before release, and which past refactor once introduced a subtle regression. If these facts live only in chat history, the assistant keeps making the same mistakes in new sessions, and developers keep re-explaining the same constraints.
The value of long-term memory is not to archive every conversation, but to persist “information that will change future decisions” in a way that is cheap, reversible, and auditable. In coding contexts, memory should not be a vague user profile—it should lean toward engineering facts: conclusions, preferences, project constraints, workflow practices, lessons learned from failures, plus the scope and expiry conditions of each conclusion. This article describes a neutral implementation: no dependency on any specific third-party platform, built on local inference, local file storage, and periodic compression, designed as a pluggable memory layer for common extensible assistant frameworks.
2. Conceptual Boundaries: Working Memory vs. Long-Term Memory
Cognitive layering is useful as an analogy but should not be applied mechanically. For a coding assistant, the current context window is closer to working memory: limited capacity, fast read/write, gone when the session ends. Plans, todos, and intermediate results within a single task resemble episodic memory—they capture how the process unfolded. What truly needs long-term retention is a blend of semantic and procedural memory: what this project is, what to avoid, and how things are usually done.
A long-term memory system should not try to remember everything; it should deliver three benefits. First, reduce repeated explanation: stable preferences and project constraints enter the prompt context automatically. Second, reduce repeated mistakes: failure causes, fix paths, and verification commands become searchable entries. Third, produce an evolving project summary, where periodic recaps compress scattered events instead of endlessly piling up raw text. One principle should be explicit: memory is an evidence base that assists decisions—not a second source of truth that replaces code, documentation, and code review.
3. Overall Architecture: Capture, Judgment, Storage, Consolidation, Injection, Audit
A robust memory layer can be split into six subsystems. The capture layer collects events from the conversation stream: explicit user requests to “remember this,” key conclusions produced by the assistant, test-failure log summaries, requirement changes, and so on. The judgment layer uses a local small model for lightweight classification and scoring, deciding whether a fragment deserves the candidate queue—keeping small talk, temporary experiments, and one-off error messages out of the long-term store. The storage layer uses human-readable local documents plus structured metadata, so entries can be inspected directly and indexed programmatically. The consolidation layer runs daily, weekly, or per milestone, performing deduplication, merging, conflict flagging, and expiry demotion. The injection layer assembles context before each query, including only the relevant, high-confidence subset of memories. The audit layer records write provenance, modification diffs, injection history, and deletion reasons, so “why does the assistant know this” is always answerable.
The key to this architecture is a closed loop: more writing is not better. A lifecycle runs from candidate → confirmed → active → reused → decayed → cleaned up. Every memory entry should carry source evidence, a confidence score, a scope, and a last-reused timestamp. Every memory injected into a prompt should be traceable back to its entry. Every conclusion produced by consolidation must preserve summary pointers to the merged entries. This significantly reduces memory pollution, preventing a single bad extraction from being amplified indefinitely.
4. The Memory Entry Model: Making Every Lesson Manageable
Use a document format that is “human-readable in the body, machine-readable in the header.” The body states the conclusion in natural language; the header carries governance metadata. An example:
id: mem_2026_000731type: project_constraint # conclusion | preference | constraint | workflow | pitfallscope: repo:payments/servicestatement: "Reconciliation tasks must be idempotent; duplicate triggers must never cause double charges."evidence: "2026-02 session: retries caused duplicate ledger entries; fixed with request_id deduplication."confidence: 0.86sensitivity: internalstatus: active # candidate | active | stale | archived | deletedcreated_at: 2026-02-11T10:20:00+08:00last_seen_at: 2026-04-18T16:40:00+08:00review_after: 2026-07-18tags: [idempotency, retry, ledger]
Here confidence should not come from the model’s subjective “I’m sure”—it should combine evidence strength, whether a human confirmed it, whether later tasks reused it, and whether it conflicts with existing entries. sensitivity distinguishes constraints that may be injected into ordinary coding context from those viewable only locally. review_after is a lightweight TTL that prompts re-review during periodic consolidation. status ensures deletion is not physical erasure: entries are archived first, cleaned up later, and recoverable if needed. For team settings, owner and approval fields can be added; for personal local use, keep it simple.
5. Write Policy: Write Less, Write Precisely, Stay Reversible
The biggest risk in a memory system is not omission—it is overwriting. If the assistant treats every “maybe” and “let’s try” as a long-term fact, the context will drown in noise within weeks. Use three trigger tiers. Explicit triggers are strongest: when the user clearly says “always do it this way,” generate a candidate and require one confirmation. Implicit triggers are weaker: repeated corrections, stable naming preferences, or consistently passing constraint checks only enter the candidate queue. Event triggers sit in between: when tests go from red to green, a bug closes, or requirements freeze, extract “worth reviewing” fragments but do not activate them immediately.
Deduplication should normalize semantics first, then merge similar entries. Entries can be compressed into a four-tuple of “condition–action–reason–boundary,” e.g., “When retries are possible, an idempotency key must be included, because duplicate requests create financial risk—unless the upstream guarantees exactly-once.” When new evidence conflicts with an old entry, do not overwrite directly; instead, keep the old conclusion, mark it as superseded, and record why. This supports traceability and lets periodic consolidation detect preference drift. For high-risk constraints—security, money, data deletion, compatibility—require human confirmation before promoting to active. Better to be a beat slow than to let a small model harden a passing remark into a rigid rule.
6. Periodic Summarization: Compress with Local Compute, Don’t Hoard Raw Text
Periodic summarization is the core of “the more you use it, the better it knows you,” but it should be defined as lossy compression plus governance—not aggregating a running log. Run it at three timescales: a micro-summary at session end capturing only decision changes; a rolling summary daily or every few tasks, merging similar preferences; a project memory review weekly or per milestone, handling conflicts, expirations, low-frequency unreused entries, and sensitive items. In practice, let the local small model extract candidates first, apply deterministic rule filtering next, and send high-risk changes to a human for confirmation.
An executable pseudo-flow:
on_cycle_end(events, memory_store):candidates = local_extract(events, schema=MemoryCandidate)candidates = rule_filter(candidates, min_evidence=1, drop_smalltalk=true)for c in candidates:matches = find_similar(memory_store, c.statement, scope=c.scope)if conflict(c, matches):queue_human_review(c, matches)elif near_duplicate(c, matches):merge_keep_provenance(c, matches)else:memory_store.append(c, status="candidate" if c.high_risk else "active")compact(memory_store, budget_tokens=1200, protect_tags=["security", "money"])snapshot(memory_store, note="cycle-summary")
The key parameter here is a budget, not an entry count. Injecting context has a hard cost, so long-term memory must be capacity-managed like a cache: protect high-risk entries, compress low-frequency preferences, archive obsolete workflows, and retain recent pitfalls. For forgetting, use a soft policy—“lower confidence when unreused, demote when long-unconfirmed, queue for review past the review date”—rather than hard deletion on expiry, avoiding the accidental removal of critical but rarely triggered constraints.
7. The Cost Logic: Why Memory Curation Shouldn’t Run on Expensive Online Calls
The typical working pattern of such tools is “assemble context + prompt the model.” Every extraction, merge, or summary request carries the current memory snapshot, recent conversation summaries, and task instructions. Because the memory snapshot changes constantly, the prefix is nearly impossible to reuse in remote caching—the cache miss rate approaches 100%. Add high-frequency triggering, and token consumption grows linearly or worse with project activity. Using a pay-per-token, high-capability online model for background memory curation leads to a counterintuitive outcome: the curation bill exceeds the cost of the answer itself.
A more sensible division of labor: the main session model handles complex reasoning, trade-off analysis, and code generation; the local small model handles structured extraction, similarity judgment, summary compression, tagging, and first-pass risk screening. In experience, local models in the 7B–9B range are already sufficient for these narrow, constrained tasks—provided their outputs are wrapped in schema constraints, rule validation, and sampled evaluation. Do not treat the small model as an authoritative source of truth; treat it as a cheap, stable, frequently callable structured processor. Privacy stays local, latency stays controllable, and cost comes from device compute rather than a running bill.
8. Context Injection: More Memory Is Not More Intelligence
The injection layer must answer: what to give, how much, and when to give nothing. Assemble context in a fixed priority order: system and role constraints, the current task goal, a project card, long-term memories strongly related to the task, recent failures or pending verifications, and the user’s ad-hoc additions. The long-term memory portion must have a token cap, prioritizing entries related to the current file path, module name, error type, command intent, and historical preferences. Low-confidence, long-unreused, or irrelevant memories should be actively excluded.
Also design an “anti-injection” mechanism. When the user explicitly asks to ignore existing preferences, explore a refactor, or work on a one-off script, lower memory weights so past experience doesn’t suppress new approaches. Entries marked stale should appear only as warnings, not conclusions—e.g., “The old workflow required freezing the API first, but this was re-reviewed last month; confirm whether it still applies before implementing.” After injection, record which memory IDs were used, so when an answer goes wrong you can distinguish whether the cause was model reasoning failure, insufficient code context, or misleading memory.
9. Reliability, Privacy, and Evaluation
Reliability metrics should cover four categories. Quality: extraction precision/recall, conflict detection rate, merge correctness. Behavior: reduction in repeated corrections after injection, number of invalid constraint triggers, human revert rate. Cost: local curation time, injected-token share, peak memory and disk growth. Safety: rate of mistakenly stored sensitive information, out-of-scope injections, archive restore success rate. Evaluation doesn’t need to be huge—maintain a small golden set: conversation fragments labeled “should remember / should not remember / should remember but needs confirmation,” and run regression after every prompt or rule change.
For privacy, stay local-first: raw snapshots, the entry store, summaries, and audit logs all live in a local directory. Use atomic writes and snapshots to prevent half-written files; encrypt sensitive directories or at least isolate permissions; when sharing a project externally, provide a “sanitized memory export” that by default strips secrets, internal addresses, personal information, and unreleased requirements. Additional engineering details: file locks to prevent corruption from concurrent writes, per-scope directories to avoid cross-project contamination, and periodic read-only snapshots for traceability. Avoid binding the memory store to a specific toolchain—as long as it satisfies the generic abstraction of “readable files + structured metadata + local HTTP inference + scheduled tasks,” it can migrate across different assistant hosts.
10. Rollout Plan and Common Pitfalls
Roll out in three steps. Version one: explicit memory only—write only when the user says “remember,” with periodic summaries doing simple list merging; validate readability and the revert experience. Version two: add implicit candidates and local small-model extraction, but keep low-friction confirmation for all implicit entries; watch the noise rate closely. Version three: introduce automatic injection, decay, conflict queues, and an evaluation dashboard. Don’t chase full automation from day one—once a memory system becomes confidently wrong, fixing it costs more than building it.
Common pitfalls: treating raw chat text as memory, bloating the context; treating preferences as global truths and ignoring scope; using a high-capability model for frequent curation and losing control of costs; writing without deleting until the store becomes a memory graveyard; confusing model confidence with factual confidence; and neglecting audit, leaving the team unable to explain why the assistant insists on a wrong conclusion. A mature memory layer should be humble: uncertain by default, evidence traceable, changes revertible, injection budgeted, and sensitive items confirmed. With these in place, long-term memory driven by a local small model graduates from “chat history enhancement” to a stable engineering capability.
