Local Long-Term Memory Plugin for Development Environments: Four-Layer Structure and Implementation Checklist
This article presents a practical design for a local long-term memory plugin that captures, organizes, and reuses knowledge from development conversations. It defines a four-layer memory architecture (raw events, periodic summaries, structured knowledge, and index/traceability), along with configuration, model selection, injection strategy, and maintenance procedures such as sanitization, backup, review, and rollback.
1. Problem Background: Knowledge Loss in Development Sessions
During long-term development, debugging, and operations, conversations generate valuable information: architectural decisions, team coding preferences, project constraints, troubleshooting workflows, and lessons learned from past mistakes. If this information remains confined to single sessions, the next similar problem requires re-explaining context and retrying failed approaches. Conclusions from different sessions may conflict, and no one can quickly determine which rule is currently valid.
Generic chat tools do not preserve project-level memory. Exporting conversation logs retains raw text, but that text lacks structured organization and searchability. Thus, a plugin that runs inside the development environment is needed. It automatically filters content worth keeping and periodically compiles it into searchable, editable local memory documents.
This article refers to this process as dynamic long-term memory. Memory accumulates gradually during ongoing conversations, gets periodically compressed, and is injected into subsequent conversations when needed. The solution is suitable for development environments that support plugin mechanisms and can call local models.
2. Design Goals and Overall Architecture
The plugin has five design goals:
- Automatic capture: Identify conclusions, preferences, project constraints, methods, and pitfalls from conversations.
- Conversation tracking: Continuously listen to conversation events, recording timestamps, roles, and tool call results.
- Periodic summarization: Compress incremental events into summaries and structured knowledge based on time windows, message counts, or manual triggers.
- Local closed loop: Memory documents, indexes, and model inference all stay on the local machine.
- Reviewable and editable: Every memory entry can be retrieved, traced back, and corrected manually.
Three metrics help evaluate whether these goals are met:
- False extraction rate: Number of automatically extracted entries deemed incorrect by human review, divided by the total number of automatically extracted entries. The evaluation window is weekly, with at least 30 random samples reviewed per week. If fewer than 30 entries are extracted in a week, all are reviewed.
- Retrieval hit rate: Number of times a recalled memory item is adopted by the user, divided by the total number of retrieval attempts. “Adopted” means the memory was used in the current answer or decision.
- Manual correction time: Average minutes from detection to completion of a correction for each erroneous entry.
Reliable baselines do not exist initially. For the first month, only record data; do not set hard thresholds.
The overall architecture has five layers. The collection layer listens to conversation events. The memory layer handles writing and reading the four memory document layers. The summarization layer calls the local model for extraction, compression, and merging. The retrieval and injection layer recalls memory on demand for subsequent conversations. The settings interface configures the model endpoint and trigger policies and provides viewing and editing for memory entries. Pure function modules decouple these layers for easier replacement and testing.
3. Four-Layer Memory Structure
| Layer | Write Mode | Trigger | Purpose | Main Risk |
|---|---|---|---|---|
| L0 Raw Events | Append-only | Every conversation event | Evidence chain, audit, correction | Rapid volume growth, may contain sensitive content |
| L1 Periodic Summaries | Append new summaries | Time window or message threshold | Compress context, retain decisions and todos | Summaries may miss key details |
| L2 Long-Term Knowledge | Append new versions; outdated ones flagged as invalid | Summarization layer extraction + human confirmation | Primary source for injection into future conversations | Incorrect extractions used long-term |
| L3 Index and Traceability | Updated with L2 | Synchronized after write events | Retrieval; trace to original conversation | Index and documents become inconsistent |
3.1 L0 Raw Event Layer: Append-Only, No Modification
L0 stores conversation fragments, timestamps, roles, and tool call results. This layer forms the evidence chain of the entire memory system. Raw events can be stored as files organized by session or project.
For each event file, calculate a SHA-256 hash and record the hash along with a sequence number in an index file in the same directory. The hash detects accidental or unauthorized modifications, but it cannot prevent users with equal file permissions from modifying both the event file and the index simultaneously. For higher audit requirements, copy the hash manifest to a location outside the plugin directory on a regular schedule—for example, weekly.
A recovery drill should be performed quarterly, with the following pass criteria: randomly select three event files and compare their hashes against the external manifest; the comparison must pass for all. Then modify a test copy and verify that the discrepancy is reported. If the drill fails, immediately stop writes, preserve a copy of the current state, diff files one by one, restore from backup, and log the cause.
3.2 L1 Periodic Summary Layer: Retain Decisions and Pointers
L1 is triggered by a time window or message threshold. It compresses incremental L0 events into a periodic summary. The summary retains key decisions, pending items, constraint changes, and anomalies, and records the corresponding L0 event range. This limits volume growth while keeping traceable pointers.
3.3 L2 Long-Term Knowledge Layer: Version Chain Instead of Direct Deletion
L2 is a structured knowledge base with entry types including conclusions, preferences, project constraints, methods, and pitfalls. Each entry contains the following fields: content, type, confidence, source pointers (pointing to L1 and L0), creation time, update time, validity period, status, and version chain.
When a new conclusion supersedes an older one, the plugin does not delete the old entry. It appends a new version and marks the old version as invalid. The version chain thus supports rollback; the procedure is described in Section 7.
3.4 L3 Index and Traceability Layer: From Conclusions Back to Original Conversation
L3 provides three types of indexes:
- Structured index: project, type, creation time, update time, tags, status.
- Keyword index: full-text search over content and tags.
- Vector index (optional): When enabled, supports semantic similarity retrieval but requires an additional embedding model and storage space.
By default, retrieval applies filters: project matches the current workspace, status is “active,” and validity period has not expired. After filtering, entries are sorted by type weight and relevance.
The traceability path is L2 → L1 → L0. L2 entries reference the corresponding L1 summary ID, L1 summaries reference the L0 event range, and L0 files with sequence numbers locate the original conversation. Any conclusion can be traced back to its source conversation along this chain.
4. Installation, Configuration, and Minimal Verification
Prerequisites
- The development environment supports plugins and allows read/write access to a local directory.
- A local inference service is deployed and callable, for example, a service compatible with the OpenAI API format.
- The memory directory is separate from the code repository and restricted to the current user.
- Sufficient disk space is reserved. L0 volume grows with conversation activity; plan accordingly.
Configuration Items
The field names below are examples; use the actual configuration schema of your plugin.
memory:root_dir: ~/.local/share/memory-store # Memory directory, separate from code repositoryproject_key: auto # Generate project identifier from workspace pathsummarize:trigger: window # window | message_count | manualwindow_hours: 24message_threshold: 200model:endpoint: http://127.0.0.1:8000/v1 # Only localhost or internal network addresses allowedmodel_name: local-small-modeltimeout_seconds: 60max_retries: 2retrieval:token_budget: 3000vector_index: falsehash_manifest:export_dir: /secure/backup/manifests # Outside the plugin directoryinterval_days: 7
Startup and Minimal Verification
- Start the plugin and confirm that the log shows a successful model connection.
- Send three test messages in a test project, each containing a conclusion, a preference, and a constraint.
- Check whether the L0 directory contains the corresponding event files and whether the index has hashes and sequence numbers.
- Manually trigger a summary and verify that the L1 summary records the event range.
- Check L2 for automatically extracted entries; their status should be
pending_review. - After manual confirmation, the entries become
active. Start a related question and verify that the memory is injected.
Failure Troubleshooting
| Symptom | Possible Cause | Action |
|---|---|---|
| Model connection failure | Wrong endpoint, service not started, timeout too short | Use curl to directly request the model service and verify the port and path |
| Summary output unparseable | Model does not follow the JSON schema | Lower temperature, add stricter formatting instructions, or switch model |
| Write permission error | Memory directory lacks proper permissions | Check directory owner and permission bits; do not run the plugin as root |
| Hash mismatch | File modified externally or rewritten by a sync tool | Freeze writes and follow the recovery drill procedure |
5. Context Assembly and Injection
Budget Allocation
Assume token_budget is the total budget. The following proportions are examples; adjust according to actual context length:
- System rules and current task description: approximately 10%.
- L2 entries: approximately 50%, highest priority.
- L1 summaries: approximately 25%, for background.
- L0 pointers: approximately 5%, only event IDs and ranges, not raw text.
- Remaining buffer: approximately 10% to avoid exceeding the limit.
Assembly Order
- Filter by project; exclude entries that are not active or have expired.
- Sort by type weight and relevance. Project constraints outrank preferences; preferences outrank general conclusions.
- Fill with L2 entries until the budget is exhausted.
- If room remains, add L1 summaries relevant to the current task.
- Append L0 pointers for model or user traceability when needed.
Deduplication and Conflict Handling
- Deduplication: If content fingerprints are identical or semantic similarity is very high, keep only one entry—the one with the latest update time.
- Conflict: If multiple active entries exist on the same topic, do not let the model decide alone. Inject them as “needs confirmation” items and prompt the user to resolve.
- After manual confirmation, old entries are marked invalid and the conflict disappears.
Injection Template
[Project Memory | Project: {project} | Generated: {generated_at}]- Constraints ({constraint_count}):{constraints}- Preferences:{preferences}- Conclusions & Lessons:{conclusions}- Conflicts Awaiting Confirmation:{conflicts}- Source Pointers: {source_refs}The above memory may be incomplete. If it conflicts with the current user instruction, the current instruction takes precedence.
6. Choosing a Local Small Model
The summarization layer’s model handles extraction, compression, and merging. This task demands structured output stability more than creative capability.
Selection Criteria
- Context length: Must accommodate the full event window of one summary. If the window exceeds context length, split and summarize in segments.
- JSON compliance: The model must reliably output the defined schema. This is the most critical metric.
- Language handling: For Chinese content, the model must accurately preserve technical terms, project names, and negation phrasing.
- Memory footprint after quantization: The target machine still needs headroom for development tools and the operating system.
- Throughput: Tokens generated per second. Summarization runs in the background; slower speeds are acceptable, but a timeout must be set.
- Privacy: Inference must run entirely on the local machine or internal network, without depending on external APIs.
Testing Protocol
- Extract 50 real conversation segments, sanitize them, and create ground-truth annotations manually.
- Run the same sample set on each candidate model; record JSON validity rate, field-level extraction accuracy, and average time.
- Use false extraction rate as the primary reference; do not rely solely on average scores.
- Record each model’s quantization version, runtime parameters, and hardware details for reproducibility.
Candidate models should be tested in groups by parameter size and quantization method. Base the final selection on your own samples; do not directly use benchmark figures from other sources.
7. Sanitization, Backup, Human Review, and Version Rollback
Sanitization Checklist
- Before writing to L0, use regex to filter common credential formats: API keys, access tokens, password fields, and private key headers.
- Also filter phone numbers, email addresses, national IDs, and internal IP addresses.
- Use placeholders like
<API_KEY>in examples; never write real values. - After updating sanitization rules, rescan historical L0 and record the results.
- Sanitization reduces risk but does not guarantee completeness. Projects involving customer data or compliance requirements should not enable automatic memory capture.
Backup Checklist
- Perform daily incremental backups of L0 and indexes, retaining 30 days.
- Perform weekly full backups of the entire memory directory, retaining 8 weeks.
- Copy the hash manifest to a location outside the plugin directory weekly, kept separate from backups.
- Set access control on backup directories, restricting access to necessary accounts.
- Perform a recovery drill quarterly; the criteria are described in Section 3.1 (L0).
Human Review Checklist
- New L2 entries default to
pending_review; they becomeactiveonly after manual confirmation. - Project constraints and methods must be reviewed; they cannot be skipped.
- Weekly, sample false extractions, record error types, and feed them back into the extraction prompt or model selection.
- Review results are written to an audit log, including reviewer, timestamp, and modifications.
Version Rollback Procedure
- Freeze writes, pausing summarization and automatic extraction.
- Locate the target entry in L2, inspect its version chain, and determine the version to restore.
- Set the target version to
activeand the current version toinvalid. Do not delete any version. - Rebuild relevant indexes and run a retrieval test to confirm results are as expected.
- Record the rollback reason, operator, and time.
- Resume writes.
Risk Notes
- Rollback only restores recorded versions. If there are unbacked-up changes after the rollback point, those changes cannot be recovered through the version chain.
- Users with equal file permissions can modify both L0 and the index; hashes cannot prevent this.
- Incorrectly extracted constraints may influence model responses and code decisions if injected into later conversations. Human review is the last line of defense.
- If backup directory permissions are too broad, sensitive content from past conversations can leak along with backups.
- Version chains grow over time. Periodically archive old versions past their validity periods, but confirm that no L1 pointers still reference them before archiving.
8. Trial Recommendations
Enable the plugin in a non-critical project first. Run it for two weeks, recording only the three metrics without applying thresholds. During the trial, follow the review and backup procedures in Section 7. After two weeks, decide whether to expand usage based on the false extraction rate and correction time.
