Local-First Long-Term Memory for AI Agents: Plugin Design and Practice
This article presents a fully local approach to giving AI agents persistent long-term memory through a plugin. It explains why single-session agents forget context across sessions, introduces a "kinetic memory" model that continuously collects, aggregates, and refines signals, and details a four-layer memory structure (raw logs, session summaries, topic memory, and index/profile). It covers memorability scoring, deduplication and merge pipelines, periodic summarization with local small models, multi-route retrieval with token-budget trimming, plugin installation steps, and privacy, security, and operations practices, along with current limitations and future directions.
1. Background: Why Agents Need “Kinetic Memory”
LLM-powered agents perform well within a single session but effectively lose memory across sessions. Users have to repeatedly restate project constraints, coding style preferences, and conclusions from past mistakes, so interaction cost grows linearly with usage. Common industry workarounds fall into two categories: replaying the full conversation history back into the context, or relying on a cloud-hosted memory service. The former is limited by context window size and cost; the latter introduces data-egress and compliance pressure.
“Kinetic memory” refers to a continuously running memory mechanism that periodically organizes itself. Rather than a static archive written once, it works like a kinetic system: it collects signals on every interaction, aggregates them on a cycle, discards noise, and reinforces high-frequency conclusions, keeping memory concise and traceable. This article takes a local agent host environment (a local agent runtime platform with plugin support and high customizability) as its setting and describes a fully local implementation.
2. Design Principles: Local-First, Controllable, and Auditable
- Local storage first: Memory is persisted to local disk as plain text or structured documents that users can open, edit, and delete at any time, avoiding a black box.
- Local model for summarization: Periodic induction is handled by a locally loaded small model in the 7B–9B range, requiring no network access and no pay-per-use billing pressure.
- Context assembly instead of full replay: Each turn injects only the memory fragments relevant to the current task, keeping token size under control.
- Layering and traceability: Every memory entry can answer “where it came from, when it was updated, and who referenced it.”
- Pluggable: Memory capability is mounted as a plugin, enabled declaratively through configuration, and can be disabled with one action when absent, without affecting the host runtime.
A note on cost is warranted here: this type of plugin works by “assembling context + prompting the model to process it,” carrying the current memory fragments on every turn, which yields a very low prefix cache hit rate. With a pay-per-use cloud LLM, costs accumulate quickly; local small-model inference has near-zero marginal cost, making it the more economical choice.
3. The Four-Layer Memory Structure
Borrowing the human memory hierarchy of “sensory–short-term–long-term,” memory can be organized into four layers, each traceable to the one below:
| Layer | Content | Lifecycle | Storage Form |
|---|---|---|---|
| L0 Raw stream | Complete session messages | Days | Append-only log |
| L1 Session summary | Key points per turn/session | Weeks | One file per session |
| L2 Topic memory | Conclusions, preferences, constraints, methods | Long-term | Topic-based documents |
| L3 Index and profile | Keyword index, user profile | Long-term | Lightweight index files |
L0 guarantees traceability; L1 is the first compression gate; L2 is the part that truly “understands you,” and it is recommended to split it into four topic categories: project constraints, coding preferences, process methods, and lessons from pitfalls; L3 stores only references and statistics pointing to L2, avoiding redundant growth.
A sample L2 entry structure:
id: mem-0421type: constraint # conclusion | preference | constraint | method | pitfalltopic: build-pipelinetext: Build scripts must remain idempotent; repeated runs must produce no side effectssource: session-2026-08-11T09:22confidence: 0.86hit_count: 7updated_at: 2026-08-27
4. Collection and Writing: What Is Worth Remembering
Not everything should enter memory. It is recommended to define “memorability” rules and have the local small model score candidate fragments:
- Conclusion-type: root causes confirmed after debugging, final decisions on trade-offs;
- Preference-type: naming style, directory structure, comment density, commit message format;
- Constraint-type: tech stack boundaries, dependency version pinning, compliance and security requirements;
- Method-type: reusable troubleshooting steps and verification procedures;
- Lesson-type: pitfalls encountered and their trigger conditions.
Chit-chat, temporary data, and one-off output that score below the threshold are discarded outright. Writing follows a three-step “deduplicate–merge–update” process: first retrieve existing entries by semantic similarity; on a hit, update hit_count and updated_at; only on a miss is a new entry created, preventing the buildup of synonymous entries.
// Pseudocode: write pipelineasync function ingest(fragment, ctx) {const score = await localModel.scoreMemorability(fragment);if (score < 0.6) return null;const near = await index.search(fragment, { topK: 3, threshold: 0.82 });if (near.length) return merge(near[0], fragment);return createEntry(fragment, ctx.sessionId);}
5. Periodic Summarization: Making Memory More Refined Over Time
Periodic summarization is the core of kinetic memory. A dual trigger is recommended: session end triggers L0→L1 compression; a fixed cycle (such as daily or every N interactions) triggers L1→L2 distillation. The summarization prompt should constrain the model to do only three things: extract key points, classify them into the four topic categories, and flag conflicts.
Conflict handling strategy: when mutually exclusive conclusions appear under the same topic, do not overwrite but keep both and record time and source, letting confidence and hit count decide injection priority; when the user explicitly corrects something, directly lower the old entry’s confidence.
6. Retrieval and Context Assembly
The injection strategy determines both effectiveness and overhead. The recommended approach is “three-route recall + rerank + budget trimming”:
- Keyword recall (L3 index, millisecond-level);
- Vector recall (local embedding model, optional);
- Profile recall (strong-constraint entries for the current project/language/module are always included).
After merging, rerank by confidence × hit_count, truncate within a fixed token budget, and annotate each entry’s source in the prompt so the model can distinguish “long-term constraints” from “temporary information.”
7. Installation and Activation (Generalized Description)
Taking a local agent host with a plugin mechanism as an example, the process can be abstracted into four steps:
- Obtain the plugin files (core plugin script, settings UI sub-plugin, and pure-function module directory);
- Place them in the host profile’s plugin directory, and create a package link or copy as a dependency package for the settings UI;
- Register the plugin id and entry path in the profile’s declarative patch configuration:
- insert:- id: agent-memoryname: ./plugins/agent-memory.js- id: mm-settingsname: mm-settings
- Restart the host, and the memory tools and settings panel take effect.
If using an agent with code execution capability, it can also complete the deployment itself following the steps above, but manual review of configuration items and directory permissions is recommended.
8. Privacy, Security, and Operations
- Data boundary: fully local across the chain, with no data egress; for backups, use user-chosen local or private storage.
- Deletability: provide cleanup interfaces by topic, by time, and by entry, supporting “one-click forgetting.”
- Sensitive information: apply regex and rule-based filtering before writing to mask keys, tokens, and personal information.
- Observability: log write/eviction/hit events to facilitate threshold tuning.
- Version management: bring memory documents under version control so they can be diffed and rolled back.
9. Limitations and Future Directions
The initial version typically has three shortcomings: semantic deduplication relies on simple similarity, leading to topic drift after long-term accumulation; the summarization prompt is sensitive to model capability, and small models may miss key points; and there is no cross-device sync or permission model. Future work could introduce a local embedding model to improve recall, add a memory decay function, provide a memory graph view, and explore end-to-end encrypted sync while preserving the local-first principle.
Overall, kinetic memory offers a low-cost, privacy-friendly path to long-term memory for AI agents: the layered structure guarantees traceability, periodic summarization guarantees refinement, and the local small model guarantees economy. For developers who want to “make tools understand them better over time,” this is an engineering practice worth continuously refining starting from a minimum viable version.
