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

+19
View File
@@ -5,6 +5,25 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.0.12] - 2026-03-05
### Added
- `experimental.chat.messages.transform` hook: automatically injects project conventions and decisions into system prompts for every LLM call, with configurable token budget and caching
- Skill tool awareness in Code and Architect agent prompts
- `plan_enter` permission on Code agent for switching to Architect mode
- `memory-edit` documentation in Memory agent's tool list
- Agent name logging in all tool handlers via new ToolContext.agent field
### Changed
- Upgraded `@opencode-ai/plugin` from ^1.2.9 to ^1.2.16
- Renamed deprecated `maxSteps` to `steps` in AgentDefinition and AgentConfig types
### Fixed
- Memory agent tool documentation now lists all 7 available tools (was missing memory-edit)
## [0.0.9] - 2026-02-27
### Added
+94 -59
View File
@@ -1,17 +1,56 @@
# @opencode-manager/memory
<h1 align="center">@opencode-manager/memory</h1>
Memory management plugin for OpenCode that enables semantic search and persistent storage of project knowledge.
<p align="center">
<strong>Semantic memory and planning plugin for <a href="https://opencode.ai">OpenCode</a> AI agents</strong>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/@opencode-manager/memory"><img src="https://img.shields.io/npm/v/@opencode-manager/memory" alt="npm" /></a>
<a href="https://www.npmjs.com/package/@opencode-manager/memory"><img src="https://img.shields.io/npm/dm/@opencode-manager/memory" alt="npm downloads" /></a>
<a href="https://github.com/chriswritescode-dev/opencode-manager/blob/main/LICENSE"><img src="https://img.shields.io/github/license/chriswritescode-dev/opencode-manager" alt="License" /></a>
</p>
## Quick Start
```bash
pnpm add @opencode-manager/memory
```
Add to your `opencode.json`:
```json
{
"plugin": ["@opencode-manager/memory"]
}
```
The local embedding model downloads automatically on install. For API-based embeddings (OpenAI or Voyage), see [Configuration](#configuration).
## Features
- **Semantic Memory Search** - Store and retrieve project memories using vector embeddings
- **Multiple Memory Scopes** - Categorize memories as convention, decision, or context
- **Automatic Deduplication** - Prevents duplicates via exact match and semantic similarity detection
- **Compaction Context Injection** - Injects planning state, conventions, and decisions into session compaction for seamless continuity
- **Compaction Context Injection** - Injects conventions and decisions into session compaction for seamless continuity
- **Automatic Memory Injection** - Injects relevant project memories into user messages via semantic search with distance filtering and caching
- **Bundled Agents** - Ships with Code, Architect, and Memory agents preconfigured for memory-aware workflows
- **CLI Tools** - Export, import, list, stats, and cleanup commands via `ocm-mem` binary
- **Dimension Mismatch Detection** - Detects embedding model changes and guides recovery via reindex
- **Session Planning** - Tracks objectives, phases, findings, and errors across sessions with automatic TTL cleanup
## Agents
The plugin bundles four agents that integrate with the memory system:
| Agent | ID | Mode | Description |
|-------|----|------|-------------|
| **Code** | `ocm-code` | primary | Primary coding agent with memory awareness. Checks memory before unfamiliar code, stores architectural decisions and conventions as it works. Delegates planning operations to @Memory subagent. |
| **Architect** | `ocm-architect` | primary | Read-only planning agent. Researches the codebase, delegates to @Memory for broad knowledge retrieval, designs implementation plans, then hands off to Code via `memory-plan-execute`. |
| **Memory** | `ocm-memory` | subagent | Expert agent for managing project memory. Handles post-compaction memory extraction and contradiction resolution. |
| **Code Review** | `ocm-code-review` | subagent | Read-only code reviewer with access to project memory for convention-aware reviews. Invoked via Task tool to review diffs, commits, branches, or PRs against stored conventions and decisions. |
The Code Review agent is a read-only subagent (`temperature: 0.0`) that can read memory but cannot write, edit, or delete memories or execute plans. It is invoked by other agents via the Task tool to review code changes against stored project conventions and decisions.
The Architect agent operates in read-only mode (`temperature: 0.0`, all edits denied) with additional message-level read-only enforcement via the `experimental.chat.messages.transform` hook. After the user approves a plan, it calls `memory-plan-execute` which creates a new Code session with the full plan as context.
## Tools
@@ -22,26 +61,7 @@ Memory management plugin for OpenCode that enables semantic search and persisten
| `memory-edit` | Update an existing project memory |
| `memory-delete` | Delete a project memory by ID |
| `memory-health` | Health check or full reindex of the memory store |
| `memory-planning-update` | Update session planning state (phases, objectives, progress) |
| `memory-planning-get` | Get the current planning state for a session |
| `memory-plan-execute` | Create a new Code session, save planning state, and send an approved plan as the first prompt |
Planning state differs from memories: it stores temporary session data (objectives, phase progress, findings, errors) with a 7-day TTL, while memories are persisted indefinitely and retrieved via semantic search.
## Agents
The plugin bundles four agents that integrate with the memory system:
| Agent | ID | Mode | Description |
|-------|----|------|-------------|
| **Code** | `ocm-code` | primary | Primary coding agent with memory awareness. Checks memory before unfamiliar code, stores architectural decisions and conventions as it works. Delegates planning operations to @Memory subagent. |
| **Architect** | `ocm-architect` | primary | Read-only planning agent. Researches the codebase, delegates to @Memory for broad knowledge retrieval, designs implementation plans, then hands off to Code via `memory-plan-execute`. |
| **Memory** | `ocm-memory` | subagent | Expert agent for managing project memory and planning state. Handles post-compaction memory extraction, contradiction resolution, planning state updates, and cross-session plan searches. |
| **Code Review** | `ocm-code-review` | subagent | Read-only code reviewer with access to project memory for convention-aware reviews. Invoked via Task tool to review diffs, commits, branches, or PRs against stored conventions and decisions. |
The Code Review agent is a read-only subagent (`temperature: 0.0`) that can read memory but cannot write, edit, or delete memories or execute plans. It is invoked by other agents via the Task tool to review code changes against stored project conventions and decisions.
The Architect agent operates in read-only mode (`temperature: 0.0`, all edits denied) with additional message-level read-only enforcement via the `experimental.chat.messages.transform` hook. After the user approves a plan, it calls `memory-plan-execute` which saves planning state and creates a new Code session with the full plan as context. Code and Architect agents delegate `memory-planning-update` and `memory-planning-search` to the Memory subagent.
| `memory-plan-execute` | Create a new Code session and send an approved plan as the first prompt |
## CLI
@@ -96,7 +116,7 @@ ocm-mem import memories.md --project my-project --force
#### list
List all projects with memory and session state counts.
List all projects with memory counts.
```bash
ocm-mem list
@@ -104,7 +124,7 @@ ocm-mem list
#### stats
Show memory statistics for a project (scope breakdown, session state counts).
Show memory statistics for a project (scope breakdown).
```bash
ocm-mem stats
@@ -113,13 +133,12 @@ ocm-mem stats --project my-project
#### cleanup
Delete memories or session states by criteria.
Delete memories by criteria.
```bash
ocm-mem cleanup --older-than 90
ocm-mem cleanup --ids 1,2,3 --force
ocm-mem cleanup --scope context --dry-run
ocm-mem cleanup --sessions --older-than 30
ocm-mem cleanup --all --project my-project
```
@@ -128,31 +147,10 @@ ocm-mem cleanup --all --project my-project
| `--older-than <days>` | Delete memories older than N days |
| `--ids <id,id,...>` | Delete specific memory IDs |
| `--scope <scope>` | Filter by scope: `convention`, `decision`, or `context` |
| `--sessions` | Clean up session states instead of memories |
| `--all` | Delete all memories for the project |
| `--dry-run` | Preview what would be deleted without deleting |
| `--force` | Skip confirmation prompt |
## Installation
Install the package from npm:
```bash
npm install @opencode-manager/memory
# or
pnpm add @opencode-manager/memory
```
During installation, the local embedding model (`all-MiniLM-L6-v2`) is downloaded automatically via the `postinstall` script. For API-based embeddings (OpenAI or Voyage), skip the local model and set your provider and API key in the configuration instead.
Then configure opencode to load the plugin. In your `opencode.json`:
```json
{
"plugin": ["@opencode-manager/memory"]
}
```
## Configuration
On first run, the plugin automatically copies the bundled config to your data directory:
@@ -166,19 +164,29 @@ You can edit this file to customize settings. The file is created only if it doe
"embedding": {
"provider": "local",
"model": "all-MiniLM-L6-v2",
"dimensions": 384
"dimensions": 384,
"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": ""
}
@@ -214,18 +222,41 @@ For API-based embeddings:
#### Logging
- `logging.enabled` - Enable file logging (default: `false`)
- `logging.file` - Log file path (default: `"~/.local/share/opencode/memory/logs/memory.log"`)
- `logging.debug` - Enable debug-level log output (default: `false`)
- `logging.file` - Log file path. When empty, resolves to `~/.local/share/opencode/memory/logs/memory.log` (default: `""`)
When enabled, logs are written to the specified file with timestamps. The log file has a 10MB size limit with automatic rotation.
#### Compaction
- `compaction.customPrompt` - Use a custom compaction prompt optimized for session continuity (default: `true`)
- `compaction.inlinePlanning` - Inject planning state (phases, objectives, progress) into compaction context (default: `true`)
- `compaction.maxContextTokens` - Token budget for injected memory context with priority-based trimming (default: `4000`)
- `compaction.snapshotToKV` - Store compaction snapshots in the session KV store for recovery (default: `true`)
#### Memory Injection
- `memoryInjection.enabled` - Inject relevant project memories into user messages via semantic search (default: `true`)
- `memoryInjection.debug` - Enable debug logging for memory injection (default: `false`)
- `memoryInjection.maxResults` - Maximum number of vector search results to retrieve (default: `5`)
- `memoryInjection.distanceThreshold` - Maximum vector distance for a memory to be considered relevant; lower values are stricter (default: `0.5`)
- `memoryInjection.maxTokens` - Token budget for the injected `<project-memory>` block (default: `2000`)
- `memoryInjection.cacheTtlMs` - How long (ms) to cache results for identical queries (default: `30000`)
#### Messages Transform
- `messagesTransform.enabled` - Enable the messages transform hook that handles memory injection and Architect read-only enforcement (default: `true`)
- `messagesTransform.debug` - Enable debug logging for messages transform (default: `false`)
#### Execution
- `executionModel` - Model override for plan execution sessions, format: `provider/model` (e.g. `anthropic/claude-sonnet-4-20250514`). When set, `memory-plan-execute` uses this model for the new Code session. When empty or omitted, OpenCode's default model is used (typically the `model` field from `opencode.json`).
- `executionModel` - Model override for plan execution sessions, format: `provider/model` (e.g. `anthropic/claude-haiku-3-5-20241022`). When set, `memory-plan-execute` uses this model for the new Code session. When empty or omitted, OpenCode's default model is used (typically the `model` field from `opencode.json`). **Recommended:** Set this to a fast, cheap model (e.g. Haiku or MiniMax) and use a smart model (e.g. Opus) for the Architect session — planning needs reasoning, execution needs speed.
## Architect → Code Workflow
Plan with a smart model, execute with a fast model. The Architect agent researches and designs; the Code agent implements.
Set `executionModel` in your config to a fast model (e.g., Haiku) and use a smart model (e.g., Opus) for the Architect session.
See the [full workflow guide](https://chriswritescode-dev.github.io/opencode-manager/features/memory/#architect--code) for setup details.
## Documentation
Full documentation available at [chriswritescode-dev.github.io/opencode-manager/features/memory](https://chriswritescode-dev.github.io/opencode-manager/features/memory/)
## Development
@@ -234,3 +265,7 @@ pnpm build # Compile TypeScript to dist/
pnpm test # Run tests
pnpm typecheck # Type check without emitting
```
## License
MIT
+12 -3
View File
@@ -9,13 +9,22 @@
"dedupThreshold": 0.25,
"logging": {
"enabled": false,
"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": ""
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/memory",
"version": "0.0.10",
"version": "0.0.14",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -34,10 +34,10 @@
"plugin"
],
"license": "MIT",
"homepage": "https://github.com/chriswritescode-dev/opencode-manager#readme",
"homepage": "https://chriswritescode-dev.github.io/opencode-manager/features/memory/",
"dependencies": {
"@huggingface/transformers": "^3.8.1",
"@opencode-ai/plugin": "^1.2.9",
"@opencode-ai/plugin": "^1.2.16",
"sqlite-vec": "0.1.7-alpha.2"
},
"optionalDependencies": {
+10 -16
View File
@@ -14,9 +14,6 @@ export const architectAgent: AgentDefinition = {
'*': 'deny',
},
},
tools: {
exclude: ['memory-planning-update', 'memory-planning-search'],
},
systemPrompt: `You are a planning agent with access to project memory. Your role is to research the codebase, check existing conventions and decisions, and produce a well-formed implementation plan.
# Tone and style
@@ -27,6 +24,7 @@ Prioritize technical accuracy over validating assumptions. Disagree when the evi
# Tool usage policy
- When exploring the codebase, prefer the Task tool with explore agents to reduce context usage.
- Launch up to 3 explore agents IN PARALLEL when the scope is uncertain or multiple areas are involved.
- If a task matches an available skill, use the Skill tool to load domain-specific instructions before planning. Skill outputs persist through compaction.
- Call multiple tools in a single response when they are independent. Batch tool calls for performance.
- Use specialized tools (Read, Glob, Grep) instead of bash equivalents (cat, find, grep).
- Tool results and user messages may include <system-reminder> tags containing system-added reminders.
@@ -46,7 +44,7 @@ When referencing code, use the pattern \`file_path:line_number\` for easy naviga
## Constraints
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. When approved, call memory-plan-execute to save planning state and send the plan to a Code agent.
You are in READ-ONLY mode. You must NOT edit files, run destructive commands, or make any changes. You may only read, search, and analyze. Formalize the plan and present it for the user for approval before proceeding. You MUST use the question tool (mcp_question) to collect plan approval — never ask for approval via plain text output. Do NOT call memory-plan-execute until the user explicitly approves via the question tool.
## Memory Integration
@@ -56,21 +54,22 @@ For the Research phase, prefer delegating to @Memory with a clear prompt describ
Use memory-read directly only for quick, single-query checks (e.g., confirming a specific convention exists).
## Planning State
## Injected Memory
You can read the current session's planning state directly with memory-planning-get. For cross-session plan searches, delegate to the @Memory subagent via the Task tool:
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
- **memory-planning-get** (direct): Retrieve planning state for the current session — use when resuming work or checking progress on the active plan.
- **Searching prior plans**: Delegate to @Memory — tell it to call memory-planning-search to find prior plans that may overlap with or inform the current request.
- **[convention]**: Rules to follow when planning
- **[decision]**: Architectural constraints with rationale
- **[context]**: Reference information — file locations, domain knowledge
Planning state is saved automatically when you call memory-plan-execute — pass objective, phases, and findings alongside the plan. Before creating a new plan, use memory-planning-get to check the current session.
These memories may be stale or irrelevant. Use your judgement — if a memory seems outdated, note it in your plan and recommend updating or deleting it via memory-edit or memory-delete.
## Workflow
1. **Research** — Read relevant files, search the codebase, delegate to @Memory subagent for conventions, decisions, and prior plans
2. **Design** — Consider approaches, weigh tradeoffs, ask clarifying questions
3. **Plan** — Present a clear, detailed plan to the user for review
4. **Execute** — Use the question tool to ask for user approval of the plan. Present the user with clear options (e.g., "Approve" or "Deny"). Do NOT call memory-plan-execute until the user explicitly approves. Once approved, call memory-plan-execute with the full plan (it saves planning state automatically)
4. **Approve** — After presenting the plan, you MUST call the question tool (mcp_question) to get explicit approval. Do NOT ask for approval via plain text — always use the question tool with options like "Approve plan" and "Reject plan". Only proceed to call memory-plan-execute after the user selects approval via the question tool
## Plan Format
@@ -86,10 +85,5 @@ Present plans with:
When the user approves the plan, call memory-plan-execute with:
- **plan**: The full implementation plan — must be **fully self-contained** since the Code agent has no access to this conversation. Include every file path, implementation details, code patterns to match, phase dependencies, verification steps, and gotchas. Do NOT summarize or abbreviate.
- **title**: Short descriptive label for the session list.
- **objective**: Short description of what we're building.
- **phases**: Each phase from the plan with status "pending".
- **findings**: Key architectural decisions discovered during research.
Planning state is saved automatically before the plan is dispatched to the Code agent.`,
- **title**: Short descriptive label for the session list.`,
}
+11 -7
View File
@@ -35,9 +35,6 @@ Diffs alone are not enough. After getting the diff:
- Check project memory for relevant conventions and decisions:
- Use memory-read with scope "convention" to find coding standards for the changed files
- Use memory-read with scope "decision" to find architectural decisions that may apply
- Check planning state for context:
- Use memory-planning-get to understand what the current session is working on
- Use memory-planning-search to find prior plans related to the changed code areas
## What to Look For
@@ -77,9 +74,6 @@ Don't be a zealot about style:
- Use the Task tool with explore agents to find how existing code handles similar problems
- Use memory-read to check stored conventions and decisions before claiming something doesn't fit
- Use memory-planning-get to understand session context
- Use memory-planning-search to find prior plans for intent behind the changes
- Use memory-planning-update to record review findings in planning state
- Call multiple tools in a single response when independent
- Use specialized tools (Read, Glob, Grep) instead of bash equivalents (cat, find, grep)
@@ -107,5 +101,15 @@ If no issues are found, say so clearly and briefly.
## Constraints
You are read-only on source code. Do not edit files, run destructive commands, or make any changes. Only read, search, analyze, and report findings.`,
You are read-only on source code. Do not edit files, run destructive commands, or make any changes. Only read, search, analyze, and report findings.
## Injected Memory
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
- **[convention]**: Rules to check code against
- **[decision]**: Architectural constraints that may apply
- **[context]**: Reference information
These memories may be stale or irrelevant. If a memory seems outdated, note it in your review observations. You do not have write access to memory — flag stale memories for the calling agent to handle.`,
}
+11 -8
View File
@@ -9,9 +9,10 @@ export const codeAgent: AgentDefinition = {
color: '#3b82f6',
permission: {
question: 'allow',
plan_enter: 'allow',
},
tools: {
exclude: ['memory-plan-execute', 'memory-planning-update', 'memory-planning-search'],
exclude: ['memory-plan-execute'],
},
systemPrompt: `You are a coding agent that helps users with software engineering tasks. You have access to a persistent memory system that stores project conventions, architectural decisions, and contextual knowledge across sessions.
@@ -37,6 +38,7 @@ Mark todos as completed as soon as each task is done — do not batch completion
# Tool usage policy
- When doing file search or exploring the codebase, prefer the Task tool to reduce context usage.
- Proactively use the Task tool with specialized agents when the task matches the agent's description.
- If a task matches an available skill, use the Skill tool to load domain-specific instructions. Skill outputs persist through compaction.
- Call multiple tools in a single response when they are independent. Batch parallel tool calls for performance.
- Use specialized tools (Read, Glob, Grep, Edit, Write) instead of bash equivalents (cat, find, grep, sed, echo).
- NEVER use bash echo or other CLI tools to communicate with the user. Output text directly.
@@ -46,7 +48,7 @@ When referencing code, use the pattern \`file_path:line_number\` for easy naviga
## Memory Integration
You have memory tools (memory-read, memory-write, memory-edit, memory-delete) and the @Memory subagent (via Task tool) for complex operations — multi-query research, contradiction resolution, bulk curation, planning state updates, and cross-session planning searches. Delegate to @Memory when you need broad context or when the result set could be large, to keep your context clean.
You have memory tools (memory-read, memory-write, memory-edit, memory-delete) and the @Memory subagent (via Task tool) for complex operations — multi-query research, contradiction resolution, and bulk curation. Delegate to @Memory when you need broad context or when the result set could be large, to keep your context clean.
**Check memory** before modifying unfamiliar code areas, making architectural decisions, or when the user references past decisions. Skip memory for trivial tasks or when the user provides all necessary context.
@@ -60,13 +62,14 @@ You have memory tools (memory-read, memory-write, memory-edit, memory-delete) an
- Update stale memories with memory-edit rather than creating duplicates
- Reference file paths when storing structural context
## Planning State
## Injected Memory
You can read the current session's planning state directly with memory-planning-get. For all other planning operations, delegate to the @Memory subagent via the Task tool:
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
- **memory-planning-get** (direct): Retrieve planning state for the current session — use when resuming work or when the user asks about progress.
- **Updating planning state**: Delegate to @Memory — tell it to call memory-planning-update with phase statuses, current activity, findings, and errors.
- **Searching prior plans**: Delegate to @Memory — tell it to call memory-planning-search to find related work across sessions.
- **[convention]**: Rules to follow — coding style, naming patterns, workflow preferences
- **[decision]**: Architectural choices with rationale — treat as constraints
- **[context]**: Reference information — file locations, domain knowledge, known issues
When executing a plan from the Architect agent, delegate to @Memory to update planning state as you complete each phase so progress is visible across sessions.`,
These memories may be stale or irrelevant to the current task. Use your judgement. If a memory seems outdated or incorrect, flag it to the user and use memory-edit or memory-delete to correct it.
`,
}
+10 -35
View File
@@ -4,7 +4,7 @@ export const memoryAgent: AgentDefinition = {
role: 'memory',
id: 'ocm-memory',
displayName: 'Memory',
description: 'Expert agent for managing project memory and planning state - storing and retrieving conventions, decisions, context, and session progress',
description: 'Expert agent for managing project memory - storing and retrieving conventions, decisions, context, and session progress',
mode: 'subagent',
tools: {
exclude: ['memory-plan-execute'],
@@ -171,7 +171,6 @@ You are invoked when:
- An agent makes an architectural decision that should be recorded
- An agent encounters something worth preserving for future sessions
- Review feedback involves project-specific standards
- An agent needs to update planning state or search plans across sessions (only you have memory-planning-update and memory-planning-search)
- The Architect agent needs broad memory research before designing a plan (multi-query sweep of conventions, decisions, and prior plans)
You are NOT needed for:
@@ -190,43 +189,19 @@ You are NOT needed for:
- content: The memory content
- scope: convention | decision | context
3. **memory-delete**: Remove memories by ID
3. **memory-edit**: Edit an existing memory
- id: The memory ID to edit
- content: Updated memory content
- scope: Optionally change the scope
4. **memory-delete**: Remove memories by ID
- id: The memory ID to delete
4. **memory-planning-update**: Update session planning state
- sessionID: Session to update (optional, defaults to current session)
- objective: Main task/goal (optional)
- current: Current phase or activity (optional)
- next: What comes next (optional)
- phases: Array of {title, status, notes?} (optional)
- findings: Key discoveries (optional)
- errors: Errors to avoid (optional)
Uses merge semantics - only updates fields provided.
## Injected Memory
5. **memory-planning-get**: Get planning state for a session
- sessionID: Session to retrieve (optional, defaults to current session)
Your messages may include \`<project-memory>\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`#<id> [<scope>] <content>\`.
6. **memory-planning-search**: Search planning states across all sessions in the project
- query: Optional search keyword to filter planning states. Omit to list all.
## Planning State Management
You are responsible for maintaining planning state across sessions:
1. **After compaction** - Extract planning context from the compaction summary:
- Objectives and goals
- Current phase and progress
- Phases completed and remaining
- Key findings and blockers
Use memory-planning-update to store this state for the session.
2. **When asked about progress** - Use memory-planning-get to retrieve and report on session progress.
3. **Guidance**:
- Phases should track: in_progress, completed, pending
- Store findings as they accumulate (architecture decisions, gotchas discovered)
- Track errors to avoid (mistakes made, workarounds needed)
- Mark planning as active when work is ongoing
Use these as a starting point for your research — they indicate what the system found relevant. Cross-reference with memory-read for completeness. If any injected memory is stale or contradicts newer information, update or delete it.
Your goal is to be the connective tissue between sessions—ensuring knowledge isn't lost and patterns are maintained. Be helpful, be accurate, and keep the memory base clean and useful.`,
}
+2 -2
View File
@@ -16,7 +16,7 @@ export interface AgentDefinition {
}
variant?: string
temperature?: number
maxSteps?: number
steps?: number
permission?: Record<string, unknown>
}
@@ -28,7 +28,7 @@ export interface AgentConfig {
tools?: Record<string, boolean>
variant?: string
temperature?: number
maxSteps?: number
steps?: number
hidden?: boolean
color?: string
permission?: Record<string, unknown>
+2 -2
View File
@@ -9,8 +9,8 @@ export class InMemoryCacheService implements CacheService {
private cache = new Map<string, CacheEntry<unknown>>()
private cleanupInterval: ReturnType<typeof setInterval> | null = null
constructor() {
this.cleanupInterval = setInterval(() => this.cleanup(), 60000)
constructor(cleanupIntervalMs: number = 60000) {
this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs)
}
private cleanup(): void {
+3 -80
View File
@@ -4,7 +4,6 @@ interface CleanupOptions {
olderThan?: number
ids?: number[]
scope?: MemoryScope
sessions?: boolean
all?: boolean
dryRun?: boolean
force?: boolean
@@ -40,8 +39,6 @@ function parseArgs(args: string[]): CleanupOptions {
process.exit(1)
}
options.scope = scope
} else if (arg === '--sessions') {
options.sessions = true
} else if (arg === '--all') {
options.all = true
} else if (arg === '--dry-run') {
@@ -78,7 +75,6 @@ Options:
--older-than <days> Delete memories older than N days
--ids <id,id,...> Delete specific memory IDs
--scope <scope> Filter by scope (convention, decision, context)
--sessions Clean up session states instead of memories
--all Delete all memories for the project (requires --project)
--dry-run Preview what would be deleted without deleting
--force Skip confirmation prompt
@@ -97,8 +93,8 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
process.exit(0)
}
if (!options.olderThan && !options.ids && !options.sessions && !options.all) {
console.error('At least one filter must be provided: --older-than, --ids, --sessions, or --all')
if (!options.olderThan && !options.ids && !options.all) {
console.error('At least one filter must be provided: --older-than, --ids, or --all')
help()
process.exit(1)
}
@@ -116,11 +112,7 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
const db = openDatabase(options.dbPath || globalOpts.dbPath)
try {
if (options.sessions) {
runSessionCleanup(db, options)
} else {
runMemoryCleanup(db, options)
}
runMemoryCleanup(db, options)
} finally {
db.close()
}
@@ -206,72 +198,3 @@ async function runMemoryCleanup(db: ReturnType<typeof openDatabase>, options: Cl
console.log(`Deleted ${rows.length} memories. ${remainingCount.count} remaining.`)
console.log("Note: Run 'memory-health reindex' in OpenCode to clean up orphaned embeddings.")
}
async function runSessionCleanup(db: ReturnType<typeof openDatabase>, options: CleanupOptions): Promise<void> {
const projectId = options.projectId!
const nameMap = resolveProjectNames()
let query = 'SELECT key, project_id, expires_at, created_at, updated_at FROM session_state WHERE project_id = ?'
const params: (string | number)[] = [projectId]
if (options.olderThan) {
const cutoffTime = Date.now() - options.olderThan * 24 * 60 * 60 * 1000
query += ' AND created_at < ?'
params.push(cutoffTime)
}
if (options.all) {
query = 'SELECT key, project_id, expires_at, created_at, updated_at FROM session_state WHERE project_id = ?'
params.length = 0
params.push(projectId)
}
const rows = db.prepare(query).all(...params) as Array<{
key: string
project_id: string
expires_at: number | null
created_at: number
updated_at: number
}>
if (rows.length === 0) {
console.log('No session states found to delete.')
return
}
console.log('')
console.log(`Found ${rows.length} session states to delete:`)
console.log(' KEY PROJECT CREATED EXPIRED')
const displayRows = rows.slice(0, 20)
for (const row of displayRows) {
const key = truncate(row.key, 38).padEnd(40)
const project = displayProjectId(row.project_id, nameMap).padEnd(14)
const created = formatDate(row.created_at)
const expired = row.expires_at ? formatDate(row.expires_at) : '-'
console.log(` ${key} ${project} ${created} ${expired}`)
}
if (rows.length > 20) {
console.log(` ... and ${rows.length - 20} more`)
}
console.log('')
if (options.dryRun) {
console.log('Dry run - no session states deleted.')
return
}
const shouldProceed = options.force || (await confirm(`Delete ${rows.length} session states`))
if (!shouldProceed) {
console.log('Cancelled.')
return
}
const keysToDelete = rows.map((r) => r.key)
const deleteQuery = `DELETE FROM session_state WHERE key IN (${keysToDelete.map(() => '?').join(',')})`
db.prepare(deleteQuery).run(...keysToDelete)
console.log(`Deleted ${rows.length} session states.`)
}
+1 -31
View File
@@ -7,13 +7,6 @@ interface ProjectMemoryStats {
newest: number
}
interface ProjectSessionStats {
project_id: string
count: number
oldest: number
newest: number
}
function parseArgs(args: string[]): { dbPath?: string; help?: boolean } {
const options: { dbPath?: string; help?: boolean } = {}
let i = 0
@@ -39,7 +32,7 @@ function parseArgs(args: string[]): { dbPath?: string; help?: boolean } {
export function help(): void {
console.log(`
List projects with memory and session state counts
List projects with memory counts
Usage:
ocm-mem list [options]
@@ -69,12 +62,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
FROM memories GROUP BY project_id ORDER BY count DESC
`).all() as ProjectMemoryStats[]
const sessionRows = db.prepare(`
SELECT project_id, COUNT(*) as count,
MIN(created_at) as oldest, MAX(updated_at) as newest
FROM session_state GROUP BY project_id ORDER BY count DESC
`).all() as ProjectSessionStats[]
console.log('')
if (memoryRows.length > 0) {
@@ -93,23 +80,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
}
console.log('')
if (sessionRows.length > 0) {
console.log('Session states:')
console.log(' PROJECT SESSIONS OLDEST NEWEST')
for (const row of sessionRows) {
const name = displayProjectId(row.project_id, nameMap).padEnd(19)
const count = String(row.count).padEnd(9)
const oldest = formatDate(row.oldest)
const newest = formatDate(row.newest)
console.log(` ${name} ${count} ${oldest} ${newest}`)
}
} else {
console.log('No session states found.')
}
console.log('')
} finally {
db.close()
}
-25
View File
@@ -10,12 +10,6 @@ interface ProjectStats {
newest: number
}
interface SessionStats {
planning: number
compaction: number
expired: number
}
function parseArgs(args: string[]): { projectId?: string; dbPath?: string; help?: boolean } {
const options: { projectId?: string; dbPath?: string; help?: boolean } = {}
let i = 0
@@ -86,14 +80,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
FROM memories WHERE project_id = ?
`).get(finalProjectId) as ProjectStats | undefined
const sessionRows = db.prepare(`
SELECT
SUM(CASE WHEN key LIKE 'session:%' THEN 1 ELSE 0 END) as planning,
SUM(CASE WHEN key LIKE 'compaction:%' THEN 1 ELSE 0 END) as compaction,
SUM(CASE WHEN expires_at IS NOT NULL AND expires_at < ? THEN 1 ELSE 0 END) as expired
FROM session_state WHERE project_id = ?
`).get(Date.now(), finalProjectId) as SessionStats | undefined
const totalMemories = scopeRows.reduce((sum, row) => sum + row.count, 0)
console.log('')
@@ -118,17 +104,6 @@ export function run(args: string[], globalOpts: { dbPath?: string; projectId?: s
console.log(` Newest: ${formatDate(statsRow.newest)}`)
}
console.log('')
console.log('Session State:')
if (sessionRows) {
console.log(` Planning states: ${sessionRows.planning || 0}`)
console.log(` Compaction snapshots: ${sessionRows.compaction || 0}`)
console.log(` Expired (pending cleanup): ${sessionRows.expired || 0}`)
} else {
console.log(' None')
}
console.log('')
} finally {
db.close()
-9
View File
@@ -26,15 +26,6 @@ export interface GlobalOptions {
help?: boolean
}
export interface SessionState {
key: string
projectId: string
data: string
expiresAt: number | null
createdAt: number
updatedAt: number
}
export function resolveDefaultDbPath(): string {
const localPath = join(process.cwd(), '.opencode', 'state', 'opencode', 'memory', 'memory.db')
if (existsSync(localPath)) {
+1 -4
View File
@@ -6,9 +6,6 @@ const ENHANCED_BUILTIN_AGENTS: Record<string, { tools: Record<string, boolean> }
plan: {
tools: {
'memory-read': true,
'memory-planning-update': true,
'memory-planning-get': true,
'memory-planning-search': true,
},
},
}
@@ -87,7 +84,7 @@ function createAgentConfigs(agents: Record<AgentRole, AgentDefinition>): Record<
...(Object.keys(tools).length > 0 ? { tools } : {}),
...(agent.variant ? { variant: agent.variant } : {}),
...(agent.temperature !== undefined ? { temperature: agent.temperature } : {}),
...(agent.maxSteps !== undefined ? { maxSteps: agent.maxSteps } : {}),
...(agent.steps !== undefined ? { steps: agent.steps } : {}),
...(agent.hidden ? { hidden: agent.hidden } : {}),
...(agent.color ? { color: agent.color } : {}),
...(agent.permission ? { permission: agent.permission } : {}),
+1 -1
View File
@@ -111,7 +111,7 @@ export async function acquireEmbeddingServer(config: SharedEmbeddingConfig): Pro
const lockAcquired = await acquireLock(lockPath)
if (!lockAcquired) {
for (let i = 0; i < 10; i++) {
for (let i = 0; i < 30; i++) {
await sleep(500)
const health = await checkServerHealth(socketPath)
if (health !== null) {
+4 -58
View File
@@ -1,5 +1,3 @@
import type { PlanningState } from '../types'
interface PromptResponsePart {
type: string
text?: string
@@ -17,20 +15,16 @@ Preserve everything needed for seamless continuation.
## CRITICAL - Preserve These Verbatim
1. The current task/objective (quote the user's original request exactly)
2. Active planning state: current phase, completed phases, next steps, blockers
3. ALL file paths being actively worked on (with what's being done)
4. Key decisions made and their rationale
5. Any corrections or gotchas discovered during the session
6. Todo list state (what's done, in progress, pending)
2. ALL file paths being actively worked on (with what's being done)
3. Key decisions made and their rationale
4. Any corrections or gotchas discovered during the session
5. Todo list state (what's done, in progress, pending)
## Structure Your Summary As:
### Active Task
[Verbatim objective + what was happening when compaction fired]
### Planning State
[Phases with status and notes]
### Key Context
[Decisions, constraints, user preferences, corrections]
@@ -46,61 +40,13 @@ Preserve everything needed for seamless continuation.
- Prefer completeness over brevity - this is the agent's entire working memory`
}
export function formatPlanningState(planningState: PlanningState | null): string | null {
if (!planningState) return null
const sections: string[] = []
if (planningState.objective) {
sections.push(`**Objective:** ${planningState.objective}`)
}
if (planningState.current) {
sections.push(`**Current:** ${planningState.current}`)
}
if (planningState.next) {
sections.push(`**Next:** ${planningState.next}`)
}
if (planningState.phases && planningState.phases.length > 0) {
sections.push('\n### Phases:')
for (const phase of planningState.phases) {
const statusIcon = phase.status === 'completed' ? '[x]' : phase.status === 'in_progress' ? '[~]' : '[ ]'
const notes = phase.notes ? ` - ${phase.notes}` : ''
sections.push(`- ${statusIcon} ${phase.title}${notes}`)
}
}
if (planningState.findings && planningState.findings.length > 0) {
sections.push('\n### Key Findings:')
for (const finding of planningState.findings) {
sections.push(`- ${finding}`)
}
}
if (planningState.errors && planningState.errors.length > 0) {
sections.push('\n### Errors to Avoid:')
for (const error of planningState.errors) {
sections.push(`- ${error}`)
}
}
return sections.join('\n')
}
export function formatCompactionDiagnostics(stats: {
planningPhases: number
conventions: number
decisions: number
tokensInjected: number
}): string {
const parts: string[] = []
if (stats.planningPhases > 0) {
parts.push(`${stats.planningPhases} planning phase${stats.planningPhases !== 1 ? 's' : ''}`)
}
if (stats.conventions > 0) {
parts.push(`${stats.conventions} convention${stats.conventions !== 1 ? 's' : ''}`)
}
+1 -1
View File
@@ -1,9 +1,9 @@
export { createSessionHooks, type SessionHooks } from './session'
export {
buildCustomCompactionPrompt,
formatPlanningState,
formatCompactionDiagnostics,
estimateTokens,
trimToTokenBudget,
extractCompactionSummary,
} from './compaction-utils'
export { createMemoryInjectionHook, type MemoryInjectionHook } from './memory-injection'
@@ -0,0 +1,151 @@
import type { MemoryService } from '../services/memory'
import type { MemoryInjectionConfig, Logger, MemorySearchResult } from '../types'
import { InMemoryCacheService } from '../cache/memory-cache'
import { estimateTokens } from './compaction-utils'
async function sha256(message: string): Promise<string> {
const msgBuffer = new TextEncoder().encode(message)
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
}
interface MemoryInjectionDeps {
projectId: string
memoryService: MemoryService
logger: Logger
config?: MemoryInjectionConfig
}
export interface MemoryInjectionHook {
handler: (userText: string) => Promise<string | null>
destroy: () => void
}
export function createMemoryInjectionHook(deps: MemoryInjectionDeps): MemoryInjectionHook {
const { projectId, memoryService, logger, config } = deps
const enabled = config?.enabled ?? true
const debug = config?.debug ?? false
const maxResults = config?.maxResults ?? 5
const distanceThreshold = config?.distanceThreshold ?? 0.5
const maxTokens = config?.maxTokens ?? 2000
const cacheTtlMs = config?.cacheTtlMs ?? 30000
const cache = new InMemoryCacheService()
let initialized = false
const handler = async (userText: string): Promise<string | null> => {
if (!enabled) {
return null
}
if (!initialized) {
logger.log(`memory-injection: initialized (enabled=${enabled}, maxResults=${maxResults}, distanceThreshold=${distanceThreshold}, maxTokens=${maxTokens}, cacheTtlMs=${cacheTtlMs})`)
initialized = true
}
if (debug) {
logger.debug('memory-injection: hook invoked', { projectId, userTextLength: userText.length })
}
try {
const hash = await sha256(userText)
const cacheKey = `memory-injection:${hash}`
const cached = await cache.get<string>(cacheKey)
if (cached !== null) {
if (debug) {
logger.debug('memory-injection: cache hit', { projectId, hash })
}
return cached === '' ? null : cached
}
if (debug) {
logger.debug('memory-injection: cache miss', { projectId, hash })
}
const searchResults = await memoryService.search(userText, projectId, { limit: maxResults })
logger.log(`memory-injection: search returned ${searchResults.length} results for project ${projectId}`)
if (debug && searchResults.length > 0) {
const distances = searchResults.map((r: MemorySearchResult) => `#${r.memory.id}(${r.memory.scope}):${r.distance.toFixed(3)}`)
logger.debug('memory-injection: result distances', { distances, distanceThreshold })
}
const filteredResults = searchResults.filter((result: MemorySearchResult) => result.distance <= distanceThreshold)
if (searchResults.length > 0 && filteredResults.length === 0) {
const closest = Math.min(...searchResults.map((r: MemorySearchResult) => r.distance))
logger.log(`memory-injection: all ${searchResults.length} results filtered out (closest distance: ${closest.toFixed(3)}, threshold: ${distanceThreshold})`)
}
if (searchResults.length === 0) {
logger.log('memory-injection: search returned 0 results (vec may be unavailable)')
}
if (filteredResults.length === 0) {
await cache.set(cacheKey, '', cacheTtlMs / 1000)
if (debug) {
logger.debug('memory-injection: no matching memories found', { projectId })
}
return null
}
const sections: string[] = []
sections.push('<project-memory>')
for (const result of filteredResults) {
const { memory } = result
sections.push(`- #${memory.id} [${memory.scope}] ${memory.content}`)
}
sections.push('</project-memory>')
let formatted = sections.join('\n')
let tokens = estimateTokens(formatted)
if (tokens > maxTokens) {
const trimmedSections: string[] = []
trimmedSections.push('<project-memory>')
let currentTokens = estimateTokens('<project-memory>')
for (const result of filteredResults) {
const line = `- #${result.memory.id} [${result.memory.scope}] ${result.memory.content}`
const lineTokens = estimateTokens(line)
if (currentTokens + lineTokens > maxTokens - estimateTokens('</project-memory>')) {
break
}
trimmedSections.push(line)
currentTokens += lineTokens
}
trimmedSections.push('</project-memory>')
formatted = trimmedSections.join('\n')
tokens = estimateTokens(formatted)
if (debug) {
logger.debug('memory-injection: trimmed to token limit', { tokens })
}
}
await cache.set(cacheKey, formatted, cacheTtlMs / 1000)
logger.log(`memory-injection: injected ${filteredResults.length} relevant memories (${tokens} tokens) for query`)
return formatted
} catch (error) {
logger.error('memory-injection: failed to inject memories', error)
return null
}
}
return {
handler,
destroy: () => cache.destroy(),
}
}
+6 -75
View File
@@ -1,10 +1,8 @@
import type { Logger, PlanningState, PreCompactionSnapshot, CompactionConfig } from '../types'
import type { Logger, CompactionConfig } from '../types'
import type { MemoryService } from '../services/memory'
import type { SessionStateService } from '../services/session-state'
import type { PluginInput } from '@opencode-ai/plugin'
import {
buildCustomCompactionPrompt,
formatPlanningState,
formatCompactionDiagnostics,
estimateTokens,
trimToTokenBudget,
@@ -33,7 +31,6 @@ interface EventInput {
interface CompactingInput {
sessionID: string
branch?: string
}
interface CompactingOutput {
@@ -53,17 +50,11 @@ function formatEventProperties(props?: Record<string, unknown>): string {
}
function buildSubtaskPrompt(
sessionId: string,
compactionSummary: string,
planningState: PlanningState | null
): string {
const planningSection = planningState
? `## Current Planning State\n\n${formatPlanningState(planningState) ?? '(no details)'}\n\n---\n`
: ''
return `Review the following and extract any project knowledge worth preserving across sessions.
${planningSection}## Compaction Summary
## Compaction Summary
${compactionSummary}
@@ -74,26 +65,21 @@ For each item found, store it with the appropriate scope:
- decision: architectural choices with their rationale
- context: project structure, key file locations, domain knowledge, known issues
Also extract any planning state (phases, objectives, progress, blockers). If found, use memory-planning-update with sessionID "${sessionId}" to store it.
Be selective — only store knowledge useful in future sessions. Check for duplicates before writing (use memory-read to search first).
End your response with:
1. A brief summary of what was stored
2. Whether there was active work in progress (in-progress todos, pending tasks, or incomplete planning phases). If so, tell the main agent to review the planning state and todo list and continue where it left off.`
2. Whether there was active work in progress (in-progress todos or pending tasks). If so, tell the main agent to review the todo list and continue where it left off.`
}
const DEFAULT_COMPACTION_CONFIG: CompactionConfig = {
customPrompt: true,
inlinePlanning: true,
maxContextTokens: 4000,
snapshotToKV: true,
}
export function createSessionHooks(
projectId: string,
memoryService: MemoryService,
sessionStateService: SessionStateService,
logger: Logger,
ctx: PluginInput,
config?: CompactionConfig
@@ -119,11 +105,6 @@ export function createSessionHooks(
logger.log(`Post-compaction: fetched compaction summary (${compactionSummary.length} chars)`)
const planningState = sessionStateService.getPlanningState(sessionId, projectId)
if (planningState) {
logger.log(`Post-compaction: fetched planning state for session ${sessionId}`)
}
await ctx.client.session.prompt({
path: { id: sessionId },
body: {
@@ -132,7 +113,7 @@ export function createSessionHooks(
type: 'subtask',
agent: 'Memory',
description: 'Memory extraction after compaction',
prompt: buildSubtaskPrompt(sessionId, compactionSummary, planningState),
prompt: buildSubtaskPrompt(compactionSummary),
},
],
},
@@ -172,45 +153,11 @@ export function createSessionHooks(
})
},
async onCompacting(input: CompactingInput, output: CompactingOutput) {
const { sessionID: sessionId, branch } = input
const { sessionID: sessionId } = input
logger.log(`Compacting hook fired for project ${projectId}, session ${sessionId}`)
try {
const sections: string[] = []
let totalTokens = 0
let planningState: PlanningState | null = null
if (compactionConfig.inlinePlanning) {
planningState = sessionStateService.getPlanningState(sessionId, projectId)
if (planningState) {
const planningText = formatPlanningState(planningState)
if (planningText) {
sections.push(`## Planning State\n${planningText}`)
totalTokens += estimateTokens(planningText)
}
logger.log(`Compacting: fetched planning state for session ${sessionId}`)
}
}
if (compactionConfig.snapshotToKV) {
const priorSnapshot = sessionStateService.getCompactionSnapshot(sessionId, projectId)
if (priorSnapshot) {
const snapshotParts: string[] = []
snapshotParts.push(`Last compaction: ${new Date(priorSnapshot.timestamp).toLocaleString()}`)
if (priorSnapshot.branch) {
snapshotParts.push(`branch: ${priorSnapshot.branch}`)
}
if (priorSnapshot.planningState) {
const priorPlanningText = formatPlanningState(priorSnapshot.planningState)
if (priorPlanningText) {
snapshotParts.push(`\n### Prior Planning State:\n${priorPlanningText}`)
}
}
sections.push(`## Prior Session Context\n${snapshotParts.join('\n')}`)
totalTokens += estimateTokens(snapshotParts.join('\n'))
logger.log(`Compacting: fetched prior snapshot for session ${sessionId}`)
}
}
const [convMemories, decMemories] = await Promise.all([
memoryService.listByProject(projectId, { scope: 'convention', limit: 10 }),
@@ -234,7 +181,7 @@ export function createSessionHooks(
const maxTokens = compactionConfig.maxContextTokens ?? 4000
let trimmedSections = [...sections]
let currentTokens = totalTokens
let currentTokens = 0
for (let i = trimmedSections.length - 1; i >= 0; i--) {
const sectionTokens = estimateTokens(trimmedSections[i]!)
@@ -257,23 +204,7 @@ export function createSessionHooks(
logger.log(`Compacting: set custom compaction prompt`)
}
if (compactionConfig.snapshotToKV) {
try {
const snapshot: PreCompactionSnapshot = {
timestamp: new Date().toISOString(),
sessionId,
planningState: planningState ?? undefined,
branch,
}
sessionStateService.setCompactionSnapshot(sessionId, projectId, snapshot)
logger.log(`Compacting: stored pre-compaction snapshot`)
} catch (error) {
logger.error(`Failed to store pre-compaction snapshot: ${error}`)
}
}
const diagnostics = formatCompactionDiagnostics({
planningPhases: planningState?.phases?.length ?? 0,
conventions: convMemories.length,
decisions: decMemories.length,
tokensInjected: estimateTokens(trimmedSections.join('\n\n')),
+116 -215
View File
@@ -3,27 +3,28 @@ import { tool } from '@opencode-ai/plugin'
import { agents } from './agents'
import { createConfigHandler } from './config'
import { VERSION } from './version'
import { createSessionHooks } from './hooks'
import { createSessionHooks, createMemoryInjectionHook } from './hooks'
import { join } from 'path'
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery, getTableDimensions, recreateVecTable } from './storage'
import { initializeDatabase, resolveDataDir, closeDatabase, createMetadataQuery } from './storage'
import type { MemoryService } from './services/memory'
import { createVecService } from './storage/vec'
import { createEmbeddingProvider, checkServerHealth, isServerRunning, killEmbeddingServer } from './embedding'
import { createMemoryService } from './services/memory'
import { createSessionStateService } from './services/session-state'
import { createEmbeddingSyncService } from './services/embedding-sync'
import { loadPluginConfig } from './setup'
import { resolveLogPath } from './storage'
import { createLogger } from './utils/logger'
import type { Database } from 'bun:sqlite'
import type { PluginConfig, CompactionConfig, HealthStatus, Logger, PlanningState } from './types'
import type { PluginConfig, CompactionConfig, HealthStatus, Logger } from './types'
import type { EmbeddingProvider } from './embedding'
import type { VecService } from './storage/vec-types'
import { createNoopVecService } from './storage/vec'
const z = tool.schema
async function getHealthStatus(
projectId: string,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
@@ -35,7 +36,7 @@ async function getHealthStatus(
let memoryCount = 0
try {
db.prepare('SELECT 1').get()
const row = db.prepare("SELECT COUNT(*) as count FROM memories").get() as { count: number }
const row = db.prepare("SELECT COUNT(*) as count FROM memories WHERE project_id = ?").get(projectId) as { count: number }
memoryCount = row.count
} catch {
dbStatus = 'error'
@@ -138,12 +139,13 @@ function formatHealthStatus(status: HealthStatus, provider: EmbeddingProvider):
}
async function executeHealthCheck(
projectId: string,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
): Promise<string> {
const status = await getHealthStatus(db, config, provider, dataDir)
const status = await getHealthStatus(projectId, db, config, provider, dataDir)
return formatHealthStatus(status, provider)
}
@@ -154,12 +156,13 @@ interface DimensionMismatchState {
}
async function executeReindex(
projectId: string,
memoryService: MemoryService,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
mismatchState: DimensionMismatchState,
vec: VecService,
): Promise<string> {
const configuredModel = config.embedding.model
const configuredDimensions = config.embedding.dimensions ?? provider.dimensions
@@ -175,14 +178,12 @@ async function executeReindex(
return 'Reindex failed: embedding provider is not operational. Check your API key and model configuration.'
}
const tableResult = getTableDimensions(db)
if (tableResult.exists && tableResult.dimensions !== configuredDimensions) {
recreateVecTable(db, configuredDimensions)
const newVec = await createVecService(db, dataDir, configuredDimensions)
memoryService.setVecService(newVec)
const tableInfo = await vec.getDimensions()
if (tableInfo.exists && tableInfo.dimensions !== null && tableInfo.dimensions !== configuredDimensions) {
await vec.recreateTable(configuredDimensions)
}
const result = await memoryService.reindex()
const result = await memoryService.reindex(projectId)
if (result.success > 0 || result.total === 0) {
const metadata = createMetadataQuery(db)
@@ -213,14 +214,17 @@ async function executeReindex(
}
async function autoValidateOnLoad(
projectId: string,
memoryService: MemoryService,
db: Database,
config: PluginConfig,
provider: EmbeddingProvider,
dataDir: string,
mismatchState: DimensionMismatchState,
vec: VecService,
logger: Logger,
): Promise<void> {
const status = await getHealthStatus(db, config, provider, dataDir)
const status = await getHealthStatus(projectId, db, config, provider, dataDir)
if (status.overallStatus === 'error') {
logger.log('Auto-validate: unhealthy (db error), skipping')
@@ -238,16 +242,8 @@ async function autoValidateOnLoad(
}
logger.log('Auto-validate: model drift detected, starting reindex')
const result = await memoryService.reindex()
if (result.success > 0 || result.total === 0) {
const metadata = createMetadataQuery(db)
metadata.setEmbeddingModel(
config.embedding.model,
config.embedding.dimensions ?? provider.dimensions,
)
}
logger.log(`Auto-validate: reindex complete (total=${result.total}, success=${result.success}, failed=${result.failed})`)
await executeReindex(projectId, memoryService, db, config, provider, mismatchState, vec)
logger.log('Auto-validate: reindex complete')
}
function parseModelString(modelStr?: string): { providerID: string; modelID: string } | undefined {
@@ -269,6 +265,7 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const logger = createLogger({
enabled: loggingConfig?.enabled ?? false,
file: loggingConfig?.file ?? resolveLogPath(),
debug: loggingConfig?.debug ?? false,
})
logger.log(`Initializing plugin for directory: ${directory}, projectId: ${projectId}`)
@@ -292,10 +289,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
logger,
})
const sessionStateService = createSessionStateService(db, logger)
sessionStateService.startCleanupInterval()
sessionStateService.deleteExpired()
if (config.dedupThreshold) {
memoryService.setDedupThreshold(config.dedupThreshold)
}
@@ -306,8 +299,17 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
actual: null,
}
const initPromise = createVecService(db, dataDir, dimensions)
const initState = {
vecReady: false,
syncRunning: false,
syncComplete: false,
}
let currentVec: VecService = noopVec
createVecService(db, dataDir, dimensions, logger)
.then(async (vec) => {
currentVec = vec
memoryService.setVecService(vec)
if (!vec.available) {
@@ -316,30 +318,46 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
}
logger.log('Vec service initialized')
initState.vecReady = true
const tableResult = getTableDimensions(db)
if (tableResult.exists && tableResult.dimensions !== dimensions) {
mismatchState.detected = true
mismatchState.expected = dimensions
mismatchState.actual = tableResult.dimensions
memoryService.setVecService(createNoopVecService())
logger.log(`Dimension mismatch detected: config=${dimensions}, table=${tableResult.dimensions ?? 'unknown'}`)
return
const tableInfo = await vec.getDimensions()
if (tableInfo.exists && tableInfo.dimensions !== null && tableInfo.dimensions !== dimensions) {
logger.log(`Dimension mismatch detected: config=${dimensions}, table=${tableInfo.dimensions}, auto-recreating`)
await vec.recreateTable(dimensions)
}
const embeddingSync = createEmbeddingSyncService(memoryService, logger)
await embeddingSync.start().catch((err: unknown) => {
logger.error('Embedding sync failed', err)
})
await autoValidateOnLoad(memoryService, db, config, provider, dataDir, logger)
initState.syncRunning = true
embeddingSync.start().then(
() => {
initState.syncRunning = false
initState.syncComplete = true
autoValidateOnLoad(projectId, memoryService, db, config, provider, dataDir, mismatchState, currentVec, logger)
.catch((err: unknown) => {
logger.error('Auto-validate failed', err)
})
},
(err: unknown) => {
initState.syncRunning = false
logger.error('Embedding sync failed', err)
}
)
})
.catch((err: unknown) => {
logger.error('Vec service initialization failed', err)
})
const compactionConfig: CompactionConfig | undefined = config.compaction
const sessionHooks = createSessionHooks(projectId, memoryService, sessionStateService, logger, input, compactionConfig)
const memoryInjectionConfig = config.memoryInjection
const messagesTransformConfig = config.messagesTransform
const sessionHooks = createSessionHooks(projectId, memoryService, logger, input, compactionConfig)
const memoryInjection = createMemoryInjectionHook({
projectId,
memoryService,
logger,
config: memoryInjectionConfig,
})
const injectedMessageIds = new Set<string>()
const scopeEnum = z.enum(['convention', 'decision', 'context'])
@@ -353,8 +371,8 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
if (cleaned) return
cleaned = true
logger.log('Cleaning up plugin resources...')
memoryInjection.destroy()
await memoryService.destroy()
sessionStateService.destroy()
closeDatabase(db)
logger.log('Plugin cleanup complete')
}
@@ -376,7 +394,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
limit: z.number().optional().default(10).describe('Max results'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-read: query="${args.query ?? 'none'}", scope=${args.scope}, limit=${args.limit}`)
let results
@@ -411,7 +428,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
scope: scopeEnum.describe('Memory scope category'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-write: scope=${args.scope}, content="${args.content?.substring(0, 80)}"`)
const result = await memoryService.create({
@@ -432,11 +448,10 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
scope: scopeEnum.optional().describe('Change the scope category'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-edit: id=${args.id}, content="${args.content?.substring(0, 80)}"`)
const memory = memoryService.getById(args.id)
if (!memory) {
if (!memory || memory.projectId !== projectId) {
logger.log(`memory-edit: id=${args.id} not found`)
return withDimensionWarning(`Memory #${args.id} not found.`)
}
@@ -456,12 +471,11 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
id: z.number().describe('The memory ID to delete'),
},
execute: async (args) => {
await initPromise
const id = args.id
logger.log(`memory-delete: id=${id}`)
const memory = memoryService.getById(id)
if (!memory) {
if (!memory || memory.projectId !== projectId) {
logger.log(`memory-delete: id=${id} not found`)
return withDimensionWarning(`Memory #${id} not found.`)
}
@@ -477,157 +491,24 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
action: z.enum(['check', 'reindex']).optional().default('check').describe('Action to perform: "check" for health status, "reindex" to regenerate embeddings'),
},
execute: async (args) => {
await initPromise
if (args.action === 'reindex') {
return executeReindex(memoryService, db, config, provider, dataDir, mismatchState)
}
return withDimensionWarning(await executeHealthCheck(db, config, provider, dataDir))
},
}),
'memory-planning-update': tool({
description: 'Update the session planning state (phases, objectives, progress). Merge new fields with existing state.',
args: {
sessionID: z.string().optional().describe('Session ID to update. Defaults to current session if omitted.'),
objective: z.string().optional().describe('The main task/goal'),
current: z.string().optional().describe('Current phase or activity'),
next: z.string().optional().describe('What comes next'),
phases: z.array(z.object({
title: z.string(),
status: z.string(),
notes: z.string().optional(),
})).optional().describe('Phase list with status'),
findings: z.array(z.string()).optional().describe('Key discoveries'),
errors: z.array(z.string()).optional().describe('Errors to avoid'),
},
execute: async (args, context) => {
await initPromise
const sessionId = args.sessionID ?? context.sessionID
logger.log(`memory-planning-update: session=${sessionId}`)
const existing = sessionStateService.getPlanningState(sessionId, projectId)
const merged: typeof existing = {
...(existing ?? {}),
...(args.objective !== undefined && { objective: args.objective }),
...(args.current !== undefined && { current: args.current }),
...(args.next !== undefined && { next: args.next }),
...(args.phases !== undefined && { phases: args.phases }),
...(args.findings !== undefined && {
findings: [...new Set([...(existing?.findings ?? []), ...args.findings])]
}),
...(args.errors !== undefined && {
errors: [...new Set([...(existing?.errors ?? []), ...args.errors])]
}),
active: true,
}
sessionStateService.setPlanningState(sessionId, projectId, merged as PlanningState)
const hasPhases = merged?.phases && merged.phases.length > 0
const summary = [
merged?.objective && `objective: ${merged.objective}`,
merged?.current && `current: ${merged.current}`,
hasPhases && `${merged.phases!.length} phases`,
].filter(Boolean).join(', ')
logger.log(`memory-planning-update: stored for session ${sessionId}`)
return `Planning state updated for session ${sessionId}. ${summary || 'No data provided'}`
},
}),
'memory-planning-get': tool({
description: 'Get the current planning state for a session',
args: {
sessionID: z.string().optional().describe('Session ID to retrieve. Defaults to current session if omitted.'),
},
execute: async (args, context) => {
await initPromise
const sessionId = args.sessionID ?? context.sessionID
logger.log(`memory-planning-get: session=${sessionId}`)
const planningState = sessionStateService.getPlanningState(sessionId, projectId)
if (!planningState) {
return 'No planning state found for this session'
}
const sections: string[] = []
if (planningState.objective) sections.push(`**Objective:** ${planningState.objective}`)
if (planningState.current) sections.push(`**Current:** ${planningState.current}`)
if (planningState.next) sections.push(`**Next:** ${planningState.next}`)
if (planningState.phases && planningState.phases.length > 0) {
sections.push('\n### Phases:')
for (const phase of planningState.phases) {
const statusIcon = phase.status === 'completed' ? '[x]' : phase.status === 'in_progress' ? '[~]' : '[ ]'
const notes = phase.notes ? ` - ${phase.notes}` : ''
sections.push(`- ${statusIcon} ${phase.title}${notes}`)
if (!currentVec.available) {
return 'Reindex unavailable: vector service is still initializing. Try again in a few seconds.'
}
return executeReindex(projectId, memoryService, db, config, provider, mismatchState, currentVec)
}
if (planningState.findings && planningState.findings.length > 0) {
sections.push('\n### Key Findings:')
for (const finding of planningState.findings) {
sections.push(`- ${finding}`)
}
}
if (planningState.errors && planningState.errors.length > 0) {
sections.push('\n### Errors to Avoid:')
for (const error of planningState.errors) {
sections.push(`- ${error}`)
}
}
return sections.join('\n') || 'Planning state exists but is empty'
},
}),
'memory-planning-search': tool({
description: 'Search planning states across all sessions in the current project. Use this to find planning context from prior sessions.',
args: {
query: z.string().optional().describe('Search keyword to filter planning states. Omit to list all.'),
},
execute: async (args) => {
await initPromise
logger.log(`memory-planning-search: query="${args.query ?? 'all'}"`)
const results = args.query
? sessionStateService.searchPlanningStates(projectId, args.query)
: sessionStateService.listPlanningStates(projectId)
if (results.length === 0) {
return args.query
? `No planning states found matching "${args.query}"`
: 'No planning states found for this project'
}
const formatted = results.map(({ sessionId, planningState, updatedAt }) => {
const parts: string[] = [`**Session:** ${sessionId} (updated ${new Date(updatedAt).toISOString().split('T')[0]})`]
if (planningState.objective) parts.push(` Objective: ${planningState.objective}`)
if (planningState.current) parts.push(` Current: ${planningState.current}`)
if (planningState.next) parts.push(` Next: ${planningState.next}`)
if (planningState.phases && planningState.phases.length > 0) {
const completed = planningState.phases.filter(p => p.status === 'completed').length
parts.push(` Phases: ${completed}/${planningState.phases.length} completed`)
}
return parts.join('\n')
})
return `Found ${results.length} planning state(s):\n\n${formatted.join('\n\n')}`
const result = await executeHealthCheck(projectId, db, config, provider, dataDir)
const initInfo = `\nInit: ${initState.vecReady ? 'vec ready' : 'vec pending'}${initState.syncRunning ? ', sync in progress' : initState.syncComplete ? ', sync complete' : ''}`
return withDimensionWarning(result + initInfo)
},
}),
'memory-plan-execute': tool({
description: 'Create a new Code session, save planning state, and send the plan as the first prompt. Call this after the user approves the plan.',
description: 'Create a new Code session and send the plan as the first prompt. Call this after the user approves the plan.',
args: {
plan: z.string().describe('The full implementation plan to send to the Code agent'),
title: z.string().describe('Short title for the session (shown in session list)'),
objective: z.string().optional().describe('Short description of what we are building'),
phases: z.array(z.object({
title: z.string(),
status: z.string(),
notes: z.string().optional(),
})).optional().describe('Phases from the plan, each with status "pending"'),
findings: z.array(z.string()).optional().describe('Key architectural decisions discovered during research'),
},
execute: async (args, context) => {
await initPromise
execute: async (args) => {
logger.log(`memory-plan-execute: creating session titled "${args.title}"`)
const sessionTitle = args.title.length > 60 ? `${args.title.substring(0, 57)}...` : args.title
@@ -644,24 +525,12 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const newSessionId = createResult.data.id
logger.log(`memory-plan-execute: created session=${newSessionId}`)
const planningState: PlanningState = {
...(args.objective && { objective: args.objective }),
current: `Plan approved, sending to Code agent`,
...(args.phases && { phases: args.phases }),
...(args.findings && { findings: args.findings }),
active: true,
}
sessionStateService.setPlanningState(context.sessionID, projectId, planningState)
logger.log(`memory-plan-execute: saved planning state for session=${context.sessionID}`)
const planningInstruction = `\n\n---\n\nWhen you complete each phase, delegate to the @Memory subagent via the Task tool to update planning state. Tell it to call memory-planning-update with sessionID "${context.sessionID}". Update phase statuses as you progress (pending → in_progress → completed). Set current to describe what you're working on. When all work is done, set current to "Completed".`
const executionModel = parseModelString(config.executionModel)
const promptResult = await client.session.promptAsync({
path: { id: newSessionId },
body: {
parts: [{ type: 'text' as const, text: args.plan + planningInstruction }],
parts: [{ type: 'text' as const, text: args.plan }],
agent: 'Code',
...(executionModel && { model: executionModel }),
},
@@ -674,13 +543,6 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
logger.log(`memory-plan-execute: prompted session=${newSessionId}`)
const currentState = sessionStateService.getPlanningState(context.sessionID, projectId)
sessionStateService.setPlanningState(context.sessionID, projectId, {
...(currentState ?? planningState),
current: `Plan sent to execution session ${newSessionId}`,
})
logger.log(`memory-plan-execute: updated planning state for source session=${context.sessionID}`)
const modelInfo = executionModel ? `${executionModel.providerID}/${executionModel.modelID}` : 'default'
return `Implementation session created and plan sent.\n\nSession: ${newSessionId}\nTitle: ${sessionTitle}\nModel: ${modelInfo}\n\nSwitch to this session to begin. You can change the model from the session dropdown.`
},
@@ -699,13 +561,13 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
'experimental.session.compacting': async (input, output) => {
logger.log(`Compacting triggered`)
await sessionHooks.onCompacting(
input as { sessionID: string; branch?: string },
input as { sessionID: string },
output as { context: string[]; prompt?: string }
)
},
'experimental.chat.messages.transform': async (
_input: Record<string, never>,
output: { messages: Array<{ info: { role: string; agent?: string }; parts: Array<Record<string, unknown>> }> }
output: { messages: Array<{ info: { role: string; agent?: string; id?: string }; parts: Array<Record<string, unknown>> }> }
) => {
const messages = output.messages
let userMessage: typeof messages[number] | undefined
@@ -715,14 +577,53 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
break
}
}
if (!userMessage || userMessage.info.agent !== agents.architect.displayName) return
if (!userMessage) return
const messageId = userMessage.info.id
const alreadyInjected = messageId ? injectedMessageIds.has(messageId) : false
if (!alreadyInjected) {
const textParts = userMessage.parts
.filter((p) => p.type === 'text' && typeof p.text === 'string')
.map((p) => p.text as string)
const userText = textParts.join('\n').trim()
if (userText.length > 0) {
const memoryInjectionEnabled = config.memoryInjection?.enabled ?? true
if (memoryInjectionEnabled) {
const injected = await memoryInjection.handler(userText)
if (injected) {
userMessage.parts.push({
type: 'text',
text: injected,
synthetic: true,
})
}
}
}
if (messageId) {
injectedMessageIds.add(messageId)
if (injectedMessageIds.size > 100) {
const first = injectedMessageIds.values().next().value
if (first) injectedMessageIds.delete(first)
}
}
}
const messagesTransformEnabled = messagesTransformConfig?.enabled ?? true
if (!messagesTransformEnabled) return
const isArchitect = userMessage.info.agent === agents.architect.displayName
if (!isArchitect) return
userMessage.parts.push({
type: 'text',
text: `<system-reminder>
Plan mode is active. You MUST NOT make any file edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-health, memory-planning-get, memory-plan-execute).
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-health, memory-plan-execute).
</system-reminder>`,
synthetic: true,
})
@@ -18,7 +18,7 @@ export class EmbeddingSyncService {
private batchSize: number
private maxRetries: number
private syncInProgress: boolean = false
private static readonly MAX_ITERATIONS = 100
private static readonly MAX_ITERATIONS = 1000
constructor(memoryService: MemoryService, logger?: Logger, options: EmbeddingSyncOptions = {}) {
this.memoryService = memoryService
@@ -44,12 +44,12 @@ export class EmbeddingSyncService {
let failed = 0
try {
let pending = this.memoryService.countMemoriesWithoutEmbeddings()
let pending = await this.memoryService.countMemoriesWithoutEmbeddings()
let iterations = 0
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
iterations++
const memories = this.memoryService.getMemoriesWithoutEmbeddings(undefined, this.batchSize)
const memories = await this.memoryService.getMemoriesWithoutEmbeddings(undefined, this.batchSize)
let batchSuccess = 0
let batchFailed = 0
@@ -83,7 +83,7 @@ export class EmbeddingSyncService {
break
}
pending = this.memoryService.countMemoriesWithoutEmbeddings()
pending = await this.memoryService.countMemoriesWithoutEmbeddings()
if (pending > 0) {
this.logger?.log(`[embedding-sync] Progress: ${embedded} embedded, ${failed} failed, ${pending} remaining`)
@@ -110,12 +110,12 @@ export class EmbeddingSyncService {
let failed = 0
try {
let pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
let pending = await this.memoryService.countMemoriesWithoutEmbeddings(projectId)
let iterations = 0
while (pending > 0 && iterations < EmbeddingSyncService.MAX_ITERATIONS) {
iterations++
const memories = this.memoryService.getMemoriesWithoutEmbeddings(projectId, this.batchSize)
const memories = await this.memoryService.getMemoriesWithoutEmbeddings(projectId, this.batchSize)
let batchSuccess = 0
let batchFailed = 0
@@ -148,7 +148,7 @@ export class EmbeddingSyncService {
break
}
pending = this.memoryService.countMemoriesWithoutEmbeddings(projectId)
pending = await this.memoryService.countMemoriesWithoutEmbeddings(projectId)
}
if (iterations >= EmbeddingSyncService.MAX_ITERATIONS) {
+3 -2
View File
@@ -169,6 +169,7 @@ export class MemoryService {
}
): Promise<MemorySearchResult[]> {
const embedding = await this.embeddingService.embedText(query)
this.logger?.log(`memory-search: embedding generated (dimensions=${embedding.length}, hasSignal=${embedding.some(v => v !== 0)})`)
const results = await this.queries.search(embedding, projectId, filters)
results.forEach((r) => this.queries.trackAccess(r.memory.id))
return results
@@ -197,11 +198,11 @@ export class MemoryService {
return this.queries.countByProject(projectId)
}
getMemoriesWithoutEmbeddings(projectId?: string, limit: number = 50): Memory[] {
async getMemoriesWithoutEmbeddings(projectId?: string, limit: number = 50): Promise<Memory[]> {
return this.queries.getMemoriesWithoutEmbeddings(projectId, limit)
}
countMemoriesWithoutEmbeddings(projectId?: string): number {
async countMemoriesWithoutEmbeddings(projectId?: string): Promise<number> {
return this.queries.countMemoriesWithoutEmbeddings(projectId)
}
@@ -1,137 +0,0 @@
import type { Database } from 'bun:sqlite'
import { createSessionStateQueries } from '../storage/session-state-queries'
import type { SessionState, PlanningState, PreCompactionSnapshot } from '../types'
const DEFAULT_SESSION_TTL = 7 * 24 * 60 * 60 * 1000
const DEFAULT_SNAPSHOT_TTL = 24 * 60 * 60 * 1000
export interface PlanningStateResult {
sessionId: string
planningState: PlanningState
updatedAt: number
}
export class SessionStateService {
private queries: ReturnType<typeof createSessionStateQueries>
private cleanupInterval: ReturnType<typeof setInterval> | null = null
private logger?: { log: (msg: string, ...args: unknown[]) => void; error: (msg: string, ...args: unknown[]) => void }
constructor(db: Database, logger?: { log: (msg: string, ...args: unknown[]) => void; error: (msg: string, ...args: unknown[]) => void }) {
this.queries = createSessionStateQueries(db)
this.logger = logger
}
get<T>(key: string): T | null {
const row = this.queries.get(key)
if (!row) return null
try {
return JSON.parse(row.data) as T
} catch {
return null
}
}
set<T>(key: string, projectId: string, data: T, ttlMs?: number): void {
const expiresAt = ttlMs ? Date.now() + ttlMs : null
const jsonData = JSON.stringify(data)
this.queries.set(key, projectId, jsonData, expiresAt)
}
delete(key: string): void {
this.queries.delete(key)
}
deleteByPrefix(prefix: string): void {
this.queries.deleteByPrefix(prefix)
}
deleteExpired(): number {
return this.queries.deleteExpired()
}
listByProject(projectId: string): SessionState[] {
const rows = this.queries.listByProject(projectId)
return rows.map((row): SessionState => ({
key: row.key,
projectId: row.project_id,
data: JSON.parse(row.data),
expiresAt: row.expires_at,
createdAt: row.created_at,
updatedAt: row.updated_at,
}))
}
startCleanupInterval(intervalMs: number = 30 * 60 * 1000): void {
if (this.cleanupInterval) return
this.cleanupInterval = setInterval(() => {
try {
const deleted = this.deleteExpired()
if (deleted > 0 && this.logger) {
this.logger.log(`Cleaned up ${deleted} expired session state entries`)
}
} catch (error) {
if (this.logger) {
this.logger.error('Failed to clean up expired session state', error)
}
}
}, intervalMs)
}
stopCleanupInterval(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)
this.cleanupInterval = null
}
}
destroy(): void {
this.stopCleanupInterval()
}
setPlanningState(sessionId: string, projectId: string, planningState: PlanningState): void {
const key = `session:${projectId}:${sessionId}`
this.set(key, projectId, planningState, DEFAULT_SESSION_TTL)
}
getPlanningState(sessionId: string, projectId: string): PlanningState | null {
const key = `session:${projectId}:${sessionId}`
return this.get<PlanningState>(key)
}
listPlanningStates(projectId: string): PlanningStateResult[] {
const prefix = `session:${projectId}:`
const rows = this.queries.listByProjectAndPrefix(projectId, prefix)
return rows.map(row => ({
sessionId: row.key.slice(prefix.length),
planningState: JSON.parse(row.data) as PlanningState,
updatedAt: row.updated_at,
}))
}
searchPlanningStates(projectId: string, query: string): PlanningStateResult[] {
const prefix = `session:${projectId}:`
const rows = this.queries.searchByProjectAndPrefix(projectId, prefix, query)
return rows.map(row => ({
sessionId: row.key.slice(prefix.length),
planningState: JSON.parse(row.data) as PlanningState,
updatedAt: row.updated_at,
}))
}
setCompactionSnapshot(sessionId: string, projectId: string, snapshot: PreCompactionSnapshot): void {
const key = `compaction:snapshot:${projectId}:${sessionId}`
this.set(key, projectId, snapshot, DEFAULT_SNAPSHOT_TTL)
}
getCompactionSnapshot(sessionId: string, projectId: string): PreCompactionSnapshot | null {
const key = `compaction:snapshot:${projectId}:${sessionId}`
return this.get<PreCompactionSnapshot>(key)
}
}
export function createSessionStateService(
db: Database,
logger?: { log: (msg: string, ...args: unknown[]) => void; error: (msg: string, ...args: unknown[]) => void }
): SessionStateService {
return new SessionStateService(db, logger)
}
+2
View File
@@ -110,6 +110,8 @@ function normalizeConfig(config: PluginConfig): PluginConfig {
dedupThreshold: config.dedupThreshold,
logging: config.logging,
compaction: config.compaction,
memoryInjection: config.memoryInjection,
messagesTransform: config.messagesTransform,
executionModel: config.executionModel,
}
-14
View File
@@ -97,20 +97,6 @@ export function initializeDatabase(dataDir: string): Database {
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id)`)
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope)`)
db.run(`
CREATE TABLE IF NOT EXISTS session_state (
key TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
db.run(`CREATE INDEX IF NOT EXISTS idx_session_state_project_id ON session_state(project_id)`)
db.run(`CREATE INDEX IF NOT EXISTS idx_session_state_expires_at ON session_state(expires_at)`)
runMigrations(db)
db.run(`
+1 -7
View File
@@ -1,10 +1,7 @@
export { initializeDatabase, closeDatabase, resolveDataDir, resolveLogPath } from './database'
export { createVecService } from './vec'
export { getTableDimensions, recreateVecTable } from './vec-utils'
export type { TableDimensionsResult } from './vec-utils'
export type { VecService, VecSearchResult } from './vec-types'
export type { VecService, VecSearchResult, TableDimensionsResult } from './vec-types'
export { createMemoryQuery } from './memory-queries'
export { createSessionStateQueries } from './session-state-queries'
export { createMetadataQuery } from './metadata-queries'
export type {
@@ -15,8 +12,5 @@ export type {
MemorySearchResult,
MemoryStats,
ListMemoriesFilter,
SessionState,
PlanningState,
PreCompactionSnapshot,
CompactionConfig,
} from '../types'
+32 -85
View File
@@ -36,7 +36,15 @@ interface Logger {
export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger) {
const logError = (context: string, error?: unknown) => {
if (logger) {
logger.error(context, error)
const errorMessage = error instanceof Error ? error.message : String(error)
const errorStack = error instanceof Error ? error.stack : undefined
logger.error(context, { message: errorMessage, stack: errorStack })
}
}
const logInfo = (message: string) => {
if (logger) {
logger.log(message)
}
}
@@ -227,6 +235,7 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
: { scope: filters?.scope, limit: filters?.limit }
const memories = this.listAll(basicFilters)
logInfo(`memory-queries: vec unavailable, returning ${memories.length} unranked results`)
return memories.map(memory => ({ memory, distance: 1.0 }))
}
@@ -238,6 +247,7 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
? { projectId, scope: filters?.scope, limit: filters?.limit }
: { scope: filters?.scope, limit: filters?.limit }
const memories = this.listAll(basicFilters)
logInfo(`memory-queries: vec returned 0 results (no embeddings?), returning ${memories.length} unranked results`)
return memories.map(memory => ({ memory, distance: 1.0 }))
}
@@ -251,18 +261,23 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
WHERE id IN (${placeholders})
`).all(...memoryIds) as MemoryRow[]
return rows
const results = rows
.map(row => ({
memory: mapRow(row),
distance: distanceMap.get(row.id) ?? 1.0,
}))
.sort((a, b) => a.distance - b.distance)
} catch {
logInfo(`memory-queries: vec returned ${vecResults.length} ranked results`)
return results
} catch (error) {
logError('memory-queries: vec search error, returning unranked results', error)
const basicFilters = projectId
? { projectId, scope: filters?.scope, limit: filters?.limit }
: { scope: filters?.scope, limit: filters?.limit }
const memories = this.listAll(basicFilters)
logInfo(`memory-queries: returning ${memories.length} unranked results after error`)
return memories.map(memory => ({ memory, distance: 1.0 }))
}
},
@@ -312,93 +327,25 @@ export function createMemoryQuery(db: Database, vec: VecService, logger?: Logger
return !!result
},
getMemoriesWithoutEmbeddings(
async getMemoriesWithoutEmbeddings(
projectId?: string,
limit: number = 50
): Memory[] {
const embeddingsTableExists = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get()
): Promise<Memory[]> {
const rows = await vec.getWithoutEmbeddings(projectId, limit)
if (rows.length === 0) return []
if (!embeddingsTableExists) {
const conditions: string[] = []
const params: (string | number)[] = []
if (projectId) {
conditions.push('project_id = ?')
params.push(projectId)
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
const rows = db.prepare(`
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
FROM memories
${where}
ORDER BY created_at ASC
LIMIT ? OFFSET 0
`).all(...params, limit) as MemoryRow[]
return rows.map(mapRow)
}
const conditions: string[] = ['e.memory_id IS NULL']
const params: (string | number)[] = []
if (projectId) {
conditions.push('m.project_id = ?')
params.push(projectId)
}
const rows = db.prepare(`
SELECT m.id, m.project_id, m.scope, m.content, m.file_path, m.access_count, m.last_accessed_at, m.created_at, m.updated_at
FROM memories m
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
WHERE ${conditions.join(' AND ')}
ORDER BY m.created_at ASC
LIMIT ? OFFSET 0
`).all(...params, limit) as MemoryRow[]
return rows.map(mapRow)
const ids = rows.map(r => r.id)
const placeholders = ids.map(() => '?').join(',')
const memories = db.prepare(`
SELECT id, project_id, scope, content, file_path, access_count, last_accessed_at, created_at, updated_at
FROM memories WHERE id IN (${placeholders})
ORDER BY created_at ASC
`).all(...ids) as MemoryRow[]
return memories.map(mapRow)
},
countMemoriesWithoutEmbeddings(projectId?: string): number {
const embeddingsTableExists = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get()
if (!embeddingsTableExists) {
const conditions: string[] = []
const params: (string | number)[] = []
if (projectId) {
conditions.push('project_id = ?')
params.push(projectId)
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
const result = db.prepare(`
SELECT COUNT(*) as count FROM memories ${where}
`).get(...params) as { count: number }
return result.count
}
const conditions: string[] = ['e.memory_id IS NULL']
const params: (string | number)[] = []
if (projectId) {
conditions.push('m.project_id = ?')
params.push(projectId)
}
const result = db.prepare(`
SELECT COUNT(*) as count
FROM memories m
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
WHERE ${conditions.join(' AND ')}
`).get(...params) as { count: number }
return result.count
async countMemoriesWithoutEmbeddings(projectId?: string): Promise<number> {
return vec.countWithoutEmbeddings(projectId)
},
getByContent(projectId: string, content: string): Memory | undefined {
@@ -1,124 +0,0 @@
import type { Database } from 'bun:sqlite'
export interface SessionStateRow {
key: string
project_id: string
data: string
expires_at: number | null
created_at: number
updated_at: number
}
function mapRow(row: {
key: string
project_id: string
data: string
expires_at: number | null
created_at: number
updated_at: number
}): SessionStateRow {
return row
}
function escapeLikeWildcards(value: string): string {
return value.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_')
}
type SessionStateRowRaw = Parameters<typeof mapRow>[0]
export function createSessionStateQueries(db: Database) {
const getStmt = db.prepare(
`SELECT key, project_id, data, expires_at, created_at, updated_at
FROM session_state
WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)`
)
const setStmt = db.prepare(
`INSERT INTO session_state (key, project_id, data, expires_at, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(key) DO UPDATE SET
data = excluded.data,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at`
)
const deleteStmt = db.prepare(`DELETE FROM session_state WHERE key = ?`)
const deleteByPrefixStmt = db.prepare(
`DELETE FROM session_state WHERE key LIKE ?`
)
const deleteExpiredStmt = db.prepare(
`DELETE FROM session_state WHERE expires_at IS NOT NULL AND expires_at < ?`
)
const listByProjectStmt = db.prepare(
`SELECT key, project_id, data, expires_at, created_at, updated_at
FROM session_state
WHERE project_id = ? AND (expires_at IS NULL OR expires_at > ?)
ORDER BY updated_at DESC`
)
const searchByProjectAndPrefixStmt = db.prepare(
`SELECT key, project_id, data, expires_at, created_at, updated_at
FROM session_state
WHERE project_id = ? AND key LIKE ? AND data LIKE ? ESCAPE '\\' AND (expires_at IS NULL OR expires_at > ?)
ORDER BY updated_at DESC`
)
const listByProjectAndPrefixStmt = db.prepare(
`SELECT key, project_id, data, expires_at, created_at, updated_at
FROM session_state
WHERE project_id = ? AND key LIKE ? AND (expires_at IS NULL OR expires_at > ?)
ORDER BY updated_at DESC`
)
return {
get(key: string): SessionStateRow | undefined {
const now = Date.now()
const row = getStmt.get(key, now) as SessionStateRowRaw | null
return row ? mapRow(row) : undefined
},
set(key: string, projectId: string, data: string, expiresAt: number | null): void {
const now = Date.now()
setStmt.run(key, projectId, data, expiresAt, now, now)
},
delete(key: string): void {
deleteStmt.run(key)
},
deleteByPrefix(prefix: string): void {
const pattern = prefix.endsWith('*') ? prefix.slice(0, -1) + '%' : `${prefix}%`
deleteByPrefixStmt.run(pattern)
},
deleteExpired(): number {
const now = Date.now()
const result = deleteExpiredStmt.run(now)
return result.changes
},
listByProject(projectId: string): SessionStateRow[] {
const now = Date.now()
const rows = listByProjectStmt.all(projectId, now) as SessionStateRowRaw[]
return rows.map(mapRow)
},
searchByProjectAndPrefix(projectId: string, keyPrefix: string, searchTerm: string): SessionStateRow[] {
const now = Date.now()
const keyPattern = `${escapeLikeWildcards(keyPrefix)}%`
const searchPattern = `%${escapeLikeWildcards(searchTerm)}%`
const rows = searchByProjectAndPrefixStmt.all(projectId, keyPattern, searchPattern, now) as SessionStateRowRaw[]
return rows.map(mapRow)
},
listByProjectAndPrefix(projectId: string, keyPrefix: string): SessionStateRow[] {
const now = Date.now()
const keyPattern = `${escapeLikeWildcards(keyPrefix)}%`
const rows = listByProjectAndPrefixStmt.all(projectId, keyPattern, now) as SessionStateRowRaw[]
return rows.map(mapRow)
},
}
}
+25 -1
View File
@@ -84,7 +84,10 @@ async function startWorker(config: {
cleanupStale(pidPath, socketPath)
const workerScript = join(__dirname, 'vec-worker.ts')
const workerScriptJs = join(__dirname, 'vec-worker.js')
const workerScript = existsSync(workerScriptJs)
? workerScriptJs
: join(__dirname, 'vec-worker.ts')
const proc = spawn('bun', [
workerScript,
'--db', config.dbPath,
@@ -174,6 +177,27 @@ export async function createWorkerVecService(config: {
return resp.results as VecSearchResult[]
},
async countWithoutEmbeddings(projectId?: string): Promise<number> {
const resp = await req({ action: 'countWithoutEmbeddings', projectId })
return (resp?.count as number) ?? 0
},
async getWithoutEmbeddings(projectId?: string, limit: number = 50): Promise<Array<{ id: number; content: string }>> {
const resp = await req({ action: 'getWithoutEmbeddings', projectId, limit })
if (!resp?.rows) return []
return resp.rows as Array<{ id: number; content: string }>
},
async recreateTable(dimensions: number): Promise<void> {
await req({ action: 'recreateTable', dimensions })
},
async getDimensions(): Promise<{ exists: boolean; dimensions: number | null }> {
const resp = await req({ action: 'getDimensions' })
if (!resp) return { exists: false, dimensions: null }
return { exists: resp.exists as boolean, dimensions: (resp.dimensions as number | null) ?? null }
},
dispose() {
const pidPath = join(config.dataDir, 'vec-worker.pid')
if (existsSync(pidPath)) {
-115
View File
@@ -1,115 +0,0 @@
import type { Database } from 'bun:sqlite'
import type { VecService, VecSearchResult } from './vec-types'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
export function createDirectVecService(db: Database): VecService {
let loaded = false
try {
const { getLoadablePath } = require('sqlite-vec')
db.loadExtension(getLoadablePath())
loaded = true
} catch {
loaded = false
}
return {
get available() {
return loaded
},
async initialize(dimensions: number) {
if (!loaded) return
const exists = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get()
if (!exists) {
db.run(`
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
embedding float[${dimensions}],
+memory_id INTEGER,
+project_id TEXT
)
`)
}
},
async insert(embedding: number[], memoryId: number, projectId: string) {
if (!loaded) return
db.prepare(
'INSERT INTO memory_embeddings (embedding, memory_id, project_id) VALUES (?, ?, ?)'
).run(JSON.stringify(embedding), memoryId, projectId)
},
async delete(memoryId: number) {
if (!loaded) return
db.prepare('DELETE FROM memory_embeddings WHERE memory_id = ?').run(memoryId)
},
async deleteByProject(projectId: string) {
if (!loaded) return
db.prepare('DELETE FROM memory_embeddings WHERE project_id = ?').run(projectId)
},
async deleteByMemoryIds(memoryIds: number[]) {
if (!loaded || memoryIds.length === 0) return
const placeholders = memoryIds.map(() => '?').join(',')
db.prepare(`DELETE FROM memory_embeddings WHERE memory_id IN (${placeholders})`).run(...memoryIds)
},
async search(embedding: number[], projectId?: string, scope?: string, limit: number = 10): Promise<VecSearchResult[]> {
if (!loaded) return []
const embeddingJson = JSON.stringify(embedding)
const conditions: string[] = []
const params: (string | number)[] = [embeddingJson]
if (projectId) {
conditions.push('e.project_id = ?')
params.push(projectId)
}
if (scope) {
conditions.push('m.scope = ?')
params.push(scope)
}
params.push(limit)
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
const rows = db.prepare(`
SELECT e.memory_id, (e.embedding <=> ?) as distance
FROM memory_embeddings e
JOIN memories m ON m.id = e.memory_id
${whereClause}
ORDER BY distance
LIMIT ?
`).all(...params) as Array<{ memory_id: number; distance: number }>
return rows.map(r => ({ memoryId: r.memory_id, distance: r.distance }))
},
async findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise<VecSearchResult[]> {
if (!loaded) return []
const embeddingJson = JSON.stringify(embedding)
const rows = db.prepare(`
SELECT e.memory_id, (e.embedding <=> ?) as distance
FROM memory_embeddings e
JOIN memories m ON m.id = e.memory_id
WHERE m.project_id = ?
AND (e.embedding <=> ?) < ?
ORDER BY distance LIMIT ?
`).all(embeddingJson, projectId, embeddingJson, threshold, limit) as Array<{
memory_id: number
distance: number
}>
return rows.map(r => ({ memoryId: r.memory_id, distance: r.distance }))
},
dispose() {},
}
}
+6
View File
@@ -3,6 +3,8 @@ export interface VecSearchResult {
distance: number
}
export type TableDimensionsResult = { exists: boolean; dimensions: number | null }
export interface VecService {
readonly available: boolean
initialize(dimensions: number): Promise<void>
@@ -12,5 +14,9 @@ export interface VecService {
deleteByMemoryIds(memoryIds: number[]): Promise<void>
search(embedding: number[], projectId?: string, scope?: string, limit?: number): Promise<VecSearchResult[]>
findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise<VecSearchResult[]>
countWithoutEmbeddings(projectId?: string): Promise<number>
getWithoutEmbeddings(projectId?: string, limit?: number): Promise<Array<{ id: number; content: string }>>
recreateTable(dimensions: number): Promise<void>
getDimensions(): Promise<TableDimensionsResult>
dispose(): void
}
-27
View File
@@ -1,27 +0,0 @@
import type { Database } from 'bun:sqlite'
export type TableDimensionsResult =
| { exists: false }
| { exists: true; dimensions: number | null }
export function getTableDimensions(db: Database): TableDimensionsResult {
const row = db.prepare(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get() as { sql: string } | undefined
if (!row) return { exists: false }
const match = row.sql.match(/float\[(\d+)\]/i)
return { exists: true, dimensions: match ? parseInt(match[1]!, 10) : null }
}
export function recreateVecTable(db: Database, dimensions: number): void {
db.run('DROP TABLE IF EXISTS memory_embeddings')
db.run(`
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
embedding float[${dimensions}],
+memory_id INTEGER,
+project_id TEXT
)
`)
}
+180 -37
View File
@@ -57,7 +57,40 @@ class VecWorker {
if (!exists) {
this.db.run(`
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
embedding float[${this.config.dimensions}],
embedding float[${this.config.dimensions}] distance_metric=cosine,
+memory_id INTEGER,
+project_id TEXT
)
`)
return
}
const row = this.db.prepare(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get() as { sql: string } | undefined
if (!row) return
const match = row.sql.match(/float\[(\d+)\]/i)
const existingDimensions = match ? parseInt(match[1]!, 10) : null
if (existingDimensions !== null && existingDimensions !== this.config.dimensions) {
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
this.db.run(`
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
embedding float[${this.config.dimensions}] distance_metric=cosine,
+memory_id INTEGER,
+project_id TEXT
)
`)
return
}
if (!row.sql.includes('distance_metric=cosine')) {
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
this.db.run(`
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
embedding float[${this.config.dimensions}] distance_metric=cosine,
+memory_id INTEGER,
+project_id TEXT
)
@@ -118,7 +151,7 @@ class VecWorker {
if (!exists) {
this.db.run(`
CREATE VIRTUAL TABLE IF NOT EXISTS memory_embeddings USING vec0(
embedding float[${dims}],
embedding float[${dims}] distance_metric=cosine,
+memory_id INTEGER,
+project_id TEXT
)
@@ -165,32 +198,40 @@ class VecWorker {
const scope = req.scope as string | undefined
const limit = (req.limit as number) ?? 10
const embeddingJson = JSON.stringify(embedding)
const needsPostFilter = !!(projectId || scope)
const knnLimit = needsPostFilter ? limit * 5 : limit
const conditions: string[] = []
const params: (string | number)[] = [embeddingJson]
if (projectId) {
conditions.push('e.project_id = ?')
params.push(projectId)
}
if (scope) {
conditions.push('m.scope = ?')
params.push(scope)
}
params.push(limit)
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
const rows = this.db.prepare(`
SELECT e.memory_id, (e.embedding <=> ?) as distance
FROM memory_embeddings e
JOIN memories m ON m.id = e.memory_id
${where}
ORDER BY distance
let knnRows = this.db.prepare(`
SELECT memory_id, distance
FROM memory_embeddings
WHERE embedding MATCH ?
LIMIT ?
`).all(...params) as Array<{ memory_id: number; distance: number }>
`).all(embeddingJson, knnLimit) as Array<{ memory_id: number; distance: number }>
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
if (needsPostFilter && knnRows.length > 0) {
const ids = knnRows.map(r => r.memory_id)
const placeholders = ids.map(() => '?').join(',')
const conditions: string[] = [`id IN (${placeholders})`]
const params: (string | number)[] = [...ids]
if (projectId) {
conditions.push('project_id = ?')
params.push(projectId)
}
if (scope) {
conditions.push('scope = ?')
params.push(scope)
}
const validRows = this.db.prepare(
`SELECT id FROM memories WHERE ${conditions.join(' AND ')}`
).all(...params) as Array<{ id: number }>
const validIds = new Set(validRows.map(r => r.id))
knnRows = knnRows.filter(r => validIds.has(r.memory_id))
}
const results = knnRows.slice(0, limit)
return { results: results.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
}
case 'findSimilar': {
@@ -200,19 +241,28 @@ class VecWorker {
const limit = req.limit as number
const embeddingJson = JSON.stringify(embedding)
const rows = this.db.prepare(`
SELECT e.memory_id, (e.embedding <=> ?) as distance
FROM memory_embeddings e
JOIN memories m ON m.id = e.memory_id
WHERE m.project_id = ?
AND (e.embedding <=> ?) < ?
ORDER BY distance LIMIT ?
`).all(embeddingJson, projectId, embeddingJson, threshold, limit) as Array<{
memory_id: number
distance: number
}>
const knnRows = this.db.prepare(`
SELECT memory_id, distance
FROM memory_embeddings
WHERE embedding MATCH ?
LIMIT ?
`).all(embeddingJson, limit * 5) as Array<{ memory_id: number; distance: number }>
return { results: rows.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
const ids = knnRows.map(r => r.memory_id)
if (ids.length === 0) {
return { results: [] }
}
const placeholders = ids.map(() => '?').join(',')
const projectRows = this.db.prepare(
`SELECT id FROM memories WHERE id IN (${placeholders}) AND project_id = ?`
).all(...ids, projectId) as Array<{ id: number }>
const validIds = new Set(projectRows.map(r => r.id))
const filtered = knnRows
.filter(r => validIds.has(r.memory_id) && r.distance < threshold)
.slice(0, limit)
return { results: filtered.map(r => ({ memoryId: r.memory_id, distance: r.distance })) }
}
case 'count': {
@@ -220,6 +270,99 @@ class VecWorker {
return { count: row.count }
}
case 'countWithoutEmbeddings': {
const projectId = req.projectId as string | undefined
const embeddingsTableExists = this.db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get()
if (!embeddingsTableExists) {
const conditions: string[] = []
const params: (string | number)[] = []
if (projectId) {
conditions.push('project_id = ?')
params.push(projectId)
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
const result = this.db.prepare(`SELECT COUNT(*) as count FROM memories ${where}`).get(...params) as { count: number }
return { count: result.count }
}
const conditions: string[] = ['e.memory_id IS NULL']
const params: (string | number)[] = []
if (projectId) {
conditions.push('m.project_id = ?')
params.push(projectId)
}
const result = this.db.prepare(`
SELECT COUNT(*) as count
FROM memories m
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
WHERE ${conditions.join(' AND ')}
`).get(...params) as { count: number }
return { count: result.count }
}
case 'getWithoutEmbeddings': {
const projectId = req.projectId as string | undefined
const limit = (req.limit as number) ?? 50
const embeddingsTableExists = this.db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get()
if (!embeddingsTableExists) {
const conditions: string[] = []
const params: (string | number)[] = []
if (projectId) {
conditions.push('project_id = ?')
params.push(projectId)
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
const rows = this.db.prepare(`
SELECT id, content FROM memories ${where} ORDER BY created_at ASC LIMIT ?
`).all(...params, limit) as Array<{ id: number; content: string }>
return { rows }
}
const conditions: string[] = ['e.memory_id IS NULL']
const params: (string | number)[] = []
if (projectId) {
conditions.push('m.project_id = ?')
params.push(projectId)
}
const rows = this.db.prepare(`
SELECT m.id, m.content
FROM memories m
LEFT JOIN memory_embeddings e ON m.id = e.memory_id
WHERE ${conditions.join(' AND ')}
ORDER BY m.created_at ASC
LIMIT ?
`).all(...params, limit) as Array<{ id: number; content: string }>
return { rows }
}
case 'recreateTable': {
const dims = req.dimensions as number
this.db.run('DROP TABLE IF EXISTS memory_embeddings')
this.db.run(`
CREATE VIRTUAL TABLE memory_embeddings USING vec0(
embedding float[${dims}] distance_metric=cosine,
+memory_id INTEGER,
+project_id TEXT
)
`)
return { status: 'ok' }
}
case 'getDimensions': {
const row = this.db.prepare(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='memory_embeddings'"
).get() as { sql: string } | undefined
if (!row) return { exists: false, dimensions: null }
const match = row.sql.match(/float\[(\d+)\]/i)
return { exists: true, dimensions: match ? parseInt(match[1]!, 10) : null }
}
default:
return { error: `Unknown action: ${req.action}` }
}
+17 -28
View File
@@ -1,40 +1,25 @@
import type { Database } from 'bun:sqlite'
import { platform } from 'os'
import { join } from 'path'
import type { VecService } from './vec-types'
import { createDirectVecService } from './vec-direct'
import type { Logger } from '../types'
export type { VecService, VecSearchResult } from './vec-types'
export function initializeVecTables(db: Database, dimensions: number): void {
const direct = createDirectVecService(db)
if (direct.available) {
direct.initialize(dimensions)
}
}
export async function createVecService(db: Database, dataDir: string, dimensions: number): Promise<VecService> {
const direct = createDirectVecService(db)
if (direct.available) {
await direct.initialize(dimensions)
return direct
}
if (platform() === 'darwin') {
try {
const { createWorkerVecService } = await import('./vec-client')
const dbPath = join(dataDir, 'memory.db')
const worker = await createWorkerVecService({ dbPath, dataDir, dimensions })
if (worker.available) {
await worker.initialize(dimensions)
return worker
}
} catch {
// Worker fallback unavailable
export async function createVecService(_db: Database, dataDir: string, dimensions: number, logger?: Logger): Promise<VecService> {
try {
const { createWorkerVecService } = await import('./vec-client')
const dbPath = join(dataDir, 'memory.db')
const worker = await createWorkerVecService({ dbPath, dataDir, dimensions })
if (worker.available) {
await worker.initialize(dimensions)
return worker
}
logger?.error('Vec worker started but not available')
} catch (err) {
logger?.error('Vec worker failed to start', err)
}
logger?.log('Vec worker unavailable, using noop service')
return createNoopVecService()
}
@@ -48,6 +33,10 @@ export function createNoopVecService(): VecService {
async deleteByMemoryIds() {},
async search() { return [] },
async findSimilar() { return [] },
async countWithoutEmbeddings() { return 0 },
async getWithoutEmbeddings() { return [] },
async recreateTable() {},
async getDimensions() { return { exists: false, dimensions: null } },
dispose() {},
}
}
+18 -29
View File
@@ -50,11 +50,13 @@ export interface EmbeddingConfig {
export interface LoggingConfig {
enabled: boolean
file: string
debug?: boolean
}
export interface Logger {
log: (message: string, ...args: unknown[]) => void
error: (message: string, ...args: unknown[]) => void
debug: (message: string, ...args: unknown[]) => void
}
export interface PluginConfig {
@@ -63,6 +65,8 @@ export interface PluginConfig {
dedupThreshold?: number
logging?: LoggingConfig
compaction?: CompactionConfig
memoryInjection?: MemoryInjectionConfig
messagesTransform?: MessagesTransformConfig
executionModel?: string
}
@@ -72,38 +76,23 @@ export interface ListMemoriesFilter {
offset?: number
}
export interface SessionState {
key: string
projectId: string
data: unknown
expiresAt: number | null
createdAt: number
updatedAt: number
}
export interface PlanningState {
objective?: string
current?: string
next?: string
phases?: Array<{ title: string; status: string; notes?: string }>
findings?: string[]
errors?: string[]
active?: boolean
}
export interface PreCompactionSnapshot {
timestamp: string
sessionId: string
planningState?: PlanningState
branch?: string
activeFiles?: string[]
}
export interface CompactionConfig {
customPrompt?: boolean
inlinePlanning?: boolean
maxContextTokens?: number
snapshotToKV?: boolean
}
export interface MemoryInjectionConfig {
enabled?: boolean
maxResults?: number
distanceThreshold?: number
maxTokens?: number
cacheTtlMs?: number
debug?: boolean
}
export interface MessagesTransformConfig {
enabled?: boolean
debug?: boolean
}
export interface HealthStatus {
+27 -2
View File
@@ -26,21 +26,41 @@ function checkFileSize(filePath: string): void {
}
export function createLogger(config: LoggingConfig) {
if (!config.enabled) {
const isEnabled = config.enabled
const isDebug = config.debug ?? false
if (!isEnabled) {
return {
log: (_message: string, ..._args: unknown[]): void => {},
error: (_message: string, ..._args: unknown[]): void => {},
debug: (_message: string, ..._args: unknown[]): void => {},
}
}
const filePath = config.file
ensureLogDir(filePath)
function formatArg(arg: unknown): string {
if (arg === null) return 'null'
if (arg === undefined) return 'undefined'
if (arg instanceof Error) {
return arg.stack ?? `${arg.name}: ${arg.message}`
}
if (typeof arg === 'object') {
try {
return JSON.stringify(arg)
} catch {
return String(arg)
}
}
return String(arg)
}
function write(level: string, message: string, args: unknown[]): void {
checkFileSize(filePath)
const timestamp = new Date().toISOString()
const formattedArgs = args.length > 0 ? ' ' + args.map(a => String(a)).join(' ') : ''
const formattedArgs = args.length > 0 ? ' ' + args.map(formatArg).join(' ') : ''
const line = `${timestamp} ${level} ${PREFIX} ${message}${formattedArgs}\n`
try {
@@ -57,5 +77,10 @@ export function createLogger(config: LoggingConfig) {
error: (message: string, ...args: unknown[]): void => {
write('ERROR', message, args)
},
debug: isDebug
? (message: string, ...args: unknown[]): void => {
write('DEBUG', message, args)
}
: (_message: string, ..._args: unknown[]): void => {},
}
}
+1 -1
View File
@@ -1 +1 @@
export const VERSION = '0.0.10'
export const VERSION = '0.0.14'
+2 -77
View File
@@ -1,13 +1,11 @@
import { describe, test, expect } from 'bun:test'
import {
buildCustomCompactionPrompt,
formatPlanningState,
formatCompactionDiagnostics,
estimateTokens,
trimToTokenBudget,
extractCompactionSummary,
} from '../src/hooks/compaction-utils'
import type { PlanningState } from '../src/types'
describe('buildCustomCompactionPrompt', () => {
test('returns a non-empty string', () => {
@@ -21,82 +19,15 @@ describe('buildCustomCompactionPrompt', () => {
const prompt = buildCustomCompactionPrompt()
expect(prompt).toContain('## CRITICAL - Preserve These Verbatim')
expect(prompt).toContain('### Active Task')
expect(prompt).toContain('### Planning State')
expect(prompt).toContain('### Key Context')
expect(prompt).toContain('### Active Files')
expect(prompt).toContain('### Next Steps')
})
})
describe('formatPlanningState', () => {
test('returns null for null input', () => {
const result = formatPlanningState(null)
expect(result).toBeNull()
})
test('formats basic planning state', () => {
const planningState: PlanningState = {
objective: 'Implement feature X',
current: 'Writing code',
next: 'Run tests',
}
const result = formatPlanningState(planningState)
expect(result).toContain('**Objective:** Implement feature X')
expect(result).toContain('**Current:** Writing code')
expect(result).toContain('**Next:** Run tests')
})
test('formats phases with status', () => {
const planningState: PlanningState = {
objective: 'Test',
phases: [
{ title: 'Phase 1', status: 'completed', notes: 'Done' },
{ title: 'Phase 2', status: 'in_progress' },
{ title: 'Phase 3', status: 'pending' },
],
}
const result = formatPlanningState(planningState)
expect(result).toContain('### Phases:')
expect(result).toContain('[x] Phase 1 - Done')
expect(result).toContain('[~] Phase 2')
expect(result).toContain('[ ] Phase 3')
})
test('formats findings', () => {
const planningState: PlanningState = {
objective: 'Test',
findings: ['Found bug A', 'Performance issue'],
}
const result = formatPlanningState(planningState)
expect(result).toContain('### Key Findings:')
expect(result).toContain('- Found bug A')
expect(result).toContain('- Performance issue')
})
test('formats errors to avoid', () => {
const planningState: PlanningState = {
objective: 'Test',
errors: ['Memory leak', 'Race condition'],
}
const result = formatPlanningState(planningState)
expect(result).toContain('### Errors to Avoid:')
expect(result).toContain('- Memory leak')
expect(result).toContain('- Race condition')
})
})
describe('formatCompactionDiagnostics', () => {
test('returns empty string for zero counts', () => {
const result = formatCompactionDiagnostics({
planningPhases: 0,
conventions: 0,
decisions: 0,
tokensInjected: 0,
@@ -106,23 +37,20 @@ describe('formatCompactionDiagnostics', () => {
test('formats single items correctly', () => {
const result = formatCompactionDiagnostics({
planningPhases: 1,
conventions: 0,
conventions: 1,
decisions: 0,
tokensInjected: 100,
})
expect(result).toContain('1 planning phase')
expect(result).toContain('1 convention')
expect(result).toContain('~100 tokens injected')
})
test('formats multiple items correctly', () => {
const result = formatCompactionDiagnostics({
planningPhases: 3,
conventions: 5,
decisions: 2,
tokensInjected: 800,
})
expect(result).toContain('3 planning phases')
expect(result).toContain('5 conventions')
expect(result).toContain('2 decisions')
expect(result).toContain('~800 tokens injected')
@@ -215,6 +143,3 @@ describe('extractCompactionSummary', () => {
expect(result).toBe('Latest summary')
})
})
+9 -137
View File
@@ -1,8 +1,7 @@
import { describe, test, expect, beforeEach } from 'bun:test'
import { createSessionHooks } from '../src/hooks/session'
import type { MemoryService } from '../src/services/memory'
import type { SessionStateService } from '../src/services/session-state'
import type { Logger, Memory, MemoryScope, PlanningState } from '../src/types'
import type { Logger, Memory, MemoryScope } from '../src/types'
import type { PluginInput } from '@opencode-ai/plugin'
const TEST_PROJECT_ID = 'test-project-id'
@@ -10,20 +9,9 @@ const TEST_PROJECT_ID = 'test-project-id'
const mockLogger: Logger = {
log: () => {},
error: () => {},
debug: () => {},
}
const mockSessionStateService = {
getPlanningState: (_sessionId: string, _projectId: string) => null,
getCompactionSnapshot: (_sessionId: string, _projectId: string) => null,
setCompactionSnapshot: () => {},
} as unknown as SessionStateService
const createMockSessionStateServiceWithPlanning = (planningState: PlanningState | null): SessionStateService => ({
getPlanningState: (_sessionId: string, _projectId: string) => planningState,
getCompactionSnapshot: (_sessionId: string, _projectId: string) => null,
setCompactionSnapshot: () => {},
} as unknown as SessionStateService)
const mockPromptAsync = async () => {}
const mockPluginInput: PluginInput = {
@@ -110,7 +98,7 @@ const mockMemories: Memory[] = [
describe('SessionHooks', () => {
test('Session compacting hook includes memory sections in context', async () => {
const memoryService = createMockMemoryService(mockMemories)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, mockPluginInput)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockLogger, mockPluginInput)
const input = { sessionID: 'test-session' }
const output = { context: [] as string[] }
@@ -126,7 +114,7 @@ describe('SessionHooks', () => {
test('Session compacting hook does nothing when no memories', async () => {
const memoryService = createMockMemoryService([])
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, mockPluginInput)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockLogger, mockPluginInput)
const input = { sessionID: 'test-session' }
const output = { context: [] as string[] }
@@ -138,7 +126,7 @@ describe('SessionHooks', () => {
test('Session tracks initialized sessions', async () => {
const memoryService = createMockMemoryService([])
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, mockPluginInput)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockLogger, mockPluginInput)
const input = { sessionID: 'test-session-1' }
const output = {}
@@ -151,7 +139,7 @@ describe('SessionHooks', () => {
test('Session event handler logs session.compacted event', async () => {
const memoryService = createMockMemoryService([])
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, mockPluginInput)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockLogger, mockPluginInput)
const input = {
event: {
@@ -194,7 +182,7 @@ describe('SessionHooks', () => {
} as unknown as PluginInput
const memoryService = createMockMemoryService([])
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockLogger, customMockPluginInput)
await hooks.onEvent({
event: { type: 'session.compacted', properties: { sessionId: 'test-session-123' } },
@@ -210,126 +198,10 @@ describe('SessionHooks', () => {
expect(subtask.agent).toBe('Memory')
expect(subtask.description).toBe('Memory extraction after compaction')
expect(subtask.prompt).toContain('Compaction summary content')
expect(subtask.prompt).toContain('sessionID "test-session-123"')
expect(subtask.prompt).toContain('active work in progress')
expect(call.body.parts.length).toBe(1)
})
test('session.compacted includes planning state in subtask prompt when available', async () => {
let promptCall: unknown = null
const planningState: PlanningState = {
objective: 'Refactor memory extraction flow',
current: 'Updating buildSubtaskPrompt to accept planning state',
next: 'Run tests and verify behavior',
phases: [
{ title: 'Update buildSubtaskPrompt', status: 'completed', notes: 'Added planningState parameter' },
{ title: 'Update runPostCompactionFlow', status: 'in_progress', notes: 'Fetching from KV store' },
{ title: 'Add tests', status: 'pending' },
],
findings: ['SubtaskPart keeps session busy'],
errors: [],
}
const customMockPluginInput: PluginInput = {
client: {
session: {
messages: async () => ({
data: [
{ info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Compaction summary here' }] },
],
}),
create: async () => ({ data: { id: 'unused' } }),
prompt: async (call: unknown) => {
promptCall = call
return { data: { parts: [{ type: 'text', text: 'Done' }] } }
},
promptAsync: async () => {},
},
app: {
log: () => {},
},
},
project: { id: TEST_PROJECT_ID, worktree: '/test' },
directory: '/test',
worktree: '/test',
serverUrl: new URL('http://localhost:5551'),
} as unknown as PluginInput
const memoryService = createMockMemoryService([])
const sessionStateWithPlanning = createMockSessionStateServiceWithPlanning(planningState)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, sessionStateWithPlanning, mockLogger, customMockPluginInput)
await hooks.onEvent({
event: { type: 'session.compacted', properties: { sessionId: 'test-session-planning' } },
})
await new Promise(resolve => setTimeout(resolve, 50))
expect(promptCall).not.toBeNull()
const call = promptCall as any
const subtask = call.body.parts[0]
expect(subtask.prompt).toContain('Current Planning State')
expect(subtask.prompt).toContain('Refactor memory extraction flow')
expect(subtask.prompt).toContain('Updating buildSubtaskPrompt')
expect(subtask.prompt).toContain('[x] Update buildSubtaskPrompt')
expect(subtask.prompt).toContain('[~] Update runPostCompactionFlow')
})
test('session.compacted with active planning includes resume instruction', async () => {
let promptCall: unknown = null
const planningState: PlanningState = {
objective: 'Complete the refactor',
current: 'Running tests',
next: 'Commit changes',
phases: [
{ title: 'Phase 1', status: 'completed' },
{ title: 'Phase 2', status: 'in_progress', notes: 'Almost done' },
],
}
const customMockPluginInput: PluginInput = {
client: {
session: {
messages: async () => ({
data: [
{ info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Summary' }] },
],
}),
create: async () => ({ data: { id: 'unused' } }),
prompt: async (call: unknown) => {
promptCall = call
return { data: { parts: [{ type: 'text', text: 'Done' }] } }
},
promptAsync: async () => {},
},
app: {
log: () => {},
},
},
project: { id: TEST_PROJECT_ID, worktree: '/test' },
directory: '/test',
worktree: '/test',
serverUrl: new URL('http://localhost:5551'),
} as unknown as PluginInput
const memoryService = createMockMemoryService([])
const sessionStateWithPlanning = createMockSessionStateServiceWithPlanning(planningState)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, sessionStateWithPlanning, mockLogger, customMockPluginInput)
await hooks.onEvent({
event: { type: 'session.compacted', properties: { sessionId: 'test-session-active' } },
})
await new Promise(resolve => setTimeout(resolve, 50))
expect(promptCall).not.toBeNull()
const call = promptCall as any
expect(call.path.id).toBe('test-session-active')
expect(call.body.parts[0]?.type).toBe('subtask')
expect(call.body.parts[0]?.prompt).toContain('continue where it left off')
})
test('session.compacted with missing sessionId does NOT trigger flow', async () => {
let promptCalled = false
@@ -355,7 +227,7 @@ describe('SessionHooks', () => {
} as unknown as PluginInput
const memoryService = createMockMemoryService([])
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockLogger, customMockPluginInput)
await hooks.onEvent({
event: { type: 'session.compacted', properties: {} },
@@ -394,7 +266,7 @@ describe('SessionHooks', () => {
} as unknown as PluginInput
const memoryService = createMockMemoryService([])
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockLogger, customMockPluginInput)
await hooks.onEvent({
event: { type: 'session.compacted', properties: { sessionId: 'test-no-summary' } },
@@ -0,0 +1,359 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { createMemoryInjectionHook } from '../src/hooks/memory-injection'
import type { MemoryService } from '../src/services/memory'
import type { Logger, Memory, MemoryInjectionConfig, MemorySearchResult } from '../src/types'
const TEST_PROJECT_ID = 'test-project-id'
const mockLogger: Logger = {
log: (message: string) => {},
error: (message: string) => {},
}
function createCapturingLogger(): Logger & { logs: string[]; errors: string[] } {
const logs: string[] = []
const errors: string[] = []
return {
log: (message: string) => { logs.push(message) },
error: (message: string) => { errors.push(message) },
debug: (message: string) => {},
logs,
errors,
}
}
function createMockMemoryService(searchResults: MemorySearchResult[]): MemoryService {
return {
search: async (query: string, projectId?: string, filters?: { scope?: string; limit?: number }) => {
return searchResults.slice(0, filters?.limit ?? searchResults.length)
},
listByProject: () => [],
getById: (id: number) => undefined,
create: async () => ({ id: 1, deduplicated: false }),
update: async () => {},
delete: async () => {},
listAll: () => [],
getStats: () => ({ projectId: TEST_PROJECT_ID, total: 0, byScope: {} as Record<string, number> }),
countByProject: () => 0,
deleteByProject: () => {},
deleteByFilePath: () => {},
setDedupThreshold: () => {},
destroy: () => {},
} as unknown as MemoryService
}
const mockConvention: Memory = {
id: 1,
projectId: TEST_PROJECT_ID,
scope: 'convention',
content: 'Use 2 spaces for indentation',
filePath: null,
accessCount: 3,
lastAccessedAt: Date.now(),
createdAt: Date.now(),
updatedAt: Date.now(),
}
const mockDecision: Memory = {
id: 2,
projectId: TEST_PROJECT_ID,
scope: 'decision',
content: 'Use SQLite for local storage',
filePath: null,
accessCount: 10,
lastAccessedAt: Date.now(),
createdAt: Date.now(),
updatedAt: Date.now(),
}
const mockContext: Memory = {
id: 3,
projectId: TEST_PROJECT_ID,
scope: 'context',
content: 'Project uses Bun runtime',
filePath: null,
accessCount: 5,
lastAccessedAt: Date.now(),
createdAt: Date.now(),
updatedAt: Date.now(),
}
describe('MemoryInjectionHook', () => {
test('Injects relevant memories when search returns results below threshold', async () => {
const searchResults: MemorySearchResult[] = [
{ memory: mockConvention, distance: 0.2 },
{ memory: mockDecision, distance: 0.3 },
]
const memoryService = createMockMemoryService(searchResults)
const config: MemoryInjectionConfig = {
enabled: true,
maxResults: 5,
distanceThreshold: 0.5,
}
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
config,
})
const result = await hook.handler('How should I format my code?')
expect(result).not.toBeNull()
expect(result).toContain('<project-memory>')
expect(result).toContain('[convention]')
expect(result).toContain('[decision]')
expect(result).toContain('Use 2 spaces for indentation')
expect(result).toContain('Use SQLite for local storage')
expect(result).toContain('</project-memory>')
})
test('Returns null when no memories match (all above threshold)', async () => {
const searchResults: MemorySearchResult[] = [
{ memory: mockConvention, distance: 0.8 },
{ memory: mockDecision, distance: 0.9 },
]
const memoryService = createMockMemoryService(searchResults)
const config: MemoryInjectionConfig = {
enabled: true,
distanceThreshold: 0.5,
}
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
config,
})
const result = await hook.handler('Random unrelated query')
expect(result).toBeNull()
})
test('Returns null when search returns empty', async () => {
const memoryService = createMockMemoryService([])
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
})
const result = await hook.handler('Some query')
expect(result).toBeNull()
})
test('Respects enabled: false', async () => {
const searchResults: MemorySearchResult[] = [
{ memory: mockConvention, distance: 0.2 },
]
const memoryService = createMockMemoryService(searchResults)
const config: MemoryInjectionConfig = {
enabled: false,
}
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
config,
})
const result = await hook.handler('Some query')
expect(result).toBeNull()
})
test('Respects token budget — drops low-relevance items', async () => {
const longContent = 'This is a very long convention content that takes up many tokens. '.repeat(20)
const memories: Memory[] = []
for (let i = 0; i < 5; i++) {
memories.push({
id: i,
projectId: TEST_PROJECT_ID,
scope: 'convention',
content: longContent,
filePath: null,
accessCount: 1,
lastAccessedAt: Date.now(),
createdAt: Date.now(),
updatedAt: Date.now(),
})
}
const searchResults: MemorySearchResult[] = memories.map((m, i) => ({
memory: m,
distance: 0.1 + i * 0.05,
}))
const memoryService = createMockMemoryService(searchResults)
const config: MemoryInjectionConfig = {
enabled: true,
maxTokens: 50,
}
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
config,
})
const result = await hook.handler('convention query')
expect(result).not.toBeNull()
const resultText = result as string
const bulletCount = (resultText.match(/- \[convention\]/g) || []).length
expect(bulletCount).toBeLessThan(5)
})
test('Caches by user text — second call doesn\'t re-search', async () => {
let searchCallCount = 0
const memoryService = {
search: async (query: string, projectId?: string, filters?: { scope?: string; limit?: number }) => {
searchCallCount++
return [
{ memory: mockConvention, distance: 0.2 },
]
},
} as unknown as MemoryService
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
})
const userText = 'How should I format code?'
await hook.handler(userText)
await hook.handler(userText)
expect(searchCallCount).toBe(1)
})
test('Handles search errors gracefully', async () => {
const memoryService = {
search: async () => {
throw new Error('Database error')
},
} as unknown as MemoryService
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
})
const result = await hook.handler('Some query')
expect(result).toBeNull()
})
test('Different cache keys for different user text', async () => {
let searchCallCount = 0
const memoryService = {
search: async (query: string) => {
searchCallCount++
return [
{ memory: mockConvention, distance: 0.2 },
]
},
} as unknown as MemoryService
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
})
await hook.handler('text A')
await hook.handler('text B')
expect(searchCallCount).toBe(2)
})
test('Includes context scope in output', async () => {
const searchResults: MemorySearchResult[] = [
{ memory: mockContext, distance: 0.2 },
]
const memoryService = createMockMemoryService(searchResults)
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: mockLogger,
})
const result = await hook.handler('What runtime does this project use?')
expect(result).not.toBeNull()
expect(result).toContain('[context]')
expect(result).toContain('Project uses Bun runtime')
})
test('Logs closest distance when all results filtered by threshold', async () => {
const searchResults: MemorySearchResult[] = [
{ memory: mockConvention, distance: 0.7 },
{ memory: mockDecision, distance: 0.8 },
]
const memoryService = createMockMemoryService(searchResults)
const capturingLogger = createCapturingLogger()
const config: MemoryInjectionConfig = {
enabled: true,
distanceThreshold: 0.5,
}
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: capturingLogger,
config,
})
await hook.handler('Some query about code')
const filterLog = capturingLogger.logs.find(l => l.includes('filtered out'))
expect(filterLog).toBeDefined()
expect(filterLog).toContain('closest distance: 0.700')
expect(filterLog).toContain('threshold: 0.5')
})
test('Logs search result count', async () => {
const searchResults: MemorySearchResult[] = [
{ memory: mockConvention, distance: 0.2 },
]
const memoryService = createMockMemoryService(searchResults)
const capturingLogger = createCapturingLogger()
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: capturingLogger,
})
await hook.handler('How should I format code?')
const searchLog = capturingLogger.logs.find(l => l.includes('search returned'))
expect(searchLog).toBeDefined()
expect(searchLog).toContain('1 results')
})
test('Logs config on first invocation', async () => {
const memoryService = createMockMemoryService([])
const capturingLogger = createCapturingLogger()
const hook = createMemoryInjectionHook({
projectId: TEST_PROJECT_ID,
memoryService,
logger: capturingLogger,
})
await hook.handler('First call')
await hook.handler('Second call different text')
const initLogs = capturingLogger.logs.filter(l => l.includes('initialized'))
expect(initLogs.length).toBe(1)
})
})
+173 -5
View File
@@ -2,9 +2,9 @@ import { describe, test, expect, beforeEach, beforeAll } from 'bun:test'
import { Database } from 'bun:sqlite'
import { MemoryService } from '../src/services/memory'
import { createMemoryQuery } from '../src/storage/memory-queries'
import { initializeVecTables } from '../src/storage/vec'
import type { VecService } from '../src/storage/vec-types'
import type { EmbeddingProvider } from '../src/embedding'
import type { CacheService } from '../src/cache/types'
import type { CacheService, Logger } from '../src/types'
import type { MemoryScope } from '../src/types'
const TEST_PROJECT_ID = 'test-project-id'
@@ -99,9 +99,7 @@ describe('MemoryService', () => {
beforeEach(() => {
db = createTestDb()
initializeVecTables(db, 1536)
const queries = createMemoryQuery(db)
memoryService = new MemoryService({
db,
embeddingService: {
@@ -392,7 +390,6 @@ describe('MemoryService', () => {
}
const db2 = createTestDb()
initializeVecTables(db2, 1536)
const trackingService = new MemoryService({
db: db2,
@@ -423,4 +420,175 @@ describe('MemoryService', () => {
expect(embedTextsCalls.length).toBeGreaterThan(1)
expect(embedTextsCalls[0]!.length).toBeLessThanOrEqual(50)
})
test('search logs embedding dimensions when logger provided', async () => {
const capturingLogger: Logger & { logs: string[] } = {
logs: [],
log: (message: string) => { capturingLogger.logs.push(message) },
error: (message: string) => {},
}
const serviceWithLogger = new MemoryService({
db,
embeddingService: {
embedText: async (text: string) => {
const results = await mockEmbeddingProvider.embed([text])
return results[0]
},
embedTexts: mockEmbeddingProvider.embed.bind(mockEmbeddingProvider),
},
cache: mockCache,
logger: capturingLogger,
})
await serviceWithLogger.search('test query', TEST_PROJECT_ID)
const embeddingLog = capturingLogger.logs.find(l => l.includes('embedding generated'))
expect(embeddingLog).toBeDefined()
expect(embeddingLog).toContain('dimensions=')
expect(embeddingLog).toContain('hasSignal=')
})
})
describe('MemoryQuery search logging', () => {
let db: Database
function createTestDb(): Database {
const db = new Database(':memory:')
db.run(`
CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id TEXT NOT NULL,
scope TEXT NOT NULL,
content TEXT NOT NULL,
file_path TEXT,
access_count INTEGER NOT NULL DEFAULT 0,
last_accessed_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
db.run(`CREATE INDEX IF NOT EXISTS idx_memories_project_id ON memories(project_id)`)
return db
}
function createUnavailableVecService(): VecService {
return {
get available() { return false },
async initialize() {},
async insert() {},
async delete() {},
async deleteByProject() {},
async deleteByMemoryIds() {},
async search() { return [] },
async findSimilar() { return [] },
async countWithoutEmbeddings() { return 0 },
async getWithoutEmbeddings() { return [] },
async recreateTable() {},
async getDimensions() { return { exists: false, dimensions: null } },
dispose() {},
}
}
function createEmptyResultsVecService(): VecService {
return {
get available() { return true },
async initialize() {},
async insert() {},
async delete() {},
async deleteByProject() {},
async deleteByMemoryIds() {},
async search() { return [] },
async findSimilar() { return [] },
async countWithoutEmbeddings() { return 0 },
async getWithoutEmbeddings() { return [] },
async recreateTable() {},
async getDimensions() { return { exists: false, dimensions: null } },
dispose() {},
}
}
function createSuccessfulVecService(): VecService {
return {
get available() { return true },
async initialize() {},
async insert() {},
async delete() {},
async deleteByProject() {},
async deleteByMemoryIds() {},
async search(embedding, projectId, scope, limit) {
return [
{ memoryId: 1, distance: 0.1 },
{ memoryId: 2, distance: 0.2 },
]
},
async findSimilar() { return [] },
async countWithoutEmbeddings() { return 0 },
async getWithoutEmbeddings() { return [] },
async recreateTable() {},
async getDimensions() { return { exists: false, dimensions: null } },
dispose() {},
}
}
beforeEach(() => {
db = createTestDb()
})
test('logs when vec is unavailable', async () => {
const capturingLogger: Logger & { logs: string[]; errors: string[] } = {
logs: [],
errors: [],
log: (message: string) => { capturingLogger.logs.push(message) },
error: (message: string) => { capturingLogger.errors.push(message) },
}
const queries = createMemoryQuery(db, createUnavailableVecService(), capturingLogger)
await queries.search([0.1, 0.2, 0.3], TEST_PROJECT_ID)
const unavailableLog = capturingLogger.logs.find(l => l.includes('vec unavailable'))
expect(unavailableLog).toBeDefined()
})
test('logs when vec returns 0 results', async () => {
const capturingLogger: Logger & { logs: string[]; errors: string[] } = {
logs: [],
errors: [],
log: (message: string) => { capturingLogger.logs.push(message) },
error: (message: string) => { capturingLogger.errors.push(message) },
}
const queries = createMemoryQuery(db, createEmptyResultsVecService(), capturingLogger)
await queries.search([0.1, 0.2, 0.3], TEST_PROJECT_ID)
const emptyLog = capturingLogger.logs.find(l => l.includes('vec returned 0 results'))
expect(emptyLog).toBeDefined()
})
test('logs on successful vec search', async () => {
const capturingLogger: Logger & { logs: string[]; errors: string[] } = {
logs: [],
errors: [],
log: (message: string) => { capturingLogger.logs.push(message) },
error: (message: string) => { capturingLogger.errors.push(message) },
}
db.run(
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
[TEST_PROJECT_ID, 'context', 'test content', null, 0, Date.now(), Date.now()]
)
db.run(
'INSERT INTO memories (project_id, scope, content, file_path, access_count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
[TEST_PROJECT_ID, 'context', 'test content 2', null, 0, Date.now(), Date.now()]
)
const queries = createMemoryQuery(db, createSuccessfulVecService(), capturingLogger)
await queries.search([0.1, 0.2, 0.3], TEST_PROJECT_ID)
const successLog = capturingLogger.logs.find(l => l.includes('ranked results'))
expect(successLog).toBeDefined()
})
})
+69 -2
View File
@@ -476,8 +476,6 @@ describe('messages.transform hook', () => {
const text = userMsg.parts[1].text as string
expect(text).toContain('system-reminder')
expect(text).toContain('MUST NOT make any file edits')
expect(text).not.toContain('memory-planning-update')
expect(text).not.toContain('memory-planning-search')
})
test('does NOT inject for non-Architect agents', async () => {
@@ -518,4 +516,73 @@ describe('messages.transform hook', () => {
expect(output.messages[0].parts).toHaveLength(1)
expect(output.messages[2].parts).toHaveLength(2)
})
test('does not double-inject memory for same message id', async () => {
const output = {
messages: [
{ info: { role: 'user', id: 'msg-123' }, parts: [{ type: 'text', text: 'tell me about the project' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output)
const partsAfterFirst = output.messages[0].parts.length
await hooks['experimental.chat.messages.transform']({}, output)
const partsAfterSecond = output.messages[0].parts.length
expect(partsAfterSecond).toBe(partsAfterFirst)
})
test('processes messages without id on every call without throwing', async () => {
const output = {
messages: [
{ info: { role: 'user' }, parts: [{ type: 'text', text: 'tell me about the project' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output)
const partsAfterFirst = output.messages[0].parts.length
const output2 = {
messages: [
{ info: { role: 'user' }, parts: [{ type: 'text', text: 'tell me more' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output2)
const partsAfterSecond = output2.messages[0].parts.length
expect(partsAfterFirst).toBeGreaterThanOrEqual(1)
expect(partsAfterSecond).toBeGreaterThanOrEqual(1)
})
test('evicts oldest message id after 100 entries', async () => {
const firstId = 'msg-evict-0'
const firstOutput = {
messages: [
{ info: { role: 'user', id: firstId }, parts: [{ type: 'text', text: 'first message' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, firstOutput)
const firstInjectionParts = firstOutput.messages[0].parts.length
for (let i = 1; i <= 100; i++) {
const output = {
messages: [
{ info: { role: 'user', id: `msg-evict-${i}` }, parts: [{ type: 'text', text: `message ${i}` }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output)
}
const reOutput = {
messages: [
{ info: { role: 'user', id: firstId }, parts: [{ type: 'text', text: 'first message again' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, reOutput)
expect(reOutput.messages[0].parts.length).toBe(firstInjectionParts)
})
})
-285
View File
@@ -1,285 +0,0 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { Database } from 'bun:sqlite'
import { createSessionStateQueries } from '../src/storage/session-state-queries'
import { SessionStateService } from '../src/services/session-state'
import type { PlanningState, PreCompactionSnapshot } from '../src/types'
const TEST_DIR = '/tmp/opencode-manager-session-state-test-' + Date.now()
describe('SessionStateService', () => {
let db: Database
let service: SessionStateService
beforeEach(() => {
db = new Database(`${TEST_DIR}-${Math.random().toString(36).slice(2)}.db`)
db.run(`
CREATE TABLE IF NOT EXISTS session_state (
key TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
service = new SessionStateService(db)
})
afterEach(() => {
service.destroy()
db.close()
})
test('set and get basic values', () => {
service.set('test-key', 'project-1', { foo: 'bar' })
const result = service.get<{ foo: string }>('test-key')
expect(result).toEqual({ foo: 'bar' })
})
test('get returns null for non-existent key', () => {
const result = service.get('non-existent')
expect(result).toBeNull()
})
test('set with TTL expires correctly', async () => {
service.set('ttl-key', 'project-1', 'value', 100)
const resultBefore = service.get('ttl-key')
expect(resultBefore).toBe('value')
await new Promise(resolve => setTimeout(resolve, 150))
const resultAfter = service.get('ttl-key')
expect(resultAfter).toBeNull()
})
test('delete removes key', () => {
service.set('to-delete', 'project-1', 'value')
service.delete('to-delete')
const result = service.get('to-delete')
expect(result).toBeNull()
})
test('deleteByPrefix removes matching keys', () => {
service.set('session:abc', 'project-1', 'value1')
service.set('session:def', 'project-1', 'value2')
service.set('other:key', 'project-1', 'value3')
service.deleteByPrefix('session:*')
expect(service.get('session:abc')).toBeNull()
expect(service.get('session:def')).toBeNull()
expect(service.get('other:key')).toBe('value3')
})
test('deleteExpired cleans up expired entries', async () => {
const db2 = new Database(`${TEST_DIR}-expired-${Math.random().toString(36).slice(2)}.db`)
db2.run(`
CREATE TABLE IF NOT EXISTS session_state (
key TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
const service2 = new SessionStateService(db2)
service2.set('expired', 'project-1', 'value', 50)
service2.set('permanent', 'project-1', 'value')
await new Promise(resolve => setTimeout(resolve, 60))
const deleted = service2.deleteExpired()
expect(deleted).toBe(1)
expect(service2.get('expired')).toBeNull()
expect(service2.get('permanent')).toBe('value')
service2.destroy()
db2.close()
})
test('listByProject returns all entries for project', () => {
service.set('session:1', 'project-1', { data: '1' })
service.set('session:2', 'project-1', { data: '2' })
service.set('session:3', 'project-2', { data: '3' })
const results = service.listByProject('project-1')
expect(results.length).toBe(2)
})
test('JSON serialization round-trip for complex objects', () => {
const planningState: PlanningState = {
objective: 'Implement feature X',
current: 'Writing tests',
next: 'Deploy to production',
phases: [
{ title: 'Setup', status: 'completed', notes: 'Done' },
{ title: 'Implementation', status: 'in_progress' },
{ title: 'Testing', status: 'pending' },
],
findings: ['Found a bug', 'Performance issue'],
errors: ['Memory leak in handler'],
active: true,
}
service.set('planning:1', 'project-1', planningState)
const result = service.get<PlanningState>('planning:1')
expect(result).toEqual(planningState)
expect(result?.phases?.length).toBe(3)
expect(result?.findings?.length).toBe(2)
})
test('setPlanningState and getPlanningState convenience methods', () => {
const planningState: PlanningState = {
objective: 'Test objective',
current: 'Phase 1',
}
service.setPlanningState('session-123', 'project-1', planningState)
const result = service.getPlanningState('session-123', 'project-1')
expect(result).toEqual(planningState)
})
test('setCompactionSnapshot and getCompactionSnapshot convenience methods', () => {
const snapshot: PreCompactionSnapshot = {
timestamp: '2024-01-01T00:00:00Z',
sessionId: 'session-123',
planningState: {
objective: 'Test',
},
branch: 'main',
activeFiles: ['src/index.ts', 'src/utils.ts'],
}
service.setCompactionSnapshot('session-123', 'project-1', snapshot)
const result = service.getCompactionSnapshot('session-123', 'project-1')
expect(result).toEqual(snapshot)
expect(result?.branch).toBe('main')
expect(result?.activeFiles?.length).toBe(2)
})
test('same sessionId with different projectIds stores separate state', () => {
const state1: PlanningState = { objective: 'Project 1 objective' }
const state2: PlanningState = { objective: 'Project 2 objective' }
service.setPlanningState('session-abc', 'project-1', state1)
service.setPlanningState('session-abc', 'project-2', state2)
const result1 = service.getPlanningState('session-abc', 'project-1')
const result2 = service.getPlanningState('session-abc', 'project-2')
expect(result1).toEqual(state1)
expect(result2).toEqual(state2)
})
test('listPlanningStates returns only planning entries for the given project', () => {
service.setPlanningState('session-1', 'project-1', { objective: 'Task A' })
service.setPlanningState('session-2', 'project-1', { objective: 'Task B' })
service.setPlanningState('session-3', 'project-2', { objective: 'Task C' })
service.setCompactionSnapshot('session-1', 'project-1', {
timestamp: new Date().toISOString(),
sessionId: 'session-1',
})
const results = service.listPlanningStates('project-1')
expect(results.length).toBe(2)
expect(results.map(r => r.sessionId).sort()).toEqual(['session-1', 'session-2'])
expect(results[0]!.planningState.objective).toBeDefined()
})
test('searchPlanningStates finds matching entries by keyword', () => {
service.setPlanningState('session-1', 'project-1', {
objective: 'Refactor authentication flow',
current: 'Writing tests',
})
service.setPlanningState('session-2', 'project-1', {
objective: 'Add dark mode toggle',
current: 'Implementing CSS',
})
service.setPlanningState('session-3', 'project-1', {
objective: 'Fix authentication bug',
findings: ['Token refresh was broken'],
})
const results = service.searchPlanningStates('project-1', 'authentication')
expect(results.length).toBe(2)
const sessionIds = results.map(r => r.sessionId).sort()
expect(sessionIds).toEqual(['session-1', 'session-3'])
})
test('searchPlanningStates returns empty array when no matches', () => {
service.setPlanningState('session-1', 'project-1', { objective: 'Build feature X' })
const results = service.searchPlanningStates('project-1', 'nonexistent')
expect(results.length).toBe(0)
})
test('searchPlanningStates escapes percent wildcard in search term', () => {
service.setPlanningState('session-1', 'project-1', {
objective: '100% complete migration',
})
service.setPlanningState('session-2', 'project-1', {
objective: 'Build feature 100',
})
const results = service.searchPlanningStates('project-1', '100%')
expect(results.length).toBe(1)
expect(results[0]!.sessionId).toBe('session-1')
})
test('searchPlanningStates escapes underscore wildcard in search term', () => {
service.setPlanningState('session-1', 'project-1', {
objective: 'Fix user_name field validation',
})
service.setPlanningState('session-2', 'project-1', {
objective: 'Fix username field validation',
})
const results = service.searchPlanningStates('project-1', 'user_name')
expect(results.length).toBe(1)
expect(results[0]!.sessionId).toBe('session-1')
})
})
describe('createSessionStateQueries', () => {
let db: Database
beforeEach(() => {
db = new Database(`${TEST_DIR}-queries-${Math.random().toString(36).slice(2)}.db`)
db.run(`
CREATE TABLE IF NOT EXISTS session_state (
key TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
data TEXT NOT NULL,
expires_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
`)
})
afterEach(() => {
db.close()
})
test('set updates existing key', () => {
const queries = createSessionStateQueries(db)
queries.set('key1', 'project-1', 'value1', null)
const first = queries.get('key1')
expect(first?.data).toBe('value1')
queries.set('key1', 'project-1', 'updated-value', null)
const second = queries.get('key1')
expect(second?.data).toBe('updated-value')
})
})