Clean up and enhance memory plugin (#151)

* refactor storage to use worker-based vector operations

* update memory service and agent implementations

* update opencode plugin sdk

* update memory plugin documentation

* add tests for memory service and injection hook

* update lockfile for dependency changes

* Add memory plugin v0.0.13 with message deduplication and config UI

* Remove planning state feature from memory plugin
This commit is contained in:
Chris Scott authored and GitHub committed 2026-03-06 20:24:52 -05:00
1 parent 47ef830cbb
commit 6ef68774d8
53 files changed
+1683 -1885

No files matched your search

+90 -113
View File
@@ -50,17 +50,25 @@ The file is only created if it does not already exist. The config is validated o
"baseUrl": "",
"apiKey": ""
},
"dataDir": "~/.local/share/opencode/memory",
"dedupThreshold": 0.25,
"logging": {
"enabled": false,
"file": "~/.local/share/opencode/memory/logs/memory.log"
"debug": false,
"file": ""
},
"compaction": {
"customPrompt": true,
"inlinePlanning": true,
"maxContextTokens": 4000,
"snapshotToKV": true
"maxContextTokens": 4000
},
"memoryInjection": {
"enabled": true,
"debug": false,
"maxTokens": 2000,
"cacheTtlMs": 30000
},
"messagesTransform": {
"enabled": true,
"debug": false
},
"executionModel": ""
}
@@ -98,14 +106,20 @@ Set `baseUrl` to point at any OpenAI-compatible self-hosted service (vLLM, Ollam
| `embedding.apiKey` | API key for OpenAI/Voyage | — |
| `embedding.baseUrl` | Custom endpoint for self-hosted services | — |
| `embedding.serverGracePeriod` | Time (ms) before idle embedding server shuts down | `30000` |
| `dataDir` | SQLite database and embedding server directory | `~/.local/share/opencode/memory` |
| `dedupThreshold` | Similarity threshold for deduplication (0.05–0.40) | `0.25` |
| `logging.enabled` | Write logs to file | `false` |
| `logging.file` | Log file path (10MB limit, auto-rotated) | `…/logs/memory.log` |
| `logging.debug` | Enable debug-level log output | `false` |
| `logging.file` | Log file path (resolves to `~/.local/share/opencode/memory/logs/memory.log` when empty, 10MB limit, auto-rotated) | — |
| `compaction.customPrompt` | Use optimized compaction prompt for session continuity | `true` |
| `compaction.inlinePlanning` | Include planning state in compaction context | `true` |
| `compaction.maxContextTokens` | Max tokens for injected memory context | `4000` |
| `compaction.snapshotToKV` | Save pre-compaction snapshot for recovery | `true` |
| `memoryInjection.enabled` | Inject relevant memories into user messages via semantic search | `true` |
| `memoryInjection.debug` | Enable debug logging for memory injection | `false` |
| `memoryInjection.maxResults` | Max vector search results to retrieve | `5` |
| `memoryInjection.distanceThreshold` | Max vector distance for relevance filtering (lower = stricter) | `0.5` |
| `memoryInjection.maxTokens` | Token budget for injected `<project-memory>` block | `2000` |
| `memoryInjection.cacheTtlMs` | Cache TTL (ms) for identical query results | `30000` |
| `messagesTransform.enabled` | Enable the messages transform hook (memory injection + Architect enforcement) | `true` |
| `messagesTransform.debug` | Enable debug logging for messages transform | `false` |
| `executionModel` | Model override for plan execution sessions (`provider/model`). Falls back to OpenCode's default model. | — |
---
@@ -126,7 +140,7 @@ The plugin is composed of several subsystems that work together:
│ Service │ (sqlite-vec) │ (In-Memory) │
├──────────────┴────────────────┴───────────────────┤
│ SQLite Database (WAL) │
│ memories | session_state | metadata │
│ memories | metadata │
└──────────────────────────────────────────────────┘
```
@@ -137,7 +151,6 @@ The plugin uses a single SQLite database in WAL mode with three tables:
| Table | Purpose |
|-------|---------|
| `memories` | Stores all memory records with scope, content, access tracking |
| `session_state` | Key-value store for planning state and compaction snapshots with TTL |
| `plugin_metadata` | Tracks the active embedding model and dimensions for drift detection |
SQLite pragmas are tuned for concurrent access:
@@ -316,42 +329,6 @@ Check plugin health or trigger a reindex of all embeddings.
!!! warning "Model Changes Require Reindex"
If you change `embedding.model` or `embedding.dimensions`, existing embeddings will have mismatched dimensions. Auto-validation handles this on startup, but you can also trigger it manually with `memory-health reindex`.
### memory-planning-update
Update the session planning state. Uses merge semantics — only updates fields you provide.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `sessionID` | string | No | Session ID to update. Defaults to the current session if omitted. |
| `objective` | string | No | The main task/goal |
| `current` | string | No | Current phase or activity |
| `next` | string | No | What comes next |
| `phases` | array | No | Phase list: `[{title, status, notes?}]` |
| `findings` | array | No | Key discoveries (appended, deduplicated) |
| `errors` | array | No | Errors to avoid (appended, deduplicated) |
Findings and errors use append semantics with deduplication — new entries are added to existing ones rather than replacing them.
### memory-planning-get
Retrieve the current planning state for a session.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `sessionID` | string | No | Session ID to retrieve. Defaults to the current session if omitted. |
Returns a formatted view of the planning state including objective, current phase, phases with status icons (`[x]` completed, `[~]` in progress, `[ ]` pending), findings, and errors.
### memory-planning-search
Search planning states across all sessions in the current project. Useful for finding context from prior planning sessions.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | No | Keyword to filter planning states. Omit to list all sessions. |
Returns a summary of matching sessions showing session ID, last updated date, objective, current phase, and phase completion progress. Results are ordered by most recently updated.
### memory-plan-execute
Create a new Code session and send an implementation plan as the first prompt. Designed to be called by the Architect agent after the user approves a plan.
@@ -360,29 +337,47 @@ Create a new Code session and send an implementation plan as the first prompt. D
|-----------|------|----------|-------------|
| `plan` | string | Yes | The full implementation plan to send to the Code agent |
| `title` | string | Yes | Short title for the session (shown in session list, max 60 chars) |
| `objective` | string | No | Short description of what we're building |
| `phases` | array | No | Phase list from the plan: `[{title, status, notes?}]` |
| `findings` | array | No | Key architectural decisions discovered during research |
Saves planning state (objective, phases, findings) for the Architect session, creates a new session via the OpenCode API, then sends the plan as the first message to the Code agent. Returns the session ID and title. Only the Architect agent has access to this tool — it is excluded from Code and Memory agents.
Creates a new session via the OpenCode API and sends the plan as the first message to the Code agent. Returns the session ID and title. Only the Architect agent has access to this tool — it is excluded from Code and Memory agents.
The model used for the new Code session is determined by `executionModel` in the plugin config (format: `provider/model`, e.g. `anthropic/claude-sonnet-4-20250514`). If not set, OpenCode's default model resolution is used — typically the `model` field from `opencode.json`.
---
## Planning State
## Workflows
Planning state is separate from memories. It tracks temporary session progress — objectives, phase completion, findings, and blockers.
### Architect → Code
| Property | Memories | Planning State |
|----------|----------|----------------|
| Persistence | Indefinite | 7-day TTL |
| Scope | Cross-session, semantic search | Project-scoped, searchable across sessions |
| Purpose | Durable project knowledge | Task progress tracking |
| Cleanup | Manual (delete/archive) | Automatic (expired entries removed every 30 minutes) |
| Compaction snapshot TTL | N/A | 24 hours |
The Architect and Code agents work together in a plan-then-execute pattern. The Architect researches and designs; the Code agent implements.
The plugin injects active planning state into compaction context so task progress survives context window resets. After compaction, the Memory agent extracts any durable knowledge from the compaction summary and stores it as memories. Planning states are project-scoped and searchable across sessions using `memory-planning-search`.
**Steps:**
1. **Switch to the Architect agent** using the agent selector in the chat header
2. **Describe your task** — the Architect researches the codebase, checks memory for conventions and decisions, and designs a plan
3. **Review the plan** — the Architect presents a structured plan with objectives, phases, and decisions for your approval
4. **Approve the plan** — the Architect calls `memory-plan-execute`, which creates a new Code session and sends the full plan as context
5. **Switch to the new session** — the Code agent executes the plan phase by phase
The Architect operates in read-only mode — it cannot edit files. This separation ensures planning is thorough before any code changes are made.
#### Recommended Model Strategy
Planning requires strong reasoning — use a smart model (e.g., `claude-opus-4-6`) for the Architect session. Code execution is more mechanical — set `executionModel` to a faster, cheaper model (e.g., `claude-haiku-3-5-20241022` or a MiniMax model).
This gives you the best of both worlds: high-quality plans at the reasoning tier, fast execution at a fraction of the cost.
**Configure the execution model** in the memory plugin config (`~/.local/share/opencode/memory/config.json`):
```json
{
"executionModel": "anthropic/claude-haiku-3-5-20241022"
}
```
Or set it from the UI: **Settings > Memory Plugin > Execution Model**.
!!! tip "Cost Optimization"
With this setup, only the planning phase uses the expensive model. The Code session — which typically consumes far more tokens implementing the plan — runs on the cheaper model. The Architect's plan provides enough structure and detail that the Code agent doesn't need the same level of reasoning capability.
---
@@ -404,10 +399,6 @@ The Code agent's system prompt instructs it to:
- Check for duplicates with `memory-read` before writing new memories
- Update stale memories with `memory-edit` rather than creating duplicates
Code and Architect agents do not have direct access to `memory-planning-update` or `memory-planning-search` — these tools are exclusive to the Memory subagent. To update planning state or search across sessions, the Code agent delegates to @Memory via the Task tool.
The Code agent does not have access to `memory-plan-execute`, `memory-planning-update`, or `memory-planning-search`. It delegates planning operations to the @Memory subagent and can only read its own session's planning state via `memory-planning-get`.
### Memory Agent (subagent)
- **Display name:** `Memory`
@@ -420,13 +411,7 @@ The Memory agent handles:
- Storage with proper scope categorization and rationale
- Contradiction detection between overlapping memories
- Curation: merging duplicates, archiving outdated entries
- Planning state management after compaction events
- Post-compaction knowledge extraction (invoked automatically via SubtaskPart)
- Planning state management: updating phase progress, searching plans across sessions (exclusive access to `memory-planning-update` and `memory-planning-search`)
The Memory agent receives planning state directly in its subtask prompt — it does NOT call `memory-planning-get`. This eliminates an extra LLM round-trip and makes extraction deterministic.
The Memory agent has access to `memory-planning-search` for cross-session planning context lookup. It does not have access to `memory-plan-execute`.
### Architect Agent (primary)
@@ -441,14 +426,10 @@ The Architect agent follows a Research → Design → Plan → Execute workflow:
1. **Research** — Reads relevant files, searches the codebase, checks memory for conventions and decisions
2. **Design** — Considers approaches, weighs tradeoffs, asks clarifying questions
3. **Plan** — Presents a structured plan with objectives, phases, decisions, conventions, and key context
4. **Execute** — When the user approves, calls `memory-plan-execute` with the plan, objective, phases, and findings. Planning state is saved automatically before the plan is dispatched to the Code agent.
4. **Execute** — When the user approves, calls `memory-plan-execute` with the plan and title.
The Architect is the only agent with access to the `memory-plan-execute` tool. Plans must be fully self-contained since the Code agent receiving them has no access to the Architect's conversation.
When `memory-plan-execute` runs, it automatically appends a planning instruction to the plan telling the Code agent to update the Architect session's planning state as it progresses through phases. It also updates the Architect session's planning state to reflect that the plan has been dispatched.
The Architect agent does not have direct access to `memory-planning-update` or `memory-planning-search`. It delegates broad memory research to the @Memory subagent and reads its own session's planning state via `memory-planning-get`.
### Code Review Agent (subagent)
- **Display name:** `Code Review`
@@ -458,7 +439,7 @@ The Architect agent does not have direct access to `memory-planning-update` or `
The Code Review agent is a read-only subagent invoked by other agents via the Task tool to review diffs, commits, branches, or PRs. It checks changes against stored project conventions and decisions, then returns a structured review summary with issues (bug/warning/suggestion) and observations.
The agent can read memory (`memory-read`) and planning state (`memory-planning-get`, `memory-planning-search`, `memory-planning-update`) but cannot write, edit, or delete memories. It also cannot execute plans — `memory-plan-execute`, `memory-write`, `memory-edit`, and `memory-delete` are excluded.
The agent can read memory (`memory-read`) but cannot write, edit, or delete memories. It also cannot execute plans — `memory-plan-execute`, `memory-write`, `memory-edit`, and `memory-delete` are excluded.
The `/review` slash command triggers this agent as a subtask with the template: "Review the current code changes."
@@ -468,7 +449,7 @@ The plugin also modifies built-in OpenCode agents:
| Agent | Enhancement |
|-------|-------------|
| `plan` | Gets access to `memory-read`, `memory-planning-update`, `memory-planning-get`, and `memory-planning-search` tools |
| `plan` | Gets access to `memory-read` tool |
| `build` | Hidden (replaced by the Code agent) |
The default agent is set to `Code`.
@@ -493,37 +474,43 @@ The plugin registers several hooks into OpenCode's lifecycle:
Listens for `session.compacted` events and triggers automatic knowledge extraction:
1. Fetches the last 4 messages from the session to get the compaction summary
2. Retrieves planning state directly from session state service
3. Sends a synchronous prompt() call with a SubtaskPart to run the Memory agent
4. Memory agent receives planning state directly in the subtask prompt (no memory-planning-get call needed)
5. Extraction runs within the main session's prompt loop, keeping session busy
2. Sends a synchronous prompt() call with a SubtaskPart to run the Memory agent
3. Extraction runs within the main session's prompt loop, keeping session busy
### experimental.session.compacting
The core compaction hook that fires when a session is about to be compacted. It injects context to preserve knowledge across context window resets:
1. **Planning state** — If `inlinePlanning` is enabled, fetches and formats the current session's planning state (objective, phases, findings, errors)
1. **Project memories** — Fetches up to 10 conventions and 10 decisions for the project and formats them under `### Conventions` and `### Decisions` headings
2. **Prior compaction snapshot** — If `snapshotToKV` is enabled, retrieves the previous compaction's snapshot for continuity (timestamp, branch, prior planning state)
2. **Token budgeting** — All sections are trimmed to fit within `maxContextTokens` (default 4000). Lower-priority sections are truncated first.
3. **Project memories** — Fetches up to 10 conventions and 10 decisions for the project and formats them under `### Conventions` and `### Decisions` headings
3. **Custom prompt** — If `customPrompt` is enabled, replaces the default compaction prompt with one optimized for continuation context that preserves active tasks, file paths, decisions, and todo state
4. **Token budgeting** — All sections are trimmed to fit within `maxContextTokens` (default 4000). Sections are prioritized: planning state > prior snapshot > memories. Lower-priority sections are truncated first.
5. **Custom prompt** — If `customPrompt` is enabled, replaces the default compaction prompt with one optimized for continuation context that preserves active tasks, file paths, decisions, and todo state
6. **Snapshot storage** — Saves a pre-compaction snapshot (planning state, branch, timestamp) to session state for the next compaction cycle
7. **Diagnostics** — Appends a summary line showing how many planning phases, conventions, decisions, and tokens were injected
4. **Diagnostics** — Appends a summary line showing how many conventions, decisions, and tokens were injected
### experimental.chat.messages.transform
Injects a read-only enforcement reminder into user messages when the Architect agent is active:
Performs two functions on the message array before each LLM inference call:
1. Scans messages to find the last user message
2. If the message is addressed to the Architect agent, appends a synthetic `<system-reminder>` part
3. The reminder instructs the agent that plan mode is active and it must not make file edits or run non-readonly tools
4. This provides message-level enforcement on top of the agent's `edit: { '*': 'deny' }` permission config
**Memory Injection** (all agents):
1. Finds the last user message in the message array
2. Extracts all text parts and runs a semantic vector search against stored project memories
3. Filters results by `distanceThreshold` — only memories with distance below the threshold are kept
4. Formats matching memories into a `<project-memory>` block with scope labels (e.g., `[convention]`, `[decision]`)
5. Trims the block to fit within `maxTokens` and appends it as a synthetic text part to the user message
6. Uses SHA-256 content-hash caching (`cacheTtlMs`, default 30s) to avoid redundant vector searches across inference steps
The hook fires on every LLM inference step (including tool-use follow-ups), but since OpenCode re-reads messages from the database each iteration, synthetic parts are ephemeral. The cache ensures the vector search only runs once per unique user message within the TTL window.
Memory injection is controlled independently by `memoryInjection.enabled` (default `true`). Architect read-only enforcement is controlled by `messagesTransform.enabled` (default `true`).
**Architect Read-Only Enforcement** (Architect agent only):
1. Checks if the last user message is addressed to the Architect agent
2. If so, appends a synthetic `<system-reminder>` part enforcing read-only mode
3. This provides message-level enforcement on top of the agent's `edit: { '*': 'deny' }` permission config
---
@@ -536,9 +523,7 @@ Injects a read-only enforcement reminder into user messages when the Architect a
3. Warmup embedding provider (non-blocking)
4. Initialize SQLite database with WAL mode
5. Create memory service with no-op vec service
6. Start session state cleanup interval (every 30 min)
7. Delete expired session state entries
8. Initialize vec service asynchronously:
6. Initialize vec service asynchronously:
- If available: sync missing embeddings, auto-validate model drift
- If unavailable: continue with no-op (semantic search degraded)
@@ -549,8 +534,7 @@ On process exit, `SIGINT`, or `SIGTERM`:
1. Dispose vec service
2. Destroy in-memory cache
3. Dispose embedding provider (disconnect from shared server or release model)
4. Stop session state cleanup interval
5. Close SQLite database
4. Close SQLite database
The cleanup function is idempotent — calling it multiple times is safe.
@@ -558,7 +542,7 @@ The cleanup function is idempotent — calling it multiple times is safe.
| File | Location | Purpose |
|------|----------|---------|
| `memory.db` | `{dataDir}/` | SQLite database with all memories and session state |
| `memory.db` | `{dataDir}/` | SQLite database with all memories |
| `config.json` | `{dataDir}/` | Plugin configuration |
| `embedding.sock` | `{dataDir}/` | Unix socket for shared embedding server |
| `embedding.pid` | `{dataDir}/` | PID file for the embedding server process |
@@ -591,9 +575,9 @@ ocm-mem <command> [options]
|---------|-------------|
| `export` | Export memories to file (JSON or Markdown) |
| `import` | Import memories from file |
| `list` | List projects with memory and session state counts |
| `list` | List projects with memory counts |
| `stats` | Show memory statistics for a project |
| `cleanup` | Delete memories or session states by criteria |
| `cleanup` | Delete memories by criteria |
### Usage Examples
@@ -621,9 +605,6 @@ ocm-mem cleanup --older-than 90 --dry-run
# Delete specific memories
ocm-mem cleanup --ids 1,2,3 --force
# Clean up expired session states
ocm-mem cleanup --sessions --older-than 30
```
Run `ocm-mem <command> --help` for full options on each command.
@@ -649,10 +630,6 @@ The embedding provider is not operational. For local embeddings, the model may n
- Check if the socket file exists but the process is dead: `rm ~/.local/share/opencode/memory/embedding.sock`
- Verify Bun is installed and available on PATH
### Planning state not persisting
Planning state has a 7-day TTL. If the session is older than 7 days, the state has been automatically cleaned up. Compaction snapshots have a shorter 24-hour TTL.
### Memory not injected during compaction
Check that `compaction.customPrompt` and `compaction.inlinePlanning` are both `true` in your config. Verify that memories exist for the project by running `memory-read` without filters.
Check that `compaction.customPrompt` is `true` in your config. Verify that memories exist for the project by running `memory-read` without filters.
+2 -2
View File
@@ -55,9 +55,9 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
- **Semantic Search** - Store and retrieve project knowledge using vector embeddings (requires plugin installation)
- **Memory Scopes** - Categorize as convention, decision, or context
- **Planning State** - Track objectives, phases, and progress across compactions
- **Automatic Extraction** - Durable knowledge extracted after session compaction
- **Compaction Awareness** - Injects project memories and planning state into compaction context
- **Compaction Awareness** - Injects project memories into compaction context
- **Architect → Code** - Plan with a smart model, execute with a fast model for cost-optimized workflows
[Learn more →](memory.md)
+1 -1
View File
@@ -34,7 +34,7 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing
- **Push Notifications** - Get background alerts for agent events when app is closed
- **AI Configuration** - Configure models, providers, OAuth, and custom agents
- **MCP Servers** - Add local or remote MCP servers with OAuth support
- **Memory Plugin (Optional)** - Persistent project knowledge with semantic search and planning state
- **Memory Plugin (Optional)** - Persistent project knowledge with semantic search
!!! tip "Memory Plugin — Persistent Project Knowledge"
Store and retrieve project knowledge across sessions using vector embeddings and semantic search. Works as a standalone plugin with any OpenCode installation.