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

+ How long injected memories are cached before re-querying +

+
+
+ +
+
+ + Messages Transform +
+ +
+ + handleNestedChange('messagesTransform', 'enabled', checked)} + /> +
+ +
+ + handleNestedChange('messagesTransform', 'debug', checked)} + /> +
+
+
+ {displayConfig.dataDir && (
diff --git a/package.json b/package.json index 407d1b99..eef6ea02 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"", "dev:backend": "bun --watch backend/src/index.ts", "dev:frontend": "pnpm --filter frontend dev", - "build": "pnpm run build:backend && pnpm run build:frontend", + "build": "pnpm run build:memory && pnpm run build:backend && pnpm run build:frontend", + "build:memory": "pnpm --filter @opencode-manager/memory build", "build:backend": "pnpm --filter backend build", "build:frontend": "pnpm --filter frontend build", "typecheck": "pnpm run typecheck:frontend && pnpm run typecheck:backend", diff --git a/packages/memory/CHANGELOG.md b/packages/memory/CHANGELOG.md index f188f1aa..26fbc1fe 100644 --- a/packages/memory/CHANGELOG.md +++ b/packages/memory/CHANGELOG.md @@ -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 diff --git a/packages/memory/README.md b/packages/memory/README.md index b6a333d2..7e520d4b 100644 --- a/packages/memory/README.md +++ b/packages/memory/README.md @@ -1,17 +1,56 @@ -# @opencode-manager/memory +

@opencode-manager/memory

-Memory management plugin for OpenCode that enables semantic search and persistent storage of project knowledge. +

+ Semantic memory and planning plugin for OpenCode AI agents +

+ +

+ npm + npm downloads + License +

+ +## 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 ` | Delete memories older than N days | | `--ids ` | Delete specific memory IDs | | `--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 `` 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 diff --git a/packages/memory/config.json b/packages/memory/config.json index 05a38a90..56f6420d 100644 --- a/packages/memory/config.json +++ b/packages/memory/config.json @@ -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": "" } diff --git a/packages/memory/package.json b/packages/memory/package.json index 4276d1ca..c86c90b6 100644 --- a/packages/memory/package.json +++ b/packages/memory/package.json @@ -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": { diff --git a/packages/memory/src/agents/architect.ts b/packages/memory/src/agents/architect.ts index 626360a3..2fabba57 100644 --- a/packages/memory/src/agents/architect.ts +++ b/packages/memory/src/agents/architect.ts @@ -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 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 \`\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`# [] \`. -- **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.`, } diff --git a/packages/memory/src/agents/code-review.ts b/packages/memory/src/agents/code-review.ts index 7dd0178b..b59a3e02 100644 --- a/packages/memory/src/agents/code-review.ts +++ b/packages/memory/src/agents/code-review.ts @@ -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 \`\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`# [] \`. + +- **[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.`, } diff --git a/packages/memory/src/agents/code.ts b/packages/memory/src/agents/code.ts index 09b5c979..c4203632 100644 --- a/packages/memory/src/agents/code.ts +++ b/packages/memory/src/agents/code.ts @@ -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 \`\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`# [] \`. -- **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. +`, } diff --git a/packages/memory/src/agents/memory.ts b/packages/memory/src/agents/memory.ts index 152be446..910851b1 100644 --- a/packages/memory/src/agents/memory.ts +++ b/packages/memory/src/agents/memory.ts @@ -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 \`\` blocks containing memories automatically retrieved based on semantic similarity to the current message. Each entry has the format \`# [] \`. -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.`, } diff --git a/packages/memory/src/agents/types.ts b/packages/memory/src/agents/types.ts index e32eada1..212f3c26 100644 --- a/packages/memory/src/agents/types.ts +++ b/packages/memory/src/agents/types.ts @@ -16,7 +16,7 @@ export interface AgentDefinition { } variant?: string temperature?: number - maxSteps?: number + steps?: number permission?: Record } @@ -28,7 +28,7 @@ export interface AgentConfig { tools?: Record variant?: string temperature?: number - maxSteps?: number + steps?: number hidden?: boolean color?: string permission?: Record diff --git a/packages/memory/src/cache/memory-cache.ts b/packages/memory/src/cache/memory-cache.ts index 0c6c8630..da87750d 100644 --- a/packages/memory/src/cache/memory-cache.ts +++ b/packages/memory/src/cache/memory-cache.ts @@ -9,8 +9,8 @@ export class InMemoryCacheService implements CacheService { private cache = new Map>() private cleanupInterval: ReturnType | null = null - constructor() { - this.cleanupInterval = setInterval(() => this.cleanup(), 60000) + constructor(cleanupIntervalMs: number = 60000) { + this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs) } private cleanup(): void { diff --git a/packages/memory/src/cli/commands/cleanup.ts b/packages/memory/src/cli/commands/cleanup.ts index 9d345c1a..43e9c67f 100644 --- a/packages/memory/src/cli/commands/cleanup.ts +++ b/packages/memory/src/cli/commands/cleanup.ts @@ -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 Delete memories older than N days --ids Delete specific memory IDs --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, 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, options: CleanupOptions): Promise { - 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.`) -} diff --git a/packages/memory/src/cli/commands/list.ts b/packages/memory/src/cli/commands/list.ts index ff789f04..ee17a23a 100644 --- a/packages/memory/src/cli/commands/list.ts +++ b/packages/memory/src/cli/commands/list.ts @@ -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() } diff --git a/packages/memory/src/cli/commands/stats.ts b/packages/memory/src/cli/commands/stats.ts index 49e8f015..aabaefb0 100644 --- a/packages/memory/src/cli/commands/stats.ts +++ b/packages/memory/src/cli/commands/stats.ts @@ -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() diff --git a/packages/memory/src/cli/utils.ts b/packages/memory/src/cli/utils.ts index 099878ca..ecf03a57 100644 --- a/packages/memory/src/cli/utils.ts +++ b/packages/memory/src/cli/utils.ts @@ -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)) { diff --git a/packages/memory/src/config.ts b/packages/memory/src/config.ts index 66dd701b..1d3cb476 100644 --- a/packages/memory/src/config.ts +++ b/packages/memory/src/config.ts @@ -6,9 +6,6 @@ const ENHANCED_BUILTIN_AGENTS: Record } 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): 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 } : {}), diff --git a/packages/memory/src/embedding/shared.ts b/packages/memory/src/embedding/shared.ts index 4328e065..0d2a348f 100644 --- a/packages/memory/src/embedding/shared.ts +++ b/packages/memory/src/embedding/shared.ts @@ -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) { diff --git a/packages/memory/src/hooks/compaction-utils.ts b/packages/memory/src/hooks/compaction-utils.ts index 946c5a71..ff2a4430 100644 --- a/packages/memory/src/hooks/compaction-utils.ts +++ b/packages/memory/src/hooks/compaction-utils.ts @@ -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' : ''}`) } diff --git a/packages/memory/src/hooks/index.ts b/packages/memory/src/hooks/index.ts index ba1f0729..a2f8cb65 100644 --- a/packages/memory/src/hooks/index.ts +++ b/packages/memory/src/hooks/index.ts @@ -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' diff --git a/packages/memory/src/hooks/memory-injection.ts b/packages/memory/src/hooks/memory-injection.ts new file mode 100644 index 00000000..7a1749d5 --- /dev/null +++ b/packages/memory/src/hooks/memory-injection.ts @@ -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 { + 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 + 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 => { + 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(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('') + + for (const result of filteredResults) { + const { memory } = result + sections.push(`- #${memory.id} [${memory.scope}] ${memory.content}`) + } + + sections.push('') + + let formatted = sections.join('\n') + let tokens = estimateTokens(formatted) + + if (tokens > maxTokens) { + const trimmedSections: string[] = [] + trimmedSections.push('') + + let currentTokens = estimateTokens('') + 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('')) { + break + } + + trimmedSections.push(line) + currentTokens += lineTokens + } + + trimmedSections.push('') + 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(), + } +} diff --git a/packages/memory/src/hooks/session.ts b/packages/memory/src/hooks/session.ts index 87524f7f..81cf76ba 100644 --- a/packages/memory/src/hooks/session.ts +++ b/packages/memory/src/hooks/session.ts @@ -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 { } 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')), diff --git a/packages/memory/src/index.ts b/packages/memory/src/index.ts index 9d2e15ce..cb5c5701 100644 --- a/packages/memory/src/index.ts +++ b/packages/memory/src/index.ts @@ -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 { - 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 { 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 { - 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() 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, - output: { messages: Array<{ info: { role: string; agent?: string }; parts: Array> }> } + output: { messages: Array<{ info: { role: string; agent?: string; id?: string }; parts: Array> }> } ) => { 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: ` 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). `, synthetic: true, }) diff --git a/packages/memory/src/services/embedding-sync.ts b/packages/memory/src/services/embedding-sync.ts index 4ea2c604..4082eb78 100644 --- a/packages/memory/src/services/embedding-sync.ts +++ b/packages/memory/src/services/embedding-sync.ts @@ -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) { diff --git a/packages/memory/src/services/memory.ts b/packages/memory/src/services/memory.ts index 754cfe1a..4adcc19d 100644 --- a/packages/memory/src/services/memory.ts +++ b/packages/memory/src/services/memory.ts @@ -169,6 +169,7 @@ export class MemoryService { } ): Promise { 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 { return this.queries.getMemoriesWithoutEmbeddings(projectId, limit) } - countMemoriesWithoutEmbeddings(projectId?: string): number { + async countMemoriesWithoutEmbeddings(projectId?: string): Promise { return this.queries.countMemoriesWithoutEmbeddings(projectId) } diff --git a/packages/memory/src/services/session-state.ts b/packages/memory/src/services/session-state.ts deleted file mode 100644 index 50dc1d04..00000000 --- a/packages/memory/src/services/session-state.ts +++ /dev/null @@ -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 - private cleanupInterval: ReturnType | 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(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(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(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(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) -} diff --git a/packages/memory/src/setup.ts b/packages/memory/src/setup.ts index e1f726e3..8b0d7d2e 100644 --- a/packages/memory/src/setup.ts +++ b/packages/memory/src/setup.ts @@ -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, } diff --git a/packages/memory/src/storage/database.ts b/packages/memory/src/storage/database.ts index eb03e28a..b07f0988 100644 --- a/packages/memory/src/storage/database.ts +++ b/packages/memory/src/storage/database.ts @@ -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(` diff --git a/packages/memory/src/storage/index.ts b/packages/memory/src/storage/index.ts index 5904f61f..f3b111f9 100644 --- a/packages/memory/src/storage/index.ts +++ b/packages/memory/src/storage/index.ts @@ -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' diff --git a/packages/memory/src/storage/memory-queries.ts b/packages/memory/src/storage/memory-queries.ts index 8f7ce577..c430f5eb 100644 --- a/packages/memory/src/storage/memory-queries.ts +++ b/packages/memory/src/storage/memory-queries.ts @@ -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 { + 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 { + return vec.countWithoutEmbeddings(projectId) }, getByContent(projectId: string, content: string): Memory | undefined { diff --git a/packages/memory/src/storage/session-state-queries.ts b/packages/memory/src/storage/session-state-queries.ts deleted file mode 100644 index 476e994f..00000000 --- a/packages/memory/src/storage/session-state-queries.ts +++ /dev/null @@ -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[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) - }, - } -} diff --git a/packages/memory/src/storage/vec-client.ts b/packages/memory/src/storage/vec-client.ts index 2abf696c..ac4de9c5 100644 --- a/packages/memory/src/storage/vec-client.ts +++ b/packages/memory/src/storage/vec-client.ts @@ -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 { + const resp = await req({ action: 'countWithoutEmbeddings', projectId }) + return (resp?.count as number) ?? 0 + }, + + async getWithoutEmbeddings(projectId?: string, limit: number = 50): Promise> { + 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 { + 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)) { diff --git a/packages/memory/src/storage/vec-direct.ts b/packages/memory/src/storage/vec-direct.ts deleted file mode 100644 index 01975bfe..00000000 --- a/packages/memory/src/storage/vec-direct.ts +++ /dev/null @@ -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 { - 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 { - 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() {}, - } -} diff --git a/packages/memory/src/storage/vec-types.ts b/packages/memory/src/storage/vec-types.ts index 3ade0f4a..76c00698 100644 --- a/packages/memory/src/storage/vec-types.ts +++ b/packages/memory/src/storage/vec-types.ts @@ -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 @@ -12,5 +14,9 @@ export interface VecService { deleteByMemoryIds(memoryIds: number[]): Promise search(embedding: number[], projectId?: string, scope?: string, limit?: number): Promise findSimilar(embedding: number[], projectId: string, threshold: number, limit: number): Promise + countWithoutEmbeddings(projectId?: string): Promise + getWithoutEmbeddings(projectId?: string, limit?: number): Promise> + recreateTable(dimensions: number): Promise + getDimensions(): Promise dispose(): void } diff --git a/packages/memory/src/storage/vec-utils.ts b/packages/memory/src/storage/vec-utils.ts deleted file mode 100644 index 2d633c73..00000000 --- a/packages/memory/src/storage/vec-utils.ts +++ /dev/null @@ -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 - ) - `) -} diff --git a/packages/memory/src/storage/vec-worker.ts b/packages/memory/src/storage/vec-worker.ts index 3c48ea09..dfb76699 100644 --- a/packages/memory/src/storage/vec-worker.ts +++ b/packages/memory/src/storage/vec-worker.ts @@ -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}` } } diff --git a/packages/memory/src/storage/vec.ts b/packages/memory/src/storage/vec.ts index b6b61673..aa302d89 100644 --- a/packages/memory/src/storage/vec.ts +++ b/packages/memory/src/storage/vec.ts @@ -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 { - 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 { + 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() {}, } } diff --git a/packages/memory/src/types.ts b/packages/memory/src/types.ts index bbef4883..61e8e2c9 100644 --- a/packages/memory/src/types.ts +++ b/packages/memory/src/types.ts @@ -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 { diff --git a/packages/memory/src/utils/logger.ts b/packages/memory/src/utils/logger.ts index 2457191d..10afac0a 100644 --- a/packages/memory/src/utils/logger.ts +++ b/packages/memory/src/utils/logger.ts @@ -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 => {}, } } diff --git a/packages/memory/src/version.ts b/packages/memory/src/version.ts index ce00bcf4..9d936c72 100644 --- a/packages/memory/src/version.ts +++ b/packages/memory/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.0.10' +export const VERSION = '0.0.14' diff --git a/packages/memory/test/compaction-utils.test.ts b/packages/memory/test/compaction-utils.test.ts index f064f213..ca4d6acd 100644 --- a/packages/memory/test/compaction-utils.test.ts +++ b/packages/memory/test/compaction-utils.test.ts @@ -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') }) }) - - - diff --git a/packages/memory/test/hooks.test.ts b/packages/memory/test/hooks.test.ts index 55c99616..3b83f500 100644 --- a/packages/memory/test/hooks.test.ts +++ b/packages/memory/test/hooks.test.ts @@ -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' } }, diff --git a/packages/memory/test/memory-injection.test.ts b/packages/memory/test/memory-injection.test.ts new file mode 100644 index 00000000..f0454120 --- /dev/null +++ b/packages/memory/test/memory-injection.test.ts @@ -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 }), + 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('') + 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('') + }) + + 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) + }) +}) diff --git a/packages/memory/test/memory-service.test.ts b/packages/memory/test/memory-service.test.ts index 676f4e0a..ac9134a4 100644 --- a/packages/memory/test/memory-service.test.ts +++ b/packages/memory/test/memory-service.test.ts @@ -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() + }) }) diff --git a/packages/memory/test/plugin.test.ts b/packages/memory/test/plugin.test.ts index 505afb36..ecc17574 100644 --- a/packages/memory/test/plugin.test.ts +++ b/packages/memory/test/plugin.test.ts @@ -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) + }) }) diff --git a/packages/memory/test/session-state.test.ts b/packages/memory/test/session-state.test.ts deleted file mode 100644 index 50543bfc..00000000 --- a/packages/memory/test/session-state.test.ts +++ /dev/null @@ -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('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') - }) -}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index afe7b6f2..c8f22075 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -282,8 +282,8 @@ importers: specifier: ^3.8.1 version: 3.8.1 '@opencode-ai/plugin': - specifier: ^1.2.9 - version: 1.2.10 + specifier: ^1.2.16 + version: 1.2.16 sqlite-vec: specifier: 0.1.7-alpha.2 version: 0.1.7-alpha.2 @@ -991,11 +991,11 @@ packages: resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==} engines: {node: '>= 20.19.0'} - '@opencode-ai/plugin@1.2.10': - resolution: {integrity: sha512-Z1BMqNHnD8AGAEb+kUz0b2SOuiODwdQLdCA4aVGTXqkGzhiD44OVxr85MeoJ5AMTnnea9SnJ3jp9GAQ5riXA5g==} + '@opencode-ai/plugin@1.2.16': + resolution: {integrity: sha512-9Kb7BQIC2P3oKCvI8K3thP5YP0vE7yLvcmBmgyACUIqc3e5UL6U+4umLpTvgQa2eQdjxtOXznuGTNwgcGMHUHg==} - '@opencode-ai/sdk@1.2.10': - resolution: {integrity: sha512-SyXcVqry2hitPVvQtvXOhqsWyFhSycG/+LTLYXrcq8AFmd9FR7dyBSDB3f5Ol6IPkYOegk8P2Eg2kKPNSNiKGw==} + '@opencode-ai/sdk@1.2.16': + resolution: {integrity: sha512-y9ae9VnCcuog0GaI4DveX1HB6DBoZgGN3EuJVlRFbBCPwhzkls6fCfHSb5+VnTS6Fy0OWFUL28VBCmixL/D+/Q==} '@peculiar/asn1-android@2.6.0': resolution: {integrity: sha512-cBRCKtYPF7vJGN76/yG8VbxRcHLPF3HnkoHhKOZeHpoVtbMYfY9ROKtH3DtYUY9m8uI1Mh47PRhHf2hSK3xcSQ==} @@ -4940,12 +4940,12 @@ snapshots: '@noble/hashes@2.0.1': {} - '@opencode-ai/plugin@1.2.10': + '@opencode-ai/plugin@1.2.16': dependencies: - '@opencode-ai/sdk': 1.2.10 + '@opencode-ai/sdk': 1.2.16 zod: 4.1.8 - '@opencode-ai/sdk@1.2.10': {} + '@opencode-ai/sdk@1.2.16': {} '@peculiar/asn1-android@2.6.0': dependencies: diff --git a/shared/src/schemas/memory.ts b/shared/src/schemas/memory.ts index 61618f99..3d089c61 100644 --- a/shared/src/schemas/memory.ts +++ b/shared/src/schemas/memory.ts @@ -60,14 +60,40 @@ export type EmbeddingConfig = z.infer export const LoggingConfigSchema = z.object({ enabled: z.boolean(), file: z.string().optional(), + debug: z.boolean().optional(), }) export type LoggingConfig = z.infer +export const CompactionConfigSchema = z.object({ + customPrompt: z.boolean().optional(), + maxContextTokens: z.number().optional(), +}) +export type CompactionConfig = z.infer + +export const MemoryInjectionConfigSchema = z.object({ + enabled: z.boolean().optional(), + maxResults: z.number().optional(), + distanceThreshold: z.number().optional(), + maxTokens: z.number().optional(), + cacheTtlMs: z.number().optional(), + debug: z.boolean().optional(), +}) +export type MemoryInjectionConfig = z.infer + +export const MessagesTransformConfigSchema = z.object({ + enabled: z.boolean().optional(), + debug: z.boolean().optional(), +}) +export type MessagesTransformConfig = z.infer + export const PluginConfigSchema = z.object({ dataDir: z.string().optional(), embedding: EmbeddingConfigSchema, dedupThreshold: z.number().min(0).max(1).default(0.25), logging: LoggingConfigSchema.optional(), + compaction: CompactionConfigSchema.optional(), + memoryInjection: MemoryInjectionConfigSchema.optional(), + messagesTransform: MessagesTransformConfigSchema.optional(), executionModel: z.string().optional(), }) export type PluginConfig = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index f27a1446..7326e943 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -86,5 +86,8 @@ export type { EmbeddingProviderType, EmbeddingConfig, LoggingConfig, + CompactionConfig, + MemoryInjectionConfig, + MessagesTransformConfig, PluginConfig, } from '../schemas/memory'