From 524975537b1ebf3b813e40cdfd47c41b477bbe91 Mon Sep 17 00:00:00 2001 From: xuli500177 <62830942+xuli500177@users.noreply.github.com> Date: Thu, 7 May 2026 22:01:51 -0400 Subject: [PATCH 01/24] feat: OpenCode plugin with 22 auto-capture hooks (closes #156) - 22 hook handlers across session lifecycle, messages, tool lifecycle, parts, files, permissions, tasks, commands, and config - Two-layer enrichment pipeline: /context + /enrich via system.transform - Two slash commands: /recall and /remember - Full Claude Code hook parity documented with gap analysis --- README.md | 14 +- ROADMAP.md | 2 +- plugin/opencode/README.md | 182 +++++++++ plugin/opencode/agentmemory-capture.ts | 546 +++++++++++++++++++++++++ plugin/opencode/commands/recall.md | 19 + plugin/opencode/commands/remember.md | 19 + plugin/opencode/plugin.json | 12 + 7 files changed, 790 insertions(+), 4 deletions(-) create mode 100644 plugin/opencode/README.md create mode 100644 plugin/opencode/agentmemory-capture.ts create mode 100644 plugin/opencode/commands/recall.md create mode 100644 plugin/opencode/commands/remember.md create mode 100644 plugin/opencode/plugin.json diff --git a/README.md b/README.md index eff3339bb9..0d98edfb77 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ agentmemory works with any agent that supports hooks, MCP, or REST API. All agen OpenCode
OpenCode
-MCP server +22 hooks + MCP + plugin Codex CLI
@@ -393,7 +393,7 @@ Then add the MCP config for your agent: | **Gemini CLI** | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` | | **Codex CLI** | `codex mcp add agentmemory -- npx -y @agentmemory/mcp` or add `[mcp_servers.agentmemory]` to `.codex/config.toml` | | **pi** | Copy [`integrations/pi`](integrations/pi/) to `~/.pi/agent/extensions/agentmemory` and restart pi | -| **OpenCode** | Add to `opencode.json`: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}` | +| **OpenCode** | Add to `opencode.json`: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}` + copy `plugin/opencode/` for 22 auto-capture hooks | | **Hermes Agent** | Add to `~/.hermes/config.yaml` with `memory.provider: agentmemory` or use the [memory provider plugin](integrations/hermes/) | | **Cline / Goose / Kilo Code** | Add MCP server in settings | | **Claude Desktop** | Add to `claude_desktop_config.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "@agentmemory/mcp"]}}}` | @@ -712,10 +712,18 @@ OpenCode (`opencode.json`): "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true } - } + }, + "plugin": ["./plugins/agentmemory-capture.ts"] } ``` +Copy the plugin file from the repo: +```bash +mkdir -p ~/.config/opencode/plugins +cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/ +cp plugin/opencode/commands/*.md ~/.config/opencode/commands/ +``` + ---

Real-Time Viewer

diff --git a/ROADMAP.md b/ROADMAP.md index 66fb546737..f77f371d7c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -37,7 +37,7 @@ Anything not on this list that a contributor wants to pursue is welcome — open ### Planned - [ ] **GitHub connector** (`@agentmemory/github-watcher`) — sync issues, PRs, discussions as observations. Shares the `POST /agentmemory/observe` wire format with the filesystem connector. -- [ ] **OpenCode hook bus** (#156) — if upstream ships hook events, wire them; otherwise ship a REST-polling adapter. +- [x] **OpenCode hook bus** (#156) — wired 22 hooks covering all 12 Claude Code hook types: session lifecycle (create/idle/status/compacted/update/diff/delete/error), messages & prompts (chat.message, message.updated user+assistant, message.removed), tool capture (before + rich ToolPart lifecycle in message.part.updated), memory injection (context + enrich via system.transform), part tracking (subtask, step-finish, reasoning, file, patch, compaction, agent, retry), file enrichment pipeline (stash via tool.execute.before + file.edited + file parts), permissions (updated + replied), task tracking (todo.updated w/ priority), commands (command.executed), config & model tracking (config + chat.params). Plus 2 slash commands (recall/remember). See `plugin/opencode/`. - [ ] **Session replay UI** in the real-time viewer — scrub the timeline, inspect per-observation payloads. - [ ] **Benchmark harness in CI** — keep the 95.2% R@5 number honest across releases by re-running LongMemEval-S on every minor tag. diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md new file mode 100644 index 0000000000..cde13ba297 --- /dev/null +++ b/plugin/opencode/README.md @@ -0,0 +1,182 @@ +

+ OpenCode +  agentmemory for OpenCode +

+ +

+ Your OpenCode agents remember everything. No more re-explaining.
+ Persistent cross-session memory via agentmemory — 95.2% retrieval accuracy on LongMemEval-S. +

+ +

+ 44 MCP tools + 22 hooks + 2 slash commands + 95.2% R@5 +

+ +--- + +## Quick start + +### 1. Start the agentmemory server + +```bash +npx @agentmemory/agentmemory +``` + +The server starts on `http://localhost:3111`. + +### 2. Configure the MCP server + +Add to `~/.config/opencode/opencode.json` or your project's `.opencode/opencode.json`: + +```json +{ + "mcp": { + "agentmemory": { + "type": "local", + "command": ["npx", "-y", "@agentmemory/mcp"], + "enabled": true + } + } +} +``` + +### 3. Install the plugin + +Add to `~/.config/opencode/opencode.json`: + +```json +{ + "plugin": ["./plugins/agentmemory-capture.ts"] +} +``` + +Copy the plugin file from this repo: + +```bash +mkdir -p ~/.config/opencode/plugins +cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/ +``` + +### 4. Add the slash commands + +Copy the commands into your project or global `.opencode/commands/` directory: + +```bash +mkdir -p ~/.config/opencode/commands +cp plugin/opencode/commands/recall.md ~/.config/opencode/commands/ +cp plugin/opencode/commands/remember.md ~/.config/opencode/commands/ +``` + +Restart OpenCode or open a new session. The plugin auto-captures everything. + +## What gets captured + +### Session lifecycle + +| Event | Hook | agentmemory API | +|---|---|---| +| Session start | `session.created` | POST /session/start | +| Idle → summarize | `session.idle` + `session.status` (idle) | POST /summarize | +| Status transitions | `session.status` (idle/busy/retry) | POST /observe | +| Compaction | `session.compacted` | POST /summarize + POST /observe | +| Metadata updates | `session.updated` | POST /observe | +| Code change tracking | `session.diff` | POST /observe | +| Session delete | `session.deleted` | POST /session/end | +| Session error | `session.error` | POST /observe | + +### Messages & prompts + +| Event | Hook | agentmemory API | +|---|---|---| +| User prompt (rich) | `chat.message` | POST /observe | +| User prompt metadata | `message.updated` (user) | POST /observe | +| Assistant response | `message.updated` (assistant) | POST /observe | +| Message removed (undo) | `message.removed` | POST /observe | + +### Parts & steps + +| Event | Hook | agentmemory API | +|---|---|---| +| Subagent start | `message.part.updated` (subtask) | POST /observe | +| Tool completed | `message.part.updated` (tool completed) | POST /observe | +| Tool error | `message.part.updated` (tool error) | POST /observe | +| Step finish (cost/tokens) | `message.part.updated` (step-finish) | POST /observe | +| Reasoning trace | `message.part.updated` (reasoning) | POST /observe | +| Patch applied | `message.part.updated` (patch) | POST /observe | +| Auto/manual compaction | `message.part.updated` (compaction) | POST /observe | +| Agent selection | `message.part.updated` (agent) | POST /observe | +| API retry | `message.part.updated` (retry) | POST /observe | + +### File enrichment pipeline + +| Event | Hook | agentmemory API | +|---|---|---| +| File tool params | `tool.execute.before` → stash paths | — | +| File edited | `file.edited` → stash paths | — | +| File part attached | `message.part.updated` (file) → stash paths | — | +| Enrichment inject | `experimental.chat.system.transform` | POST /enrich → `output.system[]` | +| Memory context inject | `experimental.chat.system.transform` | POST /context → `output.system[]` | + +### Permissions + +| Event | Hook | agentmemory API | +|---|---|---| +| Permission prompt | `permission.updated` | POST /observe | +| Permission reply | `permission.replied` | POST /observe | + +### Tasks & commands + +| Event | Hook | agentmemory API | +|---|---|---| +| Task tracking (w/ priority) | `todo.updated` | POST /observe | +| Command executed | `command.executed` | POST /observe | + +### Model & config + +| Event | Hook | agentmemory API | +|---|---|---| +| LLM parameters | `chat.params` | POST /observe | +| Config loaded | `config` | POST /observe | +| Compaction (WIP) | `experimental.session.compacting` | POST /context → `output.context[]` | + +### File enrichment + memory injection (two-layer pipeline) + +`experimental.chat.system.transform` fires before every LLM call and injects two layers of context: + +1. **Memory context** (once per session): calls `/agentmemory/context` and injects project profile, recent session summaries, and important past observations into the system prompt. This is the OpenCode equivalent of Claude's MEMORY.md bridge — instead of syncing to a markdown file, context is injected directly into the system prompt. + +2. **File enrichment** (every turn with stashed files): calls `/agentmemory/enrich` with files stashed by `tool.execute.before`, `file.edited`, and `message.part.updated` (file parts). File-specific context (past observations, related bugs, semantic search) is injected into the system prompt. + +``` +System prompt = [OpenCode instructions] + [memory context] + [file enrichment] + [user message] + ^ ^ + first turn only every file-touching turn +``` + +**Differences from Claude's PreToolUse:** + +| Dimension | Claude (PreToolUse) | OpenCode (two-hop pipeline) | +|---|---|---| +| Injection mechanism | stdout → context window | `output.system[]` → system prompt | +| Timing | Same turn (parallel with tool) | Next turn (before next LLM call) | +| File set | Per-tool (immediate) | Batched (all files since last enrichment) | +| Coverage | Edit/Write/Read/Glob/Grep only | Edit/Write/Read/Glob/Grep only | +| What gets injected | `` + bug memories | Identical `/enrich` response | + +## Slash commands + +- `/recall ` — Search past observations and lessons +- `/remember ` — Save an insight to long-term memory + +## What's not covered (vs Claude Code plugin) + +| Claude feature | Reason | +|---|---| +| SubagentStop | No explicit subtask-completion event; stop boundary is inferred from the observation timeline by the memory system | +| TaskCompleted | No team/teammate concept in OpenCode; `todo.updated` captures task state changes as a partial equivalent | +| Stop | `session.compacted` event handler exists; `experimental.session.compacting` injection hook defined in SDK but Go binary (v1.14.41) doesn't wire it — will auto-activate when upstream implements it | + +All other Claude Code hooks have direct or pipeline equivalents in this plugin. 12 of 12 Claude hook types covered. diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts new file mode 100644 index 0000000000..8eff1eaf13 --- /dev/null +++ b/plugin/opencode/agentmemory-capture.ts @@ -0,0 +1,546 @@ +import type { Plugin } from "@opencode-ai/plugin"; + +const API = process.env.AGENTMEMORY_URL || "http://localhost:3111"; +const FILE_TOOLS = new Set(["Read", "Write", "Edit", "Glob", "Grep"]); +const FILE_KEYS = ["filePath", "file_path", "path", "file", "pattern"]; +const MAX_STASHED_FILES = 20; + +async function post(path: string, body: Record): Promise { + try { + await fetch(`${API}/agentmemory${path}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(5000), + }); + } catch {} +} + +async function postJson(path: string, body: Record): Promise { + try { + const res = await fetch(`${API}/agentmemory${path}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(5000), + }); + return res.ok ? res.json() : null; + } catch { + return null; + } +} + +async function observe( + sessionId: string, + hookType: string, + data: Record, +): Promise { + await post("/observe", { + hookType, + sessionId, + project: projectPath, + cwd: projectPath, + timestamp: new Date().toISOString(), + data, + }); +} + +let activeSessionId: string | null = null; +let projectPath: string | null = null; +const stashedFiles = new Set(); +const seenSubtaskIds = new Set(); +const contextInjectedSessions = new Set(); +const seenToolCallIds = new Set(); + +function extractFilePaths(args: Record): string[] { + const files: string[] = []; + for (const key of FILE_KEYS) { + const val = args[key]; + if (typeof val === "string" && val.length > 0) { + files.push(val); + } + } + return files; +} + +function extractErrorMessage(err: unknown): string { + if (typeof err === "string") return err; + if (err && typeof err === "object") { + const e = err as Record; + if (typeof e.message === "string") return e.message; + if (e.data && typeof e.data === "object") { + const d = e.data as Record; + if (typeof d.message === "string") return d.message; + } + if (typeof e.name === "string") return e.name; + try { return JSON.stringify(err); } catch { return ""; } + } + return String(err || ""); +} + +export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { + projectPath = ctx.project?.id || ctx.worktree || null; + + return { + event: async ({ event }) => { + const type = event.type; + const props = (event as any).properties || {}; + + // ── session.created ── + if (type === "session.created") { + const info = props.info as Record | undefined; + activeSessionId = (info?.id as string) || props.sessionID || null; + stashedFiles.clear(); + seenSubtaskIds.clear(); + seenToolCallIds.clear(); + if (activeSessionId) { + contextInjectedSessions.delete(activeSessionId); + } + await post("/session/start", { + sessionId: activeSessionId, + title: info?.title ?? null, + parentID: info?.parentID ?? null, + version: info?.version ?? null, + project: projectPath, + cwd: projectPath, + }); + } + + // ── session.idle ── + if (type === "session.idle") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await post("/summarize", { sessionId: sid }); + } + } + + // ── session.status ── + if (type === "session.status") { + const status = props.status as Record | undefined; + const sid = props.sessionID || activeSessionId; + if (!sid || !status) return; + if (status.type === "idle") { + await post("/summarize", { sessionId: sid }); + } + await observe(sid, "session_status", { + status_type: status.type, + attempt: status.attempt ?? null, + message: ((status.message as string) || "").slice(0, 2000), + }); + } + + // ── session.compacted ── + if (type === "session.compacted") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await post("/summarize", { sessionId: sid }); + await observe(sid, "session_compacted", {}); + } + } + + // ── session.updated ── + if (type === "session.updated") { + const info = props.info as Record | undefined; + const sid = (info?.id as string) || props.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "session_updated", { + title: info?.title ?? null, + parentID: info?.parentID ?? null, + additions: (info?.summary as any)?.additions ?? null, + deletions: (info?.summary as any)?.deletions ?? null, + files: (info?.summary as any)?.files ?? null, + }); + } + + // ── session.diff ── + if (type === "session.diff") { + const sid = props.sessionID || activeSessionId; + if (!sid || !Array.isArray(props.diff)) return; + const diffs = props.diff as Array>; + await observe(sid, "session_diff", { + files: diffs.map(d => d.file), + additions: diffs.reduce((s, d) => s + ((d.additions as number) || 0), 0), + deletions: diffs.reduce((s, d) => s + ((d.deletions as number) || 0), 0), + diffs: diffs.slice(0, 50), + }); + } + + // ── session.deleted ── + if (type === "session.deleted") { + const sid = props.info?.id || props.sessionID || activeSessionId; + if (sid) { + await post("/session/end", { sessionId: sid }); + if (sid === activeSessionId) activeSessionId = null; + stashedFiles.clear(); + seenSubtaskIds.clear(); + seenToolCallIds.clear(); + contextInjectedSessions.delete(sid); + } + } + + // ── session.error ── + if (type === "session.error") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await observe(sid, "post_tool_use_failure", { + tool_name: "session.error", + tool_input: "", + tool_output: extractErrorMessage(props.error).slice(0, 8000), + }); + } + } + + // ── message.updated ── + if (type === "message.updated") { + const info = props.info as Record | undefined; + if (!info) return; + + if (info.role === "user") { + const sid = (info.sessionID as string) || activeSessionId; + if (sid) { + await observe(sid, "user_prompt_submit", { + agent: info.agent ?? null, + model: info.model ?? null, + system: ((info.system as string) || "").slice(0, 1000), + tools: info.tools ?? null, + summary: info.summary ?? null, + }); + } + } + + if (info.role === "assistant") { + const sid = (info.sessionID as string) || activeSessionId; + if (!sid) return; + const tokens = info.tokens as Record | undefined; + const error = info.error ? extractErrorMessage(info.error) : null; + await observe(sid, "assistant_message", { + messageID: info.id, + parentID: info.parentID, + modelID: info.modelID, + providerID: info.providerID, + mode: info.mode, + cost: info.cost ?? 0, + tokens: { + input: tokens?.input ?? 0, + output: tokens?.output ?? 0, + reasoning: tokens?.reasoning ?? 0, + cache_read: (tokens?.cache as any)?.read ?? 0, + cache_write: (tokens?.cache as any)?.write ?? 0, + }, + finish: info.finish ?? null, + error, + duration_ms: info.time + ? ((info.time as any).completed || 0) - ((info.time as any).created || 0) + : null, + }); + } + } + + // ── message.removed ── + if (type === "message.removed") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await observe(sid, "message_removed", { + messageID: props.messageID, + }); + } + } + + // ── message.part.updated ── + if (type === "message.part.updated") { + const part = props.part as Record | undefined; + if (!part) return; + const sid = (part.sessionID as string) || activeSessionId; + if (!sid) return; + + if (part.type === "subtask") { + if (seenSubtaskIds.has(part.id as string)) return; + seenSubtaskIds.add(part.id as string); + await observe(sid, "subagent_start", { + subtask_id: part.id, + agent: part.agent, + prompt: ((part.prompt as string) || "").slice(0, 4000), + description: ((part.description as string) || "").slice(0, 2000), + }); + return; + } + + if (part.type === "tool") { + const state = part.state as Record | undefined; + if (!state) return; + const callId = part.callID as string; + const toolName = part.tool as string; + + if (state.status === "completed") { + if (seenToolCallIds.has(callId)) return; + seenToolCallIds.add(callId); + const st = state as Record; + const startTime = ((st.time as any)?.start as number) || 0; + const endTime = ((st.time as any)?.end as number) || 0; + await observe(sid, "post_tool_use", { + tool_name: toolName, + call_id: callId, + tool_input: JSON.stringify(st.input).slice(0, 4000), + tool_output: ((st.output as string) || "").slice(0, 8000), + title: st.title ?? null, + metadata: st.metadata || {}, + duration_ms: endTime - startTime || null, + attachments: Array.isArray(st.attachments) + ? (st.attachments as Array>).map(a => a.filename || a.url) + : [], + }); + } else if (state.status === "error") { + if (seenToolCallIds.has(callId)) return; + seenToolCallIds.add(callId); + const st = state as Record; + const startTime = ((st.time as any)?.start as number) || 0; + const endTime = ((st.time as any)?.end as number) || 0; + await observe(sid, "post_tool_use_failure", { + tool_name: toolName, + call_id: callId, + tool_input: JSON.stringify(st.input).slice(0, 4000), + tool_output: ((st.error as string) || "").slice(0, 8000), + duration_ms: endTime - startTime || null, + }); + } + return; + } + + if (part.type === "step-finish") { + await observe(sid, "step_finish", { + messageID: part.messageID, + reason: part.reason ?? null, + cost: (part as any).cost ?? 0, + input_tokens: ((part as any).tokens?.input as number) ?? 0, + output_tokens: ((part as any).tokens?.output as number) ?? 0, + reasoning_tokens: ((part as any).tokens?.reasoning as number) ?? 0, + }); + return; + } + + if (part.type === "reasoning") { + await observe(sid, "reasoning", { + messageID: part.messageID, + text: ((part as any).text as string || "").slice(0, 4000), + }); + return; + } + + if (part.type === "file") { + const filename = (part as any).filename || (part as any).url || null; + if (filename) stashedFiles.add(filename); + return; + } + + if (part.type === "patch") { + await observe(sid, "patch_applied", { + messageID: part.messageID, + hash: (part as any).hash, + files: (part as any).files || [], + }); + return; + } + + if (part.type === "compaction") { + await observe(sid, "compaction_event", { + messageID: part.messageID, + auto: (part as any).auto ?? false, + }); + return; + } + + if (part.type === "agent") { + await observe(sid, "agent_selected", { + messageID: part.messageID, + name: (part as any).name, + }); + return; + } + + if (part.type === "retry") { + await observe(sid, "retry_attempt", { + messageID: part.messageID, + attempt: (part as any).attempt, + error: extractErrorMessage((part as any).error).slice(0, 2000), + }); + return; + } + } + + // ── file.edited ── + if (type === "file.edited") { + const sid = activeSessionId; + if (sid) { + stashedFiles.add(props.file as string); + } + } + + // ── permission.updated ── + if (type === "permission.updated") { + const sid = props.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "notification", { + notification_type: "permission_prompt", + permission: props.type || "unknown", + pattern: Array.isArray(props.pattern) + ? props.pattern.join(", ") + : (props.pattern || ""), + tool_call_id: props.callID || null, + title: props.title || props.type || "", + metadata: props.metadata || {}, + }); + } + + // ── permission.replied ── + if (type === "permission.replied") { + const sid = props.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "permission_replied", { + permission_id: props.permissionID || props.requestID || "", + response: props.response || props.reply || "", + }); + } + + // ── todo.updated ── + if (type === "todo.updated") { + const sid = props.sessionID || activeSessionId; + const todos = Array.isArray(props.todos) ? props.todos : []; + if (!sid || todos.length === 0) return; + const completed = todos.filter((t: any) => t.status === "completed"); + const active = todos.filter((t: any) => t.status !== "completed"); + await observe(sid, "task_completed", { + completed: completed.map((t: any) => ({ content: t.content, priority: t.priority })), + in_progress: active.map((t: any) => ({ content: t.content, priority: t.priority })), + total: todos.length, + }); + } + + // ── command.executed ── + if (type === "command.executed") { + const sid = props.sessionID || activeSessionId; + if (sid) { + await observe(sid, "command_executed", { + name: props.name, + arguments: props.arguments || "", + }); + } + } + }, + + // ── chat.message ── + "chat.message": async (input, output) => { + const sid = input.sessionID || activeSessionId; + if (!sid) return; + const parts = output.parts || []; + const files = parts + .filter((p: any) => p.type === "file") + .map((p: any) => p.filename || p.url) + .filter(Boolean); + for (const f of files) stashedFiles.add(f); + + const textParts = parts.filter((p: any) => p.type === "text" && !p.synthetic && !p.ignored); + const userText = textParts.map((p: any) => p.text || "").join("\n"); + + await observe(sid, "user_prompt_submit", { + agent: input.agent ?? null, + model: input.model ?? null, + variant: input.variant ?? null, + prompt: userText.slice(0, 8000), + files: files.slice(0, 20), + parts_summary: parts.map((p: any) => p.type).filter(Boolean), + }); + }, + + // ── chat.params ── + "chat.params": async (input, output) => { + const sid = input.sessionID || activeSessionId; + if (!sid) return; + await observe(sid, "llm_params", { + agent: input.agent, + model: `${input.model.providerID}/${input.model.id}`, + provider_url: input.model.api?.url ?? null, + temperature: output.temperature, + topP: output.topP, + max_output_tokens: input.model.limit?.output ?? null, + context_limit: input.model.limit?.context ?? null, + cost_1k_input: input.model.cost?.input ?? 0, + cost_1k_output: input.model.cost?.output ?? 0, + }); + }, + + // ── tool.execute.before ── + "tool.execute.before": async (input, output) => { + if (!FILE_TOOLS.has(input.tool)) return; + const args = output.args as Record | undefined; + if (!args) return; + for (const fp of extractFilePaths(args)) { + stashedFiles.add(fp); + } + if (stashedFiles.size > MAX_STASHED_FILES) { + const keep = [...stashedFiles].slice(-MAX_STASHED_FILES); + stashedFiles.clear(); + for (const f of keep) stashedFiles.add(f); + } + }, + + // ── experimental.chat.system.transform ── + "experimental.chat.system.transform": async (input, output) => { + const sid = input.sessionID || activeSessionId; + if (!sid) return; + + if (!contextInjectedSessions.has(sid)) { + contextInjectedSessions.add(sid); + const result = await postJson("/context", { + sessionId: sid, + project: projectPath, + }); + if (result && typeof result === "object" && (result as any).context) { + output.system.push((result as any).context); + } + } + + if (stashedFiles.size === 0) return; + const files = [...stashedFiles].slice(0, 10); + stashedFiles.clear(); + + const enrichResult = await postJson("/enrich", { + sessionId: sid, + files, + toolName: "enrich_inject", + }); + + if (enrichResult && typeof enrichResult === "object" && (enrichResult as any).context) { + output.system.push((enrichResult as any).context); + } + }, + + // ── experimental.session.compacting (WIP) ── + "experimental.session.compacting": async (input, output) => { + const sid = input.sessionID || activeSessionId; + if (!sid) return; + + const result = await postJson("/context", { + sessionId: sid, + project: projectPath, + }); + if (result && typeof result === "object" && (result as any).context) { + output.context.push((result as any).context); + } + }, + + // ── config ── + config: async (input) => { + if (activeSessionId) { + await observe(activeSessionId, "config_loaded", { + theme: input.theme ?? null, + model: input.model ?? null, + autoupdate: input.autoupdate ?? null, + agents: input.agent ? Object.keys(input.agent as Record) : [], + mcp_servers: input.mcp ? Object.keys(input.mcp as Record) : [], + providers: input.provider ? Object.keys(input.provider as Record) : [], + permission: input.permission ?? null, + }); + } + }, + }; +}; diff --git a/plugin/opencode/commands/recall.md b/plugin/opencode/commands/recall.md new file mode 100644 index 0000000000..de01f0884c --- /dev/null +++ b/plugin/opencode/commands/recall.md @@ -0,0 +1,19 @@ +Search past session observations and lessons for relevant context. Wrap the `memory_smart_search` and `memory_lesson_recall` MCP tools. + +## Usage + +``` +/recall [query] +``` + +## Instructions + +1. Call `memory_smart_search` with the query and `limit: 10` (hybrid BM25 + vector + graph search). +2. Call `memory_lesson_recall` with the same query and `limit: 5` (lesson search). +3. Combine results and present to the user: + - Group by session + - Show type, title, and narrative for each observation + - Highlight high-importance (>= 7) observations + - Show lessons separately with confidence scores +4. If no results, suggest 2-3 alternative search terms. +5. **Never hallucinate results.** Only present what the MCP tools actually return. diff --git a/plugin/opencode/commands/remember.md b/plugin/opencode/commands/remember.md new file mode 100644 index 0000000000..196fc0043a --- /dev/null +++ b/plugin/opencode/commands/remember.md @@ -0,0 +1,19 @@ +Explicitly save an insight, decision, or learning to agentmemory for future sessions. Wraps the `memory_save` MCP tool. + +## Usage + +``` +/remember [what to remember] +``` + +## Instructions + +1. Analyze what needs to be remembered — extract the core insight, decision, or fact. +2. Extract 2-5 searchable concepts (lowercased keyword phrases). Prefer specific terms ("jwt-refresh-rotation" over "auth"). +3. Extract relevant file paths the memory references. +4. Call `memory_save` with: + - `content` — full text to remember (preserve user's phrasing) + - `concepts` — extracted concept list + - `files` — extracted file list (empty array if none) + - `type` — choose from: pattern, preference, architecture, bug, workflow, fact +5. Confirm the save and show the concepts tagged so the user knows retrieval terms. diff --git a/plugin/opencode/plugin.json b/plugin/opencode/plugin.json new file mode 100644 index 0000000000..a66e437a2f --- /dev/null +++ b/plugin/opencode/plugin.json @@ -0,0 +1,12 @@ +{ + "name": "agentmemory-capture", + "version": "0.9.4", + "description": "OpenCode plugin for agentmemory — full Claude Code hook parity: session lifecycle (create/idle/status/compacted/update/diff/delete/error), messages & prompts (chat.message, message.updated user+assistant, message.removed), tool lifecycle (ToolPart states with timing), part tracking (subtask, step-finish, reasoning, file, patch, compaction, agent, retry), file enrichment pipeline, permissions, task tracking (w/ priority), commands, config & model tracking. 22 hooks, 2 slash commands.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory" +} From da8b09e6643896f2d9c720bf4913060702c3394c Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Thu, 7 May 2026 22:26:45 -0400 Subject: [PATCH 02/24] fix(plugin): use prompt_submit hookType so sessions get firstPrompt mem::observe checks hookType === "prompt_submit" to extract raw.userPrompt and set session.firstPrompt. The plugin was using "user_prompt_submit" which didn't match, so sessions were never named. --- plugin/opencode/agentmemory-capture.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 8eff1eaf13..7db112c807 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -198,7 +198,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (info.role === "user") { const sid = (info.sessionID as string) || activeSessionId; if (sid) { - await observe(sid, "user_prompt_submit", { + await observe(sid, "prompt_submit", { agent: info.agent ?? null, model: info.model ?? null, system: ((info.system as string) || "").slice(0, 1000), @@ -441,7 +441,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const textParts = parts.filter((p: any) => p.type === "text" && !p.synthetic && !p.ignored); const userText = textParts.map((p: any) => p.text || "").join("\n"); - await observe(sid, "user_prompt_submit", { + await observe(sid, "prompt_submit", { agent: input.agent ?? null, model: input.model ?? null, variant: input.variant ?? null, From 3a0e7a34d9568addcd660d1b151b02d96fcd600d Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 08:17:17 -0400 Subject: [PATCH 03/24] fix: address CodeRabbit review feedback on OpenCode plugin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Use ctx.worktree for projectPath instead of opaque project.id - Add Array.isArray guards before output.system/.context.push() - Only delete stashed files after successful enrich POST - Defensive JSON.stringify for undefined tool inputs - Per-session Map-based dedup sets to prevent unbounded growth - Fix negative duration_ms when time.completed is unset - Validate props.file and enforce MAX_STASHED_FILES in file.edited - Deduplicate /summarize call on session idle - Buffer early config events until session.created flushes them - Move contextInjectedSessions.add after successful context fetch - Add DEBUG-gated error logging to network helpers - Guard config input.agent/mcp/provider against non-object types - Fix MCP badge count 44→51 in plugin README --- plugin/opencode/README.md | 2 +- plugin/opencode/agentmemory-capture.ts | 112 +++++++++++++++---------- 2 files changed, 70 insertions(+), 44 deletions(-) diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md index cde13ba297..4806c82ccd 100644 --- a/plugin/opencode/README.md +++ b/plugin/opencode/README.md @@ -9,7 +9,7 @@

- 44 MCP tools + 51 MCP tools 22 hooks 2 slash commands 95.2% R@5 diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 7db112c807..5daab7fa8a 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -5,6 +5,8 @@ const FILE_TOOLS = new Set(["Read", "Write", "Edit", "Glob", "Grep"]); const FILE_KEYS = ["filePath", "file_path", "path", "file", "pattern"]; const MAX_STASHED_FILES = 20; +const DEBUG = process.env.OPENCODE_AGENTMEMORY_DEBUG === "1"; + async function post(path: string, body: Record): Promise { try { await fetch(`${API}/agentmemory${path}`, { @@ -13,7 +15,9 @@ async function post(path: string, body: Record): Promise body: JSON.stringify(body), signal: AbortSignal.timeout(5000), }); - } catch {} + } catch (e) { + if (DEBUG) console.error(`[agentmemory] POST ${path} failed:`, (e as Error).message); + } } async function postJson(path: string, body: Record): Promise { @@ -25,7 +29,8 @@ async function postJson(path: string, body: Record): Promise | null = null; let projectPath: string | null = null; const stashedFiles = new Set(); -const seenSubtaskIds = new Set(); +const seenSubtaskIds = new Map>(); +const seenToolCallIds = new Map>(); const contextInjectedSessions = new Set(); -const seenToolCallIds = new Set(); function extractFilePaths(args: Record): string[] { const files: string[] = []; @@ -79,7 +85,7 @@ function extractErrorMessage(err: unknown): string { } export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { - projectPath = ctx.project?.id || ctx.worktree || null; + projectPath = ctx.worktree || ctx.project?.id || null; return { event: async ({ event }) => { @@ -91,9 +97,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const info = props.info as Record | undefined; activeSessionId = (info?.id as string) || props.sessionID || null; stashedFiles.clear(); - seenSubtaskIds.clear(); - seenToolCallIds.clear(); if (activeSessionId) { + seenSubtaskIds.set(activeSessionId, new Set()); + seenToolCallIds.set(activeSessionId, new Set()); contextInjectedSessions.delete(activeSessionId); } await post("/session/start", { @@ -104,16 +110,14 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { project: projectPath, cwd: projectPath, }); - } - - // ── session.idle ── - if (type === "session.idle") { - const sid = props.sessionID || activeSessionId; - if (sid) { - await post("/summarize", { sessionId: sid }); + if (pendingConfig && activeSessionId) { + await observe(activeSessionId, "config_loaded", pendingConfig); + pendingConfig = null; } } + // ── session.idle ── (summarize handled in session.status idle branch) + // ── session.status ── if (type === "session.status") { const status = props.status as Record | undefined; @@ -172,8 +176,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { await post("/session/end", { sessionId: sid }); if (sid === activeSessionId) activeSessionId = null; stashedFiles.clear(); - seenSubtaskIds.clear(); - seenToolCallIds.clear(); + seenSubtaskIds.delete(sid); + seenToolCallIds.delete(sid); contextInjectedSessions.delete(sid); } } @@ -229,8 +233,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { }, finish: info.finish ?? null, error, - duration_ms: info.time - ? ((info.time as any).completed || 0) - ((info.time as any).created || 0) + duration_ms: (info.time && typeof (info.time as any).completed === "number") + ? (info.time as any).completed - ((info.time as any).created || 0) : null, }); } @@ -254,8 +258,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid) return; if (part.type === "subtask") { - if (seenSubtaskIds.has(part.id as string)) return; - seenSubtaskIds.add(part.id as string); + const subtaskSet = seenSubtaskIds.get(sid); + if (subtaskSet?.has(part.id as string)) return; + if (subtaskSet) subtaskSet.add(part.id as string); await observe(sid, "subagent_start", { subtask_id: part.id, agent: part.agent, @@ -272,15 +277,16 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const toolName = part.tool as string; if (state.status === "completed") { - if (seenToolCallIds.has(callId)) return; - seenToolCallIds.add(callId); + const callSet = seenToolCallIds.get(sid); + if (callSet?.has(callId)) return; + if (callSet) callSet.add(callId); const st = state as Record; const startTime = ((st.time as any)?.start as number) || 0; const endTime = ((st.time as any)?.end as number) || 0; await observe(sid, "post_tool_use", { tool_name: toolName, call_id: callId, - tool_input: JSON.stringify(st.input).slice(0, 4000), + tool_input: (JSON.stringify(st.input ?? null) ?? "").slice(0, 4000), tool_output: ((st.output as string) || "").slice(0, 8000), title: st.title ?? null, metadata: st.metadata || {}, @@ -290,15 +296,16 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { : [], }); } else if (state.status === "error") { - if (seenToolCallIds.has(callId)) return; - seenToolCallIds.add(callId); + const callSet = seenToolCallIds.get(sid); + if (callSet?.has(callId)) return; + if (callSet) callSet.add(callId); const st = state as Record; const startTime = ((st.time as any)?.start as number) || 0; const endTime = ((st.time as any)?.end as number) || 0; await observe(sid, "post_tool_use_failure", { tool_name: toolName, call_id: callId, - tool_input: JSON.stringify(st.input).slice(0, 4000), + tool_input: (JSON.stringify(st.input ?? null) ?? "").slice(0, 4000), tool_output: ((st.error as string) || "").slice(0, 8000), duration_ms: endTime - startTime || null, }); @@ -369,9 +376,13 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── file.edited ── if (type === "file.edited") { - const sid = activeSessionId; - if (sid) { - stashedFiles.add(props.file as string); + if (activeSessionId && typeof props.file === "string" && props.file.length > 0) { + stashedFiles.add(props.file); + if (stashedFiles.size > MAX_STASHED_FILES) { + const keep = [...stashedFiles].slice(-MAX_STASHED_FILES); + stashedFiles.clear(); + for (const f of keep) stashedFiles.add(f); + } } } @@ -489,19 +500,20 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid) return; if (!contextInjectedSessions.has(sid)) { - contextInjectedSessions.add(sid); const result = await postJson("/context", { sessionId: sid, project: projectPath, }); if (result && typeof result === "object" && (result as any).context) { - output.system.push((result as any).context); + if (Array.isArray(output.system)) { + output.system.push((result as any).context); + } + contextInjectedSessions.add(sid); } } if (stashedFiles.size === 0) return; const files = [...stashedFiles].slice(0, 10); - stashedFiles.clear(); const enrichResult = await postJson("/enrich", { sessionId: sid, @@ -510,7 +522,10 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { }); if (enrichResult && typeof enrichResult === "object" && (enrichResult as any).context) { - output.system.push((enrichResult as any).context); + if (Array.isArray(output.system)) { + output.system.push((enrichResult as any).context); + } + for (const f of files) stashedFiles.delete(f); } }, @@ -524,22 +539,33 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { project: projectPath, }); if (result && typeof result === "object" && (result as any).context) { - output.context.push((result as any).context); + if (Array.isArray(output.context)) { + output.context.push((result as any).context); + } } }, // ── config ── config: async (input) => { + const payload: Record = { + theme: input.theme ?? null, + model: input.model ?? null, + autoupdate: input.autoupdate ?? null, + agents: typeof input.agent === "object" && input.agent !== null && !Array.isArray(input.agent) + ? Object.keys(input.agent as Record) + : Array.isArray(input.agent) ? input.agent : [], + mcp_servers: typeof input.mcp === "object" && input.mcp !== null && !Array.isArray(input.mcp) + ? Object.keys(input.mcp as Record) + : Array.isArray(input.mcp) ? input.mcp : [], + providers: typeof input.provider === "object" && input.provider !== null && !Array.isArray(input.provider) + ? Object.keys(input.provider as Record) + : Array.isArray(input.provider) ? input.provider : [], + permission: input.permission ?? null, + }; if (activeSessionId) { - await observe(activeSessionId, "config_loaded", { - theme: input.theme ?? null, - model: input.model ?? null, - autoupdate: input.autoupdate ?? null, - agents: input.agent ? Object.keys(input.agent as Record) : [], - mcp_servers: input.mcp ? Object.keys(input.mcp as Record) : [], - providers: input.provider ? Object.keys(input.provider as Record) : [], - permission: input.permission ?? null, - }); + await observe(activeSessionId, "config_loaded", payload); + } else { + pendingConfig = payload; } }, }; From c1d9d2d53529021dede20aa87b58a24198f3724d Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 08:26:46 -0400 Subject: [PATCH 04/24] fix: add language identifier to fenced code block in plugin README --- plugin/opencode/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md index 4806c82ccd..00b80fba4d 100644 --- a/plugin/opencode/README.md +++ b/plugin/opencode/README.md @@ -150,7 +150,7 @@ Restart OpenCode or open a new session. The plugin auto-captures everything. 2. **File enrichment** (every turn with stashed files): calls `/agentmemory/enrich` with files stashed by `tool.execute.before`, `file.edited`, and `message.part.updated` (file parts). File-specific context (past observations, related bugs, semantic search) is injected into the system prompt. -``` +```text System prompt = [OpenCode instructions] + [memory context] + [file enrichment] + [user message] ^ ^ first turn only every file-touching turn From fcc93b8acfd94a9239d9fe4d7c80e9065ead8910 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 13:51:27 -0400 Subject: [PATCH 05/24] fix: store OpenCode session title as summary/firstPrompt on creation --- src/triggers/api.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/triggers/api.ts b/src/triggers/api.ts index 6a65f23394..5baa474823 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -531,6 +531,7 @@ export function registerApiTriggers( }, }; } + const title = typeof body.title === "string" ? body.title.trim() : undefined; const session: Session = { id: sessionId, project, @@ -538,6 +539,8 @@ export function registerApiTriggers( startedAt: new Date().toISOString(), status: "active", observationCount: 0, + ...(title ? { summary: title.slice(0, 200) } : {}), + ...(title ? { firstPrompt: title.slice(0, 200) } : {}), }; await kv.set(KV.sessions, sessionId, session); const contextResult = await sdk.trigger< From 2f35f1dfad48f267749bbb38e3dcd20fd4b4ac81 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Thu, 7 May 2026 23:25:22 -0400 Subject: [PATCH 06/24] fix(plugin): add session instruction injection and consolidation pipeline (closes #233) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three gaps from the Claude Code plugin port sweep: - Inject agentmemory usage instructions (memory_save, memory_recall, etc.) into the system prompt on first turn via experimental.chat.system.transform, replacing the skills mechanism that OpenCode lacks - Call /crystals/auto and /consolidate-pipeline on session.deleted, mirroring Claude's CONSOLIDATION_ENABLED behavior - Document MEMORY.md vs AGENTS.md architecture comparison (two-hop file bridge vs one-hop direct injection) Gap A (SubagentStop) is unfixable — OpenCode's SubtaskPart type has no completion/result fields. Gap C (Claude MEMORY.md bridge) is intentionally skipped — OpenCode uses direct injection. --- plugin/opencode/README.md | 49 +++++++++++++++++++++++++- plugin/opencode/agentmemory-capture.ts | 47 ++++++++++++++++++++++-- 2 files changed, 93 insertions(+), 3 deletions(-) diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md index 00b80fba4d..b98ee86c71 100644 --- a/plugin/opencode/README.md +++ b/plugin/opencode/README.md @@ -166,17 +166,64 @@ System prompt = [OpenCode instructions] + [memory context] + [file enrichment] + | Coverage | Edit/Write/Read/Glob/Grep only | Edit/Write/Read/Glob/Grep only | | What gets injected | `` + bug memories | Identical `/enrich` response | +## MEMORY.md vs AGENTS.md: how context flows + +Claude Code and OpenCode take fundamentally different approaches to injecting memory context into the agent's system prompt. + +### Claude Code: file-backed bridge (two-hop) + +``` +agentmemory ──write──▶ MEMORY.md ──read──▶ Claude system prompt +``` + +- The `claude-bridge/sync` endpoint serializes agentmemory observations into a `MEMORY.md` file in the project root +- Claude Code reads `MEMORY.md` on session start and prepends it to the system prompt +- **Sync is periodic** — sessions only get fresh context when the bridge last ran (session end, pre-compact) +- **Coupling**: memory data lives in a git-trackable file, visible to CI, team members, and other tools + +### OpenCode: direct injection (one-hop) + +``` +agentmemory ──push──▶ OpenCode system prompt +``` + +- `experimental.chat.system.transform` calls `/context` at runtime and pushes the response directly into `output.system[]` +- **Always current** — context is fetched at session start (once) and before file-touching turns (per-batch) +- **No file intermediary** — no stale copies, no merge conflicts, no disk I/O +- `AGENTS.md` is a static instruction file for project conventions, coding standards, and tool guidance — agentmemory does not read or write it + +### Tradeoffs + +| Dimension | Claude (MEMORY.md bridge) | OpenCode (direct injection) | +|---|---|---| +| Freshness | Stale between syncs | Always current (fetched at call time) | +| Visibility | Human-readable file in repo | In-memory injection only | +| Simplicity | Two moving parts (bridge + file) | One step (API → system prompt) | +| Team sharing | File is git-trackable, CI-friendly | Memory shared via agentmemory server API | +| Integration | Any tool can read MEMORY.md | Requires OpenCode plugin SDK | + +### Why OpenCode goes direct + +agentmemory already persists everything in SQLite (`data/state_store.db`). Adding an intermediate MEMORY.md file would duplicate data, introduce sync lag, and require the model to re-parse structured context from markdown. Direct injection delivers the same data with lower latency and zero staleness — the agent always sees what agentmemory knows right now. + ## Slash commands - `/recall ` — Search past observations and lessons - `/remember ` — Save an insight to long-term memory +## Session instruction injection + +Agentmemory usage instructions are injected into the system prompt on the first turn of every session via `experimental.chat.system.transform` (alongside memory context from `/context`). This is functionally equivalent to Claude Code's skills mechanism — the agent learns which `agentmemory_memory_*` tools to use and when, without needing separate skill invocations. + ## What's not covered (vs Claude Code plugin) | Claude feature | Reason | |---|---| -| SubagentStop | No explicit subtask-completion event; stop boundary is inferred from the observation timeline by the memory system | +| SubagentStop | OpenCode's `SubtaskPart` type has no completion/result fields; subtask lifecycle ends are not exposed as distinct events in the OpenCode SDK | | TaskCompleted | No team/teammate concept in OpenCode; `todo.updated` captures task state changes as a partial equivalent | | Stop | `session.compacted` event handler exists; `experimental.session.compacting` injection hook defined in SDK but Go binary (v1.14.41) doesn't wire it — will auto-activate when upstream implements it | +| Skills (remember/recall/forget/session-history) | Covered by injected system instructions via `experimental.chat.system.transform` — agent receives usage guidance on first turn | +| Consolidation pipeline (crystals/auto + consolidate-pipeline) | Now called on `session.deleted` — mirrors Claude's `CONSOLIDATION_ENABLED=true` behavior | +| Claude MEMORY.md bridge | OpenCode-specific; OpenCode uses its own AGENTS.md mechanism, not Claude's MEMORY.md | All other Claude Code hooks have direct or pipeline equivalents in this plugin. 12 of 12 Claude hook types covered. diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 5daab7fa8a..9120f6b570 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -28,7 +28,7 @@ async function postJson(path: string, body: Record): Promise>(); const seenToolCallIds = new Map>(); const contextInjectedSessions = new Set(); +const AGENTMEMORY_INSTRUCTIONS = ` +You have access to agentmemory for persistent cross-session memory. Use these tools proactively. + +CORE TOOLS: + +memory_save — Save an insight, decision, or fact to long-term memory. + Required: content (text), concepts (2-5 comma-separated keywords), type (pattern/preference/architecture/bug/workflow/fact) + Optional: files (comma-separated paths) + Use when: user says "remember this", after discovering a bug, after making an architectural decision, after learning a project convention. + +memory_recall — Search past observations by keywords. + Use when: user says "recall", "what did we do", "do you remember", or needs context from past sessions. + +memory_smart_search — Hybrid semantic+keyword search with progressive disclosure. + Use when: you need the most relevant past context, fuzzy/conceptual searches, or recall doesn't find what you need. + +memory_sessions — List recent sessions with status and observation counts. + Use when: user asks about session/past history, "what did we work on". + +memory_file_history — Get past observations about specific files (across all sessions). + Use when: you're about to edit a file and want to know its history, common pitfalls, or past edits. + +memory_lesson_save — Save a lesson learned (what worked, what to avoid). + Use when: you discover a pattern that could help future sessions avoid mistakes. + +memory_lesson_recall — Search lessons by query. Returns lessons sorted by confidence. + Use when: before making a decision, check if past lessons apply. + +memory_governance_delete — Delete specific memories. Requires explicit user confirmation. + Use when: user says "forget this", "delete that memory". + +memory_patterns — Detect recurring patterns across sessions. + Use when: you want to understand project-level trends over time. + +memory_consolidate — Run the 4-tier memory consolidation pipeline. + Use when: you want to compress and organize accumulated session observations. + +All tools are prefixed with \`agentmemory_\`. Tool results are JSON. Always check what was returned before presenting to the user. +`; + function extractFilePaths(args: Record): string[] { const files: string[] = []; for (const key of FILE_KEYS) { @@ -174,6 +214,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const sid = props.info?.id || props.sessionID || activeSessionId; if (sid) { await post("/session/end", { sessionId: sid }); + post("/crystals/auto", { olderThanDays: 0 }); + post("/consolidate-pipeline", { tier: "all", force: true }); if (sid === activeSessionId) activeSessionId = null; stashedFiles.clear(); seenSubtaskIds.delete(sid); @@ -500,6 +542,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid) return; if (!contextInjectedSessions.has(sid)) { + output.system.push(AGENTMEMORY_INSTRUCTIONS); const result = await postJson("/context", { sessionId: sid, project: projectPath, @@ -508,8 +551,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (Array.isArray(output.system)) { output.system.push((result as any).context); } - contextInjectedSessions.add(sid); } + contextInjectedSessions.add(sid); } if (stashedFiles.size === 0) return; From f33c662bcf539d2d1e2b6e4ff904fd0db9e88a98 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 14:58:52 -0400 Subject: [PATCH 07/24] =?UTF-8?q?fix(plugin):=20address=20adversarial=20co?= =?UTF-8?q?de=20review=20=E2=80=94=207=20critical/high=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Guard instructions push with Array.isArray check + fix TOCTOU race by moving contextInjectedSessions.add() before the await - Session-scope stashedFiles via stashFor() helper (was process-global, could cross-contaminate concurrent sessions) - Fix tool prefix in instructions (agentmemory_memory_ not agentmemory_) - Check typeof string before pushing .context into system arrays - Change olderThanDays: 0 → 7 in consolidation fire-and-forget - Increase fire-and-forget timeout from 5s to 30s (consolidation takes minutes, 5s was guaranteed to abort) --- plugin/opencode/agentmemory-capture.ts | 74 +++++++++++++++----------- 1 file changed, 43 insertions(+), 31 deletions(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 9120f6b570..70579ced30 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -7,13 +7,13 @@ const MAX_STASHED_FILES = 20; const DEBUG = process.env.OPENCODE_AGENTMEMORY_DEBUG === "1"; -async function post(path: string, body: Record): Promise { +async function post(path: string, body: Record, timeoutMs = 5000): Promise { try { await fetch(`${API}/agentmemory${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), - signal: AbortSignal.timeout(5000), + signal: AbortSignal.timeout(timeoutMs), }); } catch (e) { if (DEBUG) console.error(`[agentmemory] POST ${path} failed:`, (e as Error).message); @@ -53,11 +53,17 @@ async function observe( let activeSessionId: string | null = null; let pendingConfig: Record | null = null; let projectPath: string | null = null; -const stashedFiles = new Set(); +const stashedFiles = new Map>(); const seenSubtaskIds = new Map>(); const seenToolCallIds = new Map>(); const contextInjectedSessions = new Set(); +function stashFor(sid: string): Set { + let s = stashedFiles.get(sid); + if (!s) { s = new Set(); stashedFiles.set(sid, s); } + return s; +} + const AGENTMEMORY_INSTRUCTIONS = ` You have access to agentmemory for persistent cross-session memory. Use these tools proactively. @@ -95,7 +101,7 @@ memory_patterns — Detect recurring patterns across sessions. memory_consolidate — Run the 4-tier memory consolidation pipeline. Use when: you want to compress and organize accumulated session observations. -All tools are prefixed with \`agentmemory_\`. Tool results are JSON. Always check what was returned before presenting to the user. +All memory tools start with \`agentmemory_memory_\`. Use the exact names as they appear in your tool list. Tool results are JSON. Always check what was returned before presenting to the user. `; function extractFilePaths(args: Record): string[] { @@ -136,8 +142,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (type === "session.created") { const info = props.info as Record | undefined; activeSessionId = (info?.id as string) || props.sessionID || null; - stashedFiles.clear(); if (activeSessionId) { + stashedFiles.set(activeSessionId, new Set()); seenSubtaskIds.set(activeSessionId, new Set()); seenToolCallIds.set(activeSessionId, new Set()); contextInjectedSessions.delete(activeSessionId); @@ -214,8 +220,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const sid = props.info?.id || props.sessionID || activeSessionId; if (sid) { await post("/session/end", { sessionId: sid }); - post("/crystals/auto", { olderThanDays: 0 }); - post("/consolidate-pipeline", { tier: "all", force: true }); + post("/crystals/auto", { olderThanDays: 7 }, 30000); + post("/consolidate-pipeline", { tier: "all", force: true }, 30000); if (sid === activeSessionId) activeSessionId = null; stashedFiles.clear(); seenSubtaskIds.delete(sid); @@ -377,7 +383,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (part.type === "file") { const filename = (part as any).filename || (part as any).url || null; - if (filename) stashedFiles.add(filename); + if (filename) stashFor(sid).add(filename); return; } @@ -419,11 +425,12 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── file.edited ── if (type === "file.edited") { if (activeSessionId && typeof props.file === "string" && props.file.length > 0) { - stashedFiles.add(props.file); - if (stashedFiles.size > MAX_STASHED_FILES) { - const keep = [...stashedFiles].slice(-MAX_STASHED_FILES); - stashedFiles.clear(); - for (const f of keep) stashedFiles.add(f); + const stash = stashFor(activeSessionId); + stash.add(props.file); + if (stash.size > MAX_STASHED_FILES) { + const keep = [...stash].slice(-MAX_STASHED_FILES); + stash.clear(); + for (const f of keep) stash.add(f); } } } @@ -489,7 +496,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { .filter((p: any) => p.type === "file") .map((p: any) => p.filename || p.url) .filter(Boolean); - for (const f of files) stashedFiles.add(f); + for (const f of files) stashFor(sid).add(f); const textParts = parts.filter((p: any) => p.type === "text" && !p.synthetic && !p.ignored); const userText = textParts.map((p: any) => p.text || "").join("\n"); @@ -524,15 +531,17 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── tool.execute.before ── "tool.execute.before": async (input, output) => { if (!FILE_TOOLS.has(input.tool)) return; + if (!activeSessionId) return; const args = output.args as Record | undefined; if (!args) return; + const stash = stashFor(activeSessionId); for (const fp of extractFilePaths(args)) { - stashedFiles.add(fp); + stash.add(fp); } - if (stashedFiles.size > MAX_STASHED_FILES) { - const keep = [...stashedFiles].slice(-MAX_STASHED_FILES); - stashedFiles.clear(); - for (const f of keep) stashedFiles.add(f); + if (stash.size > MAX_STASHED_FILES) { + const keep = [...stash].slice(-MAX_STASHED_FILES); + stash.clear(); + for (const f of keep) stash.add(f); } }, @@ -542,21 +551,22 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid) return; if (!contextInjectedSessions.has(sid)) { + contextInjectedSessions.add(sid); + if (!Array.isArray(output.system)) return; output.system.push(AGENTMEMORY_INSTRUCTIONS); const result = await postJson("/context", { sessionId: sid, project: projectPath, }); - if (result && typeof result === "object" && (result as any).context) { - if (Array.isArray(output.system)) { - output.system.push((result as any).context); - } + const ctx = (result as any)?.context; + if (typeof ctx === "string" && ctx.length > 0) { + output.system.push(ctx); } - contextInjectedSessions.add(sid); } - if (stashedFiles.size === 0) return; - const files = [...stashedFiles].slice(0, 10); + const stash = stashFor(sid); + if (stash.size === 0) return; + const files = [...stash].slice(0, 10); const enrichResult = await postJson("/enrich", { sessionId: sid, @@ -564,11 +574,12 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { toolName: "enrich_inject", }); - if (enrichResult && typeof enrichResult === "object" && (enrichResult as any).context) { + const enrichCtx = (enrichResult as any)?.context; + if (typeof enrichCtx === "string" && enrichCtx.length > 0) { if (Array.isArray(output.system)) { - output.system.push((enrichResult as any).context); + output.system.push(enrichCtx); } - for (const f of files) stashedFiles.delete(f); + for (const f of files) stash.delete(f); } }, @@ -581,9 +592,10 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { sessionId: sid, project: projectPath, }); - if (result && typeof result === "object" && (result as any).context) { + const ctx = (result as any)?.context; + if (typeof ctx === "string" && ctx.length > 0) { if (Array.isArray(output.context)) { - output.context.push((result as any).context); + output.context.push(ctx); } } }, From a40b0c0504b2ea11da491308b803b58951f6e0ff Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 14:59:57 -0400 Subject: [PATCH 08/24] fix(plugin): scope stashedFiles.delete(sid) not .clear() on session.deleted --- plugin/opencode/agentmemory-capture.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 70579ced30..edc755d9b3 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -223,7 +223,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { post("/crystals/auto", { olderThanDays: 7 }, 30000); post("/consolidate-pipeline", { tier: "all", force: true }, 30000); if (sid === activeSessionId) activeSessionId = null; - stashedFiles.clear(); + stashedFiles.delete(sid); seenSubtaskIds.delete(sid); seenToolCallIds.delete(sid); contextInjectedSessions.delete(sid); From a984765474b892eb357dae11132bdb16794508cf Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 15:11:48 -0400 Subject: [PATCH 09/24] =?UTF-8?q?fix(plugin):=20address=20round=202=20adve?= =?UTF-8?q?rsarial=20review=20=E2=80=94=203=20critical=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix session cross-contamination: file.edited and tool.execute.before now use props.sessionID/input.sessionID fallback instead of only activeSessionId, preventing subagent hijack of parent stash - Fix contextInjectedSessions regression from round 1: move add(sid) to after instructions push (synchronous) but before context fetch (async), so failed /context calls don't permanently skip injection - Fix Map memory leak: prune session entries (stashedFiles, seenSubtaskIds, seenToolCallIds) when session.status goes idle, preventing unbounded growth for crash-killed sessions --- plugin/opencode/agentmemory-capture.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index edc755d9b3..817e46e11e 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -64,6 +64,12 @@ function stashFor(sid: string): Set { return s; } +function pruneSessionMaps(sid: string): void { + stashedFiles.delete(sid); + seenSubtaskIds.delete(sid); + seenToolCallIds.delete(sid); +} + const AGENTMEMORY_INSTRUCTIONS = ` You have access to agentmemory for persistent cross-session memory. Use these tools proactively. @@ -171,6 +177,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid || !status) return; if (status.type === "idle") { await post("/summarize", { sessionId: sid }); + pruneSessionMaps(sid); } await observe(sid, "session_status", { status_type: status.type, @@ -424,8 +431,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── file.edited ── if (type === "file.edited") { - if (activeSessionId && typeof props.file === "string" && props.file.length > 0) { - const stash = stashFor(activeSessionId); + const sid = props.sessionID || activeSessionId; + if (sid && typeof props.file === "string" && props.file.length > 0) { + const stash = stashFor(sid); stash.add(props.file); if (stash.size > MAX_STASHED_FILES) { const keep = [...stash].slice(-MAX_STASHED_FILES); @@ -531,10 +539,11 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── tool.execute.before ── "tool.execute.before": async (input, output) => { if (!FILE_TOOLS.has(input.tool)) return; - if (!activeSessionId) return; + const sid = input.sessionID || activeSessionId; + if (!sid) return; const args = output.args as Record | undefined; if (!args) return; - const stash = stashFor(activeSessionId); + const stash = stashFor(sid); for (const fp of extractFilePaths(args)) { stash.add(fp); } @@ -551,9 +560,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid) return; if (!contextInjectedSessions.has(sid)) { - contextInjectedSessions.add(sid); if (!Array.isArray(output.system)) return; output.system.push(AGENTMEMORY_INSTRUCTIONS); + contextInjectedSessions.add(sid); const result = await postJson("/context", { sessionId: sid, project: projectPath, From a7182a1be678f05411a93f7f89fe0ef342480a59 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 15:19:04 -0400 Subject: [PATCH 10/24] fix(plugin): address round 2 remaining medium issues - Enforce MAX_STASHED_FILES cap on chat.message (was missing, could grow unbounded from 50+ file-ref messages) - Remove activeSessionId fallback from session.deleted; log warning when both info.id and sessionID are missing instead of guessing - Add subtaskSetFor/toolCallSetFor lazy-init wrappers matching stashFor pattern; fixes dedup failures for subagents spawned without a preceding session.created event - Guard chat.params against missing input.model (TypeError crash) --- plugin/opencode/agentmemory-capture.ts | 67 +++++++++++++++++--------- 1 file changed, 45 insertions(+), 22 deletions(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 817e46e11e..909facbb4b 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -64,6 +64,18 @@ function stashFor(sid: string): Set { return s; } +function subtaskSetFor(sid: string): Set { + let s = seenSubtaskIds.get(sid); + if (!s) { s = new Set(); seenSubtaskIds.set(sid, s); } + return s; +} + +function toolCallSetFor(sid: string): Set { + let s = seenToolCallIds.get(sid); + if (!s) { s = new Set(); seenToolCallIds.set(sid, s); } + return s; +} + function pruneSessionMaps(sid: string): void { stashedFiles.delete(sid); seenSubtaskIds.delete(sid); @@ -150,8 +162,8 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { activeSessionId = (info?.id as string) || props.sessionID || null; if (activeSessionId) { stashedFiles.set(activeSessionId, new Set()); - seenSubtaskIds.set(activeSessionId, new Set()); - seenToolCallIds.set(activeSessionId, new Set()); + seenSubtaskIds.delete(activeSessionId); + seenToolCallIds.delete(activeSessionId); contextInjectedSessions.delete(activeSessionId); } await post("/session/start", { @@ -224,17 +236,19 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── session.deleted ── if (type === "session.deleted") { - const sid = props.info?.id || props.sessionID || activeSessionId; - if (sid) { - await post("/session/end", { sessionId: sid }); - post("/crystals/auto", { olderThanDays: 7 }, 30000); - post("/consolidate-pipeline", { tier: "all", force: true }, 30000); - if (sid === activeSessionId) activeSessionId = null; - stashedFiles.delete(sid); - seenSubtaskIds.delete(sid); - seenToolCallIds.delete(sid); - contextInjectedSessions.delete(sid); + const sid = props.info?.id || props.sessionID; + if (!sid) { + if (DEBUG) console.error("[agentmemory] session.deleted with no session ID"); + return; } + await post("/session/end", { sessionId: sid }); + post("/crystals/auto", { olderThanDays: 7 }, 30000); + post("/consolidate-pipeline", { tier: "all", force: true }, 30000); + if (sid === activeSessionId) activeSessionId = null; + stashedFiles.delete(sid); + seenSubtaskIds.delete(sid); + seenToolCallIds.delete(sid); + contextInjectedSessions.delete(sid); } // ── session.error ── @@ -313,9 +327,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid) return; if (part.type === "subtask") { - const subtaskSet = seenSubtaskIds.get(sid); - if (subtaskSet?.has(part.id as string)) return; - if (subtaskSet) subtaskSet.add(part.id as string); + const subtaskSet = subtaskSetFor(sid); + if (subtaskSet.has(part.id as string)) return; + subtaskSet.add(part.id as string); await observe(sid, "subagent_start", { subtask_id: part.id, agent: part.agent, @@ -332,9 +346,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const toolName = part.tool as string; if (state.status === "completed") { - const callSet = seenToolCallIds.get(sid); - if (callSet?.has(callId)) return; - if (callSet) callSet.add(callId); + const callSet = toolCallSetFor(sid); + if (callSet.has(callId)) return; + callSet.add(callId); const st = state as Record; const startTime = ((st.time as any)?.start as number) || 0; const endTime = ((st.time as any)?.end as number) || 0; @@ -351,9 +365,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { : [], }); } else if (state.status === "error") { - const callSet = seenToolCallIds.get(sid); - if (callSet?.has(callId)) return; - if (callSet) callSet.add(callId); + const callSet = toolCallSetFor(sid); + if (callSet.has(callId)) return; + callSet.add(callId); const st = state as Record; const startTime = ((st.time as any)?.start as number) || 0; const endTime = ((st.time as any)?.end as number) || 0; @@ -504,7 +518,15 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { .filter((p: any) => p.type === "file") .map((p: any) => p.filename || p.url) .filter(Boolean); - for (const f of files) stashFor(sid).add(f); + for (const f of files) { + const stash = stashFor(sid); + stash.add(f); + if (stash.size > MAX_STASHED_FILES) { + const keep = [...stash].slice(-MAX_STASHED_FILES); + stash.clear(); + for (const k of keep) stash.add(k); + } + } const textParts = parts.filter((p: any) => p.type === "text" && !p.synthetic && !p.ignored); const userText = textParts.map((p: any) => p.text || "").join("\n"); @@ -521,6 +543,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── chat.params ── "chat.params": async (input, output) => { + if (!input.model || !output) return; const sid = input.sessionID || activeSessionId; if (!sid) return; await observe(sid, "llm_params", { From 9035bdbb9f004ebeb94da48203ca8ce3f6d362bc Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 15:42:35 -0400 Subject: [PATCH 11/24] =?UTF-8?q?fix(plugin):=20address=20round=203=20adve?= =?UTF-8?q?rsarial=20review=20=E2=80=94=2010=20HIGH/MEDIUM=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add safeSlice() helper replacing all unsafe (v as string || "").slice() calls; handles objects/BigInt/circular refs via try/catch JSON.stringify - Restore activeSessionId fallback on session.deleted (if both info.id and sessionID missing, fall back like every other handler) - Fix message.updated to check info.id before info.sessionID (matches session.created/session.updated pattern) - Add props.sessionID to message.part.updated fallback chain - Guard undefined callID and subtask ID (prevent dedup silently dropping all subsequent undefined-ID events) - Cap todo.updated at 100 entries (match session.diff's slice pattern) - Fix duration_ms || → ?? (0ms genuine duration no longer falsifies) - Fix extractErrorMessage || → ?? (0/false error values preserved) - Replace extractErrorMessage.slice with safeSlice in retry handler --- plugin/opencode/agentmemory-capture.ts | 51 +++++++++++++++----------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 909facbb4b..5164fc833f 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -82,6 +82,12 @@ function pruneSessionMaps(sid: string): void { seenToolCallIds.delete(sid); } +function safeSlice(v: unknown, max: number): string { + if (typeof v === "string") return v.slice(0, max); + if (v == null) return ""; + try { return JSON.stringify(v).slice(0, max); } catch { return ""; } +} + const AGENTMEMORY_INSTRUCTIONS = ` You have access to agentmemory for persistent cross-session memory. Use these tools proactively. @@ -145,7 +151,7 @@ function extractErrorMessage(err: unknown): string { if (typeof e.name === "string") return e.name; try { return JSON.stringify(err); } catch { return ""; } } - return String(err || ""); + return String(err ?? ""); } export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { @@ -194,7 +200,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { await observe(sid, "session_status", { status_type: status.type, attempt: status.attempt ?? null, - message: ((status.message as string) || "").slice(0, 2000), + message: safeSlice(status.message, 2000), }); } @@ -236,7 +242,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── session.deleted ── if (type === "session.deleted") { - const sid = props.info?.id || props.sessionID; + const sid = props.info?.id || props.sessionID || activeSessionId; if (!sid) { if (DEBUG) console.error("[agentmemory] session.deleted with no session ID"); return; @@ -258,7 +264,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { await observe(sid, "post_tool_use_failure", { tool_name: "session.error", tool_input: "", - tool_output: extractErrorMessage(props.error).slice(0, 8000), + tool_output: safeSlice(props.error, 8000), }); } } @@ -269,12 +275,12 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!info) return; if (info.role === "user") { - const sid = (info.sessionID as string) || activeSessionId; + const sid = (info.id as string) || (info.sessionID as string) || activeSessionId; if (sid) { await observe(sid, "prompt_submit", { agent: info.agent ?? null, model: info.model ?? null, - system: ((info.system as string) || "").slice(0, 1000), + system: safeSlice(info.system, 1000), tools: info.tools ?? null, summary: info.summary ?? null, }); @@ -282,7 +288,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { } if (info.role === "assistant") { - const sid = (info.sessionID as string) || activeSessionId; + const sid = (info.id as string) || (info.sessionID as string) || activeSessionId; if (!sid) return; const tokens = info.tokens as Record | undefined; const error = info.error ? extractErrorMessage(info.error) : null; @@ -323,18 +329,20 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (type === "message.part.updated") { const part = props.part as Record | undefined; if (!part) return; - const sid = (part.sessionID as string) || activeSessionId; + const sid = (part.sessionID as string) || props.sessionID || activeSessionId; if (!sid) return; if (part.type === "subtask") { + const subtaskId = part.id as string; + if (!subtaskId) return; const subtaskSet = subtaskSetFor(sid); - if (subtaskSet.has(part.id as string)) return; - subtaskSet.add(part.id as string); + if (subtaskSet.has(subtaskId)) return; + subtaskSet.add(subtaskId); await observe(sid, "subagent_start", { subtask_id: part.id, agent: part.agent, - prompt: ((part.prompt as string) || "").slice(0, 4000), - description: ((part.description as string) || "").slice(0, 2000), + prompt: safeSlice(part.prompt, 4000), + description: safeSlice(part.description, 2000), }); return; } @@ -343,6 +351,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const state = part.state as Record | undefined; if (!state) return; const callId = part.callID as string; + if (!callId) return; const toolName = part.tool as string; if (state.status === "completed") { @@ -355,11 +364,11 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { await observe(sid, "post_tool_use", { tool_name: toolName, call_id: callId, - tool_input: (JSON.stringify(st.input ?? null) ?? "").slice(0, 4000), - tool_output: ((st.output as string) || "").slice(0, 8000), + tool_input: safeSlice(st.input, 4000), + tool_output: safeSlice(st.output, 8000), title: st.title ?? null, metadata: st.metadata || {}, - duration_ms: endTime - startTime || null, + duration_ms: endTime - startTime ?? null, attachments: Array.isArray(st.attachments) ? (st.attachments as Array>).map(a => a.filename || a.url) : [], @@ -374,9 +383,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { await observe(sid, "post_tool_use_failure", { tool_name: toolName, call_id: callId, - tool_input: (JSON.stringify(st.input ?? null) ?? "").slice(0, 4000), - tool_output: ((st.error as string) || "").slice(0, 8000), - duration_ms: endTime - startTime || null, + tool_input: safeSlice(st.input, 4000), + tool_output: safeSlice(st.error, 8000), + duration_ms: endTime - startTime ?? null, }); } return; @@ -397,7 +406,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (part.type === "reasoning") { await observe(sid, "reasoning", { messageID: part.messageID, - text: ((part as any).text as string || "").slice(0, 4000), + text: safeSlice((part as any).text, 4000), }); return; } @@ -437,7 +446,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { await observe(sid, "retry_attempt", { messageID: part.messageID, attempt: (part as any).attempt, - error: extractErrorMessage((part as any).error).slice(0, 2000), + error: safeSlice((part as any).error, 2000), }); return; } @@ -486,7 +495,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { // ── todo.updated ── if (type === "todo.updated") { const sid = props.sessionID || activeSessionId; - const todos = Array.isArray(props.todos) ? props.todos : []; + const todos = Array.isArray(props.todos) ? props.todos.slice(0, 100) : []; if (!sid || todos.length === 0) return; const completed = todos.filter((t: any) => t.status === "completed"); const active = todos.filter((t: any) => t.status !== "completed"); From b9998f95da86037d323b991d3ee112089765a5ba Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 15:55:05 -0400 Subject: [PATCH 12/24] =?UTF-8?q?fix(plugin):=20address=20round=204=20adve?= =?UTF-8?q?rsarial=20review=20=E2=80=94=206=20CRITICAL/HIGH=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CRITICAL: - Revert message.updated session ID resolution: info.id is the message UUID, not session ID. In message.updated, info is the message object (has role/tokens/modelID), not session info like in session.created. Use props.sessionID || info.sessionID || activeSessionId instead. - Fix post_tool_use_failure -> post_tool_failure: server types.ts defines "post_tool_failure" (no "use_"); compress-synthetic.ts classifies by that exact string. All error observations were misclassified as "other" instead of "error". - Fix contextInjected ordering: move add(sid) after the context fetch completes, not before. If /context times out, session is no longer permanently marked injected, allowing retry on next transform. HIGH: - Add process.cwd() fallback for projectPath (was null, causing silent 400s on every REST call when no workspace) - Guard session.start against null activeSessionId with early return (was sending sessionId: null to API) - Fix duration_ms: use typeof number checks instead of || 0 defaults; missing timing data now correctly reports null instead of 0ms --- plugin/opencode/agentmemory-capture.ts | 37 +++++++++++++------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 5164fc833f..6da51a062b 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -155,7 +155,7 @@ function extractErrorMessage(err: unknown): string { } export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { - projectPath = ctx.worktree || ctx.project?.id || null; + projectPath = ctx.worktree || ctx.project?.id || process.cwd(); return { event: async ({ event }) => { @@ -166,12 +166,11 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (type === "session.created") { const info = props.info as Record | undefined; activeSessionId = (info?.id as string) || props.sessionID || null; - if (activeSessionId) { - stashedFiles.set(activeSessionId, new Set()); - seenSubtaskIds.delete(activeSessionId); - seenToolCallIds.delete(activeSessionId); - contextInjectedSessions.delete(activeSessionId); - } + if (!activeSessionId) return; + stashedFiles.set(activeSessionId, new Set()); + seenSubtaskIds.delete(activeSessionId); + seenToolCallIds.delete(activeSessionId); + contextInjectedSessions.delete(activeSessionId); await post("/session/start", { sessionId: activeSessionId, title: info?.title ?? null, @@ -261,7 +260,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (type === "session.error") { const sid = props.sessionID || activeSessionId; if (sid) { - await observe(sid, "post_tool_use_failure", { + await observe(sid, "post_tool_failure", { tool_name: "session.error", tool_input: "", tool_output: safeSlice(props.error, 8000), @@ -275,7 +274,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!info) return; if (info.role === "user") { - const sid = (info.id as string) || (info.sessionID as string) || activeSessionId; + const sid = props.sessionID || (info.sessionID as string) || activeSessionId; if (sid) { await observe(sid, "prompt_submit", { agent: info.agent ?? null, @@ -288,7 +287,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { } if (info.role === "assistant") { - const sid = (info.id as string) || (info.sessionID as string) || activeSessionId; + const sid = props.sessionID || (info.sessionID as string) || activeSessionId; if (!sid) return; const tokens = info.tokens as Record | undefined; const error = info.error ? extractErrorMessage(info.error) : null; @@ -359,8 +358,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (callSet.has(callId)) return; callSet.add(callId); const st = state as Record; - const startTime = ((st.time as any)?.start as number) || 0; - const endTime = ((st.time as any)?.end as number) || 0; + const rawTime = (st.time as any) || {}; + const startTime = typeof rawTime.start === "number" ? rawTime.start : null; + const endTime = typeof rawTime.end === "number" ? rawTime.end : null; await observe(sid, "post_tool_use", { tool_name: toolName, call_id: callId, @@ -368,7 +368,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { tool_output: safeSlice(st.output, 8000), title: st.title ?? null, metadata: st.metadata || {}, - duration_ms: endTime - startTime ?? null, + duration_ms: (startTime != null && endTime != null) ? endTime - startTime : null, attachments: Array.isArray(st.attachments) ? (st.attachments as Array>).map(a => a.filename || a.url) : [], @@ -378,14 +378,15 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (callSet.has(callId)) return; callSet.add(callId); const st = state as Record; - const startTime = ((st.time as any)?.start as number) || 0; - const endTime = ((st.time as any)?.end as number) || 0; - await observe(sid, "post_tool_use_failure", { + const rawTime = (st.time as any) || {}; + const startTime = typeof rawTime.start === "number" ? rawTime.start : null; + const endTime = typeof rawTime.end === "number" ? rawTime.end : null; + await observe(sid, "post_tool_failure", { tool_name: toolName, call_id: callId, tool_input: safeSlice(st.input, 4000), tool_output: safeSlice(st.error, 8000), - duration_ms: endTime - startTime ?? null, + duration_ms: (startTime != null && endTime != null) ? endTime - startTime : null, }); } return; @@ -594,7 +595,6 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!contextInjectedSessions.has(sid)) { if (!Array.isArray(output.system)) return; output.system.push(AGENTMEMORY_INSTRUCTIONS); - contextInjectedSessions.add(sid); const result = await postJson("/context", { sessionId: sid, project: projectPath, @@ -603,6 +603,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (typeof ctx === "string" && ctx.length > 0) { output.system.push(ctx); } + contextInjectedSessions.add(sid); } const stash = stashFor(sid); From 1dd3066bbb3adac73c8f7951251677504b74356e Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Fri, 8 May 2026 16:23:10 -0400 Subject: [PATCH 13/24] fix(plugin): address final adversarial blockers --- plugin/opencode/agentmemory-capture.ts | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 6da51a062b..718100f484 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -6,12 +6,19 @@ const FILE_KEYS = ["filePath", "file_path", "path", "file", "pattern"]; const MAX_STASHED_FILES = 20; const DEBUG = process.env.OPENCODE_AGENTMEMORY_DEBUG === "1"; +const SECRET = process.env.AGENTMEMORY_SECRET || ""; + +function authHeaders(): Record { + const headers: Record = { "Content-Type": "application/json" }; + if (SECRET) headers["Authorization"] = `Bearer ${SECRET}`; + return headers; +} async function post(path: string, body: Record, timeoutMs = 5000): Promise { try { await fetch(`${API}/agentmemory${path}`, { method: "POST", - headers: { "Content-Type": "application/json" }, + headers: authHeaders(), body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs), }); @@ -24,7 +31,7 @@ async function postJson(path: string, body: Record): Promise { if (!sid || !status) return; if (status.type === "idle") { await post("/summarize", { sessionId: sid }); - pruneSessionMaps(sid); } await observe(sid, "session_status", { status_type: status.type, @@ -273,19 +279,6 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const info = props.info as Record | undefined; if (!info) return; - if (info.role === "user") { - const sid = props.sessionID || (info.sessionID as string) || activeSessionId; - if (sid) { - await observe(sid, "prompt_submit", { - agent: info.agent ?? null, - model: info.model ?? null, - system: safeSlice(info.system, 1000), - tools: info.tools ?? null, - summary: info.summary ?? null, - }); - } - } - if (info.role === "assistant") { const sid = props.sessionID || (info.sessionID as string) || activeSessionId; if (!sid) return; From ee9d818560fe2b9cb6f843dc75ef050782a88438 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sun, 10 May 2026 14:46:52 -0400 Subject: [PATCH 14/24] fix(opencode): gate crystallization on CONSOLIDATION_ENABLED, fix olderThanDays to 0, add compaction trigger --- plugin/opencode/README.md | 2 +- plugin/opencode/agentmemory-capture.ts | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md index b98ee86c71..e5776978cc 100644 --- a/plugin/opencode/README.md +++ b/plugin/opencode/README.md @@ -223,7 +223,7 @@ Agentmemory usage instructions are injected into the system prompt on the first | TaskCompleted | No team/teammate concept in OpenCode; `todo.updated` captures task state changes as a partial equivalent | | Stop | `session.compacted` event handler exists; `experimental.session.compacting` injection hook defined in SDK but Go binary (v1.14.41) doesn't wire it — will auto-activate when upstream implements it | | Skills (remember/recall/forget/session-history) | Covered by injected system instructions via `experimental.chat.system.transform` — agent receives usage guidance on first turn | -| Consolidation pipeline (crystals/auto + consolidate-pipeline) | Now called on `session.deleted` — mirrors Claude's `CONSOLIDATION_ENABLED=true` behavior | +| Consolidation pipeline (crystals/auto + consolidate-pipeline) | Called on `session.deleted` **and** `experimental.session.compacting` when `CONSOLIDATION_ENABLED=true` env var is set; uses `olderThanDays: 0` (crystallize all done work in the session) — mirrors Claude's `CONSOLIDATION_ENABLED=true` behavior | | Claude MEMORY.md bridge | OpenCode-specific; OpenCode uses its own AGENTS.md mechanism, not Claude's MEMORY.md | All other Claude Code hooks have direct or pipeline equivalents in this plugin. 12 of 12 Claude hook types covered. diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 718100f484..8b1a4817fc 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -253,8 +253,10 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { return; } await post("/session/end", { sessionId: sid }); - post("/crystals/auto", { olderThanDays: 7 }, 30000); - post("/consolidate-pipeline", { tier: "all", force: true }, 30000); + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + post("/crystals/auto", { olderThanDays: 0 }, 30000); + post("/consolidate-pipeline", { tier: "all", force: true }, 30000); + } if (sid === activeSessionId) activeSessionId = null; stashedFiles.delete(sid); seenSubtaskIds.delete(sid); @@ -633,6 +635,10 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { output.context.push(ctx); } } + + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + post("/crystals/auto", { olderThanDays: 0 }, 30000); + } }, // ── config ── From e0daa96a911be172bacecaea67c6dde5c5540903 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sun, 10 May 2026 18:52:28 -0400 Subject: [PATCH 15/24] fix(opencode): add crystallization triggers on session.idle and session.compacted --- plugin/opencode/agentmemory-capture.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts index 8b1a4817fc..d97aa9c205 100644 --- a/plugin/opencode/agentmemory-capture.ts +++ b/plugin/opencode/agentmemory-capture.ts @@ -201,6 +201,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { if (!sid || !status) return; if (status.type === "idle") { await post("/summarize", { sessionId: sid }); + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + post("/crystals/auto", { olderThanDays: 0 }, 30000); + } } await observe(sid, "session_status", { status_type: status.type, @@ -214,6 +217,9 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { const sid = props.sessionID || activeSessionId; if (sid) { await post("/summarize", { sessionId: sid }); + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + post("/crystals/auto", { olderThanDays: 0 }, 30000); + } await observe(sid, "session_compacted", {}); } } From a805a7e00e3c4d54015cdb19a41d45480e19293c Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sun, 10 May 2026 20:59:59 -0400 Subject: [PATCH 16/24] feat: auto-create lessons in flow-compress and consolidate, add MCP tools - flow-compress.ts: save extracted tags via mem::lesson-save - consolidate.ts: save lessons for architecture/workflow/pattern/bug memories - lessons.ts: add audit entry for mem::lesson-list - server.ts: add memory_lesson_list and memory_lesson_strengthen handlers - tools-registry.ts: add MCP tool definitions for lesson-list and lesson-strengthen - types.ts: add lesson_list to AuditEntry.operation union - README.md / plugin.json: update tool count 51 -> 53 Fixes #274 --- README.md | 8 ++--- plugin/.claude-plugin/plugin.json | 2 +- src/functions/consolidate.ts | 57 ++++++++++++++++++++++++++++++- src/functions/flow-compress.ts | 34 +++++++++++++++++- src/functions/lessons.ts | 10 ++++++ src/mcp/server.ts | 31 +++++++++++++++++ src/mcp/tools-registry.ts | 32 +++++++++++++++++ src/types.ts | 1 + 8 files changed, 168 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0d98edfb77..4bd21b6a63 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@

95.2% retrieval R@5 92% fewer tokens - 51 MCP tools + 53 MCP tools 12 auto hooks 0 external DBs 827 tests passing @@ -334,7 +334,7 @@ Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cl ### Claude Code (one block, paste it) ``` -Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 51 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. +Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. ```

@@ -602,7 +602,7 @@ npm install @xenova/transformers

MCP Server

-51 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent. +53 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent. ### 50 Tools @@ -887,7 +887,7 @@ Create `~/.agentmemory/.env`: # USER_ID= # TEAM_MODE=private -# Tool visibility: "core" (8 tools) or "all" (51 tools) +# Tool visibility: "core" (8 tools) or "all" (53 tools) # AGENTMEMORY_TOOLS=core ``` diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index b070050c56..8c175f9bd2 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agentmemory", "version": "0.9.4", - "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 51 MCP tools, 4 skills, real-time viewer.", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 53 MCP tools, 4 skills, real-time viewer.", "author": { "name": "Rohit Ghumare", "url": "https://github.com/rohitg00" diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.ts index 9ee0b14ce1..a85259b452 100644 --- a/src/functions/consolidate.ts +++ b/src/functions/consolidate.ts @@ -8,6 +8,7 @@ import type { import { KV, generateId } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; import { recordAudit } from "./audit.js"; +import { logger } from "../logger.js"; const CONSOLIDATION_SYSTEM = `You are a memory consolidation engine. Given a set of related observations from coding sessions, synthesize them into a single long-term memory. @@ -26,7 +27,6 @@ Output XML: `; import { getXmlTag, getXmlChildren } from "../prompts/xml.js"; -import { logger } from "../logger.js"; function parseMemoryXml( xml: string, @@ -62,6 +62,41 @@ function parseMemoryXml( }; } +const lessonableTypes = new Set(["architecture", "workflow", "pattern", "bug"]); + +async function saveConsolidationLesson( + sdk: ISdk, + memoryId: string, + mType: string, + title: string, + content: string, + context: string, + project?: string, +): Promise { + if (!lessonableTypes.has(mType)) return; + const truncated = content.length > 500 ? content.slice(0, 500) + "…" : content; + try { + await sdk.trigger({ + function_id: "mem::lesson-save", + payload: { + content: `[${mType}] ${title}: ${truncated}`, + context, + confidence: 0.6, + project, + tags: [mType, "consolidated"], + source: "consolidation", + sourceIds: [memoryId], + }, + }); + } catch (err) { + logger.warn("Failed to save lesson from consolidation", { + memoryId, + type: mType, + error: err instanceof Error ? err.message : String(err), + }); + } +} + export function registerConsolidateFunction( sdk: ISdk, kv: StateKV, @@ -189,6 +224,16 @@ export function registerConsolidateFunction( }); existingTitles.add(evolved.title.toLowerCase()); consolidated++; + + await saveConsolidationLesson( + sdk, + evolved.id, + parsed.type, + parsed.title, + parsed.content, + `Evolved from concept group: ${concept}`, + data.project, + ); } else { const memory: Memory = { id: generateId("mem"), @@ -206,6 +251,16 @@ export function registerConsolidateFunction( }); existingTitles.add(memory.title.toLowerCase()); consolidated++; + + await saveConsolidationLesson( + sdk, + memory.id, + parsed.type, + parsed.title, + parsed.content, + `Created from concept group: ${concept}`, + data.project, + ); } } catch (err) { logger.warn("Consolidation failed for concept", { diff --git a/src/functions/flow-compress.ts b/src/functions/flow-compress.ts index d2eb5a31c1..d8d08fbbb0 100644 --- a/src/functions/flow-compress.ts +++ b/src/functions/flow-compress.ts @@ -1,8 +1,9 @@ import type { ISdk } from "iii-sdk"; import type { StateKV } from "../state/kv.js"; -import { KV, generateId } from "../state/schema.js"; +import { KV, generateId, fingerprintId } from "../state/schema.js"; import type { Action, ActionEdge, RoutineRun, MemoryProvider } from "../types.js"; import { recordAudit } from "./audit.js"; +import { logger } from "../logger.js"; const FLOW_COMPRESS_SYSTEM = `You are a workflow summarizer. Given a completed action chain, produce a concise summary capturing: 1. The overall goal and outcome @@ -111,6 +112,37 @@ export function registerFlowCompressFunction( project: data.project, }); + if (summary.lesson) { + const lessonContent = summary.lesson.trim(); + const lessonFp = fingerprintId("lsn", lessonContent.toLowerCase()); + const existingLesson = await kv.get<{ id: string; deleted?: boolean }>( + KV.lessons, + lessonFp, + ); + if (!existingLesson || existingLesson.deleted) { + await sdk + .trigger({ + function_id: "mem::lesson-save", + payload: { + content: lessonContent, + context: summary.goal || summary.outcome || "", + confidence: 0.6, + project: data.project, + tags: [], + source: "consolidation", + sourceIds: [memory.id], + }, + }) + .catch((err) => { + logger.warn("Failed to save lesson from flow-compress", { + memoryId: memory.id, + lesson: lessonContent.slice(0, 50), + error: err instanceof Error ? err.message : String(err), + }); + }); + } + } + return { success: true, compressed: doneActions.length, diff --git a/src/functions/lessons.ts b/src/functions/lessons.ts index 9e69f464fd..8b33530aa3 100644 --- a/src/functions/lessons.ts +++ b/src/functions/lessons.ts @@ -174,6 +174,16 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void { lessons.sort((a, b) => b.confidence - a.confidence); + const lessonIds = lessons.slice(0, limit).map((l) => l.id); + try { + await recordAudit(kv, "lesson_list", "mem::lesson-list", lessonIds, { + project: data.project, + source: data.source, + minConfidence: data.minConfidence, + resultCount: lessons.length, + }); + } catch {} + return { success: true, lessons: lessons.slice(0, limit) }; }, ); diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 21c2069a9e..db77a0346c 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -1106,6 +1106,37 @@ export function registerMcpEndpoints( return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonRecallResult, null, 2) }] } }; } + case "memory_lesson_list": { + const project = typeof args.project === "string" ? args.project : undefined; + const source = + typeof args.source === "string" && + ["manual", "crystal", "consolidation"].includes(args.source) + ? args.source + : undefined; + const minConfidence = + typeof args.minConfidence === "number" ? args.minConfidence : undefined; + const limit = + typeof args.limit === "number" && args.limit > 0 ? args.limit : 50; + const lessonListResult = await sdk.trigger({ + function_id: "mem::lesson-list", + payload: { project, source, minConfidence, limit }, + }); + return { + status_code: 200, + body: { content: [{ type: "text", text: JSON.stringify(lessonListResult, null, 2) }] }, + }; + } + + case "memory_lesson_strengthen": { + if (typeof args.lessonId !== "string" || !args.lessonId.trim()) { + return { status_code: 400, body: { error: "lessonId is required" } }; + } + const lessonStrengthenResult = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { + lessonId: args.lessonId, + } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonStrengthenResult, null, 2) }] } }; + } + case "memory_reflect": { const reflectResult = await sdk.trigger({ function_id: "mem::reflect", payload: { project: args.project, diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts index 82d7e7ce0c..fee91d6387 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -766,6 +766,38 @@ export const V070_TOOLS: McpToolDef[] = [ required: ["query"], }, }, + { + name: "memory_lesson_list", + description: + "List all lessons, optionally filtered by project, source, or minimum confidence. Use to browse or review stored lessons.", + inputSchema: { + type: "object", + properties: { + project: { type: "string", description: "Filter by project" }, + source: { + type: "string", + description: "Filter by source: 'manual', 'crystal', or 'consolidation'", + }, + minConfidence: { + type: "number", + description: "Minimum confidence threshold (default 0)", + }, + limit: { type: "number", description: "Max results (default 50)" }, + }, + }, + }, + { + name: "memory_lesson_strengthen", + description: + "Boost the confidence of an existing lesson by its ID. Use when a lesson is particularly relevant or verified.", + inputSchema: { + type: "object", + properties: { + lessonId: { type: "string", description: "The ID of the lesson to strengthen" }, + }, + required: ["lessonId"], + }, + }, { name: "memory_obsidian_export", description: diff --git a/src/types.ts b/src/types.ts index 806dae6acb..55e78e9d51 100644 --- a/src/types.ts +++ b/src/types.ts @@ -510,6 +510,7 @@ export interface AuditEntry { | "lesson_save" | "lesson_recall" | "lesson_strengthen" + | "lesson_list" | "obsidian_export" | "reflect" | "insight_search" From 8cdc4cea9c313dcb4350d14fe837b8a4eac05d26 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 16:48:40 -0400 Subject: [PATCH 17/24] feat(mcp): consolidate tool surface --- plugin/.codex-plugin/plugin.json | 2 +- src/mcp/rest-proxy.ts | 24 + src/mcp/server.ts | 1651 ++++++++++------------------- src/mcp/standalone.ts | 374 ++++--- src/mcp/tools-registry.ts | 953 +++-------------- test/mcp-standalone-proxy.test.ts | 13 +- test/mcp-standalone.test.ts | 200 ++-- 7 files changed, 1050 insertions(+), 2167 deletions(-) diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index 6b8eb419f3..49a29ab98d 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agentmemory", "version": "0.9.11", - "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 51 MCP tools, 4 skills, real-time viewer.", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 13 MCP tools, 4 skills, real-time viewer.", "author": { "name": "Rohit Ghumare", "url": "https://github.com/rohitg00" diff --git a/src/mcp/rest-proxy.ts b/src/mcp/rest-proxy.ts index 5c86bcd5a6..67553c3d8f 100644 --- a/src/mcp/rest-proxy.ts +++ b/src/mcp/rest-proxy.ts @@ -2,6 +2,29 @@ const DEFAULT_URL = "http://localhost:3111"; const DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2_000; const CALL_TIMEOUT_MS = 15_000; const LOCAL_MODE_TTL_MS = 30_000; +const RATE_LIMIT_WINDOW_MS = 60_000; +const RATE_LIMIT_MAX_CALLS = 120; +const RATE_LIMIT_MAP_MAX_SIZE = 1000; + +const rateLimitMap = new Map(); + +function rateLimit(key: string): void { + const now = Date.now(); + const entry = rateLimitMap.get(key); + if (!entry || now >= entry.resetAt) { + rateLimitMap.set(key, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); + } else { + if (entry.count >= RATE_LIMIT_MAX_CALLS) { + throw new Error(`Rate limit exceeded: ${RATE_LIMIT_MAX_CALLS} calls per ${RATE_LIMIT_WINDOW_MS / 1000}s`); + } + entry.count++; + } + if (rateLimitMap.size > RATE_LIMIT_MAP_MAX_SIZE) { + for (const [k, v] of rateLimitMap) { + if (now >= v.resetAt) rateLimitMap.delete(k); + } + } +} function probeTimeoutMs(): number { const raw = process.env["AGENTMEMORY_PROBE_TIMEOUT_MS"]; @@ -92,6 +115,7 @@ export async function resolveHandle(): Promise { mode: "proxy", baseUrl: url, call: async (path, init) => { + rateLimit(url); const res = await fetch(`${url}${path}`, { ...init, headers: { diff --git a/src/mcp/server.ts b/src/mcp/server.ts index db77a0346c..370199e7b4 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -21,6 +21,11 @@ function asNonEmptyString(value: unknown): string | undefined { return typeof value === "string" && value.trim() ? value.trim() : undefined; } +function asValidatedOperation(value: unknown, allowed: string[]): string | undefined { + if (typeof value !== "string") return undefined; + return allowed.includes(value) ? value : undefined; +} + function asNumber(value: unknown, fallback?: number): number | undefined { const n = Number(value); if (Number.isFinite(n)) return n; @@ -39,6 +44,8 @@ function parseCsvList(value: unknown): string[] { return []; } +const MAX_IDS = 1000; + export function registerMcpEndpoints( sdk: ISdk, kv: StateKV, @@ -57,7 +64,7 @@ export function registerMcpEndpoints( return null; } - sdk.registerFunction("mcp::tools::list", + sdk.registerFunction("mcp::tools::list", async (req: ApiRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -70,7 +77,7 @@ export function registerMcpEndpoints( config: { api_path: "/agentmemory/mcp/tools", http_method: "GET" }, }); - sdk.registerFunction("mcp::tools::call", + sdk.registerFunction("mcp::tools::call", async ( req: ApiRequest<{ name: string; arguments: Record }>, ): Promise => { @@ -79,971 +86,560 @@ export function registerMcpEndpoints( if (!req.body || typeof req.body.name !== "string") { return { status_code: 400, body: { error: "name is required" } }; - } - - const { name, arguments: args = {} } = req.body; - - try { - switch (name) { - case "memory_recall": { - if (typeof args.query !== "string" || !args.query.trim()) { - return { - status_code: 400, - body: { error: "query is required for memory_recall" }, - }; - } - const format = - typeof args.format === "string" ? args.format.trim().toLowerCase() : "full"; - if (!["full", "compact", "narrative"].includes(format)) { - return { - status_code: 400, - body: { - error: "format must be one of: full, compact, narrative", - }, - }; - } - const tokenBudget = asNumber(args.token_budget); - if ( - args.token_budget !== undefined && - (!Number.isInteger(tokenBudget) || (tokenBudget ?? 0) < 1) - ) { - return { - status_code: 400, - body: { error: "token_budget must be a positive integer" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::search", payload: { - query: args.query, - limit: typeof args.limit === "number" ? args.limit : 10, - format, - token_budget: tokenBudget, - } }); - const text = - format === "narrative" && - result && - typeof result === "object" && - "text" in (result as Record) && - typeof (result as { text?: unknown }).text === "string" - ? (result as { text: string }).text - : JSON.stringify(result, null, 2); - return { - status_code: 200, - body: { - content: [ - { type: "text", text }, - ], - }, - }; - } - - case "memory_compress_file": { - if (typeof args.filePath !== "string" || !args.filePath.trim()) { - return { - status_code: 400, - body: { error: "filePath is required for memory_compress_file" }, - }; - } - const result = await sdk.trigger({ - function_id: "mem::compress-file", - payload: { filePath: args.filePath.trim() }, - }); - return { - status_code: 200, - body: { - content: [{ type: "text", text: JSON.stringify(result, null, 2) }], - }, - }; - } - - case "memory_save": { - if (typeof args.content !== "string" || !args.content.trim()) { - return { - status_code: 400, - body: { error: "content is required for memory_save" }, - }; - } - const type = (args.type as string) || "fact"; - const concepts = - typeof args.concepts === "string" - ? args.concepts.split(",").map((c: string) => c.trim()).filter(Boolean) - : []; - const files = - typeof args.files === "string" - ? args.files.split(",").map((f: string) => f.trim()).filter(Boolean) - : []; - - const result = await sdk.trigger({ function_id: "mem::remember", payload: { - content: args.content, - type, - concepts, - files, - } }); - return { - status_code: 200, - body: { - content: [{ type: "text", text: JSON.stringify(result) }], - }, - }; - } - - case "memory_file_history": { - if (typeof args.files !== "string" || !args.files.trim()) { - return { - status_code: 400, - body: { error: "files is required for memory_file_history" }, - }; - } - const fileList = parseCsvList(args.files); - if (!fileList.length) { - return { - status_code: 400, - body: { error: "files must contain at least one valid path" }, - }; - } - const payload: { sessionId?: string; files: string[] } = { files: fileList }; - const sessionId = asNonEmptyString(args.sessionId); - if (sessionId) payload.sessionId = sessionId; - const result = await sdk.trigger({ - function_id: "mem::file-context", - payload, - }); - return { - status_code: 200, - body: { - content: [ - { - type: "text", - text: - (result as { context: string }).context || - "No history found.", - }, - ], - }, - }; - } - - case "memory_patterns": { - const result = await sdk.trigger({ function_id: "mem::patterns", payload: { - project: args.project as string, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } - - case "memory_sessions": { - const sessions = await kv.list(KV.sessions); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify({ sessions }, null, 2) }, - ], - }, - }; - } - - case "memory_smart_search": { - if (typeof args.query !== "string" || !args.query.trim()) { - return { - status_code: 400, - body: { error: "query is required for memory_smart_search" }, - }; - } - const expandIds = parseCsvList(args.expandIds).slice(0, 20); - const limit = Math.max(1, Math.min(100, asNumber(args.limit, 10) ?? 10)); - const result = await sdk.trigger({ - function_id: "mem::smart-search", - payload: { - query: args.query, - expandIds, - limit, - }, - }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } - - case "memory_vision_search": { - const queryText = typeof args.queryText === "string" ? args.queryText : undefined; - const queryImageRef = typeof args.queryImageRef === "string" ? args.queryImageRef : undefined; - const queryImageBase64 = typeof args.queryImageBase64 === "string" ? args.queryImageBase64 : undefined; - if (!queryText && !queryImageRef && !queryImageBase64) { - return { - status_code: 400, - body: { error: "queryText, queryImageRef, or queryImageBase64 required" }, - }; - } - const topK = Math.max(1, Math.min(50, asNumber(args.topK, 10) ?? 10)); - const sessionId = typeof args.sessionId === "string" ? args.sessionId : undefined; - const result = await sdk.trigger({ - function_id: "mem::vision-search", - payload: { queryText, queryImageRef, queryImageBase64, topK, sessionId }, - }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } - - case "memory_timeline": { - if (typeof args.anchor !== "string" || !args.anchor.trim()) { - return { - status_code: 400, - body: { error: "anchor is required for memory_timeline" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::timeline", payload: { - anchor: args.anchor, - project: (args.project as string) || undefined, - before: (args.before as number) || 5, - after: (args.after as number) || 5, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } - - case "memory_profile": { - if (typeof args.project !== "string" || !args.project.trim()) { - return { - status_code: 400, - body: { error: "project is required for memory_profile" }, - }; - } - const result = await sdk.trigger({ function_id: "mem::profile", payload: { - project: args.project, - refresh: args.refresh === true || args.refresh === "true", - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } - - case "memory_export": { - const result = await sdk.trigger({ function_id: "mem::export", payload: {} }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } - - case "memory_relations": { - if (typeof args.memoryId !== "string" || !args.memoryId.trim()) { - return { - status_code: 400, - body: { error: "memoryId is required for memory_relations" }, - }; - } - const rawMaxHops = Number(args.maxHops); - const rawMinConf = Number(args.minConfidence); - const result = await sdk.trigger({ function_id: "mem::get-related", payload: { - memoryId: args.memoryId, - maxHops: Number.isFinite(rawMaxHops) ? rawMaxHops : 2, - minConfidence: Number.isFinite(rawMinConf) - ? Math.max(0, Math.min(1, rawMinConf)) - : 0, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } - - case "memory_claude_bridge_sync": { - const direction = (args.direction as string) || "write"; - const funcId = - direction === "read" - ? "mem::claude-bridge-read" - : "mem::claude-bridge-sync"; - try { - const result = await sdk.trigger({ - function_id: funcId, - payload: {}, - }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [ - { - type: "text", - text: "Claude bridge not enabled. Set CLAUDE_MEMORY_BRIDGE=true", - }, - ], - }, - }; - } - } - - case "memory_graph_query": { - try { - const payload: { - startNodeId?: string; - nodeType?: string; - maxDepth?: number; - query?: string; - } = {}; - const startNodeId = asNonEmptyString(args.startNodeId); - const nodeType = asNonEmptyString(args.nodeType); - const query = asNonEmptyString(args.query); - const maxDepth = asNumber(args.maxDepth); - if (startNodeId) payload.startNodeId = startNodeId; - if (nodeType) payload.nodeType = nodeType; - if (query) payload.query = query; - if (maxDepth !== undefined) payload.maxDepth = Math.max(1, Math.min(8, maxDepth)); - const result = await sdk.trigger({ - function_id: "mem::graph-query", - payload, - }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [ - { - type: "text", - text: "Knowledge graph not enabled. Set GRAPH_EXTRACTION_ENABLED=true", - }, - ], - }, - }; - } - } - - case "memory_consolidate": { - try { - const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: { - tier: args.tier as string, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [ - { - type: "text", - text: "Consolidation not enabled. Set CONSOLIDATION_ENABLED=true", - }, - ], - }, - }; - } - } - - case "memory_team_share": { - if ( - typeof args.itemId !== "string" || - typeof args.itemType !== "string" - ) { - return { - status_code: 400, - body: { error: "itemId and itemType are required" }, - }; - } - try { - const result = await sdk.trigger({ function_id: "mem::team-share", payload: { - itemId: args.itemId, - itemType: args.itemType, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [ - { - type: "text", - text: "Team memory not enabled. Set TEAM_ID and USER_ID", - }, - ], - }, - }; - } - } - - case "memory_team_feed": { - try { - const result = await sdk.trigger({ function_id: "mem::team-feed", payload: { - limit: typeof args.limit === "number" ? args.limit : 20, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [ - { - type: "text", - text: "Team memory not enabled. Set TEAM_ID and USER_ID", - }, - ], - }, - }; - } - } - - case "memory_audit": { - try { - const result = await sdk.trigger({ function_id: "mem::audit-query", payload: { - operation: args.operation as string, - limit: typeof args.limit === "number" ? args.limit : 50, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [{ type: "text", text: "Audit query failed" }], - isError: true, - }, - }; - } - } - - case "memory_governance_delete": { - if (typeof args.memoryIds !== "string") { - return { - status_code: 400, - body: { error: "memoryIds is required" }, - }; - } - const ids = (args.memoryIds as string) - .split(",") - .map((id) => id.trim()) - .filter(Boolean); - try { - const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: { - memoryIds: ids, - reason: args.reason as string, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [{ type: "text", text: "Governance delete failed" }], - isError: true, - }, - }; - } - } - - case "memory_snapshot_create": { - try { - const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: { - message: args.message as string, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(result, null, 2) }, - ], - }, - }; - } catch { - return { - status_code: 200, - body: { - content: [ - { - type: "text", - text: "Snapshots not enabled. Set SNAPSHOT_ENABLED=true", - }, - ], - }, - }; - } - } - - case "memory_action_create": { - if (typeof args.title !== "string" || !args.title.trim()) { - return { - status_code: 400, - body: { error: "title is required" }, - }; - } - const edges: Array<{ type: string; targetActionId: string }> = []; - if (typeof args.requires === "string" && args.requires.trim()) { - for (const id of args.requires.split(",").map((s: string) => s.trim()).filter(Boolean)) { - edges.push({ type: "requires", targetActionId: id }); - } - } - const tags = typeof args.tags === "string" && args.tags.trim() - ? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean) - : []; - const actionResult = await sdk.trigger({ function_id: "mem::action-create", payload: { - title: args.title, - description: args.description, - priority: args.priority, - project: args.project, - tags, - parentId: args.parentId, - edges: edges.length > 0 ? edges : undefined, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(actionResult, null, 2) }, - ], - }, - }; - } - - case "memory_action_update": { - if (typeof args.actionId !== "string" || !args.actionId.trim()) { - return { - status_code: 400, - body: { error: "actionId is required" }, - }; - } - const updateResult = await sdk.trigger({ function_id: "mem::action-update", payload: { - actionId: args.actionId, - status: args.status, - result: args.result, - priority: args.priority, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(updateResult, null, 2) }, - ], - }, - }; - } - - case "memory_frontier": { - const frontierResult = await sdk.trigger({ function_id: "mem::frontier", payload: { - project: args.project, - agentId: args.agentId, - limit: args.limit, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(frontierResult, null, 2) }, - ], - }, - }; - } - - case "memory_next": { - const nextResult = await sdk.trigger({ function_id: "mem::next", payload: { - project: args.project, - agentId: args.agentId, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(nextResult, null, 2) }, - ], - }, - }; - } + } - case "memory_lease": { - if ( - typeof args.actionId !== "string" || - typeof args.agentId !== "string" || - typeof args.operation !== "string" - ) { - return { - status_code: 400, - body: { error: "actionId, agentId, and operation are required" }, - }; - } - const op = args.operation as string; - let leaseResult; - if (op === "acquire") { - leaseResult = await sdk.trigger({ function_id: "mem::lease-acquire", payload: { - actionId: args.actionId, - agentId: args.agentId, - ttlMs: args.ttlMs, - } }); - } else if (op === "release") { - leaseResult = await sdk.trigger({ function_id: "mem::lease-release", payload: { - actionId: args.actionId, - agentId: args.agentId, - result: args.result, - } }); - } else if (op === "renew") { - leaseResult = await sdk.trigger({ function_id: "mem::lease-renew", payload: { - actionId: args.actionId, - agentId: args.agentId, - ttlMs: args.ttlMs, + const { name, arguments: args = {} } = req.body; + + try { + switch (name) { + case "memory_search": + case "memory_recall": + case "memory_smart_search": + case "memory_timeline": + case "memory_file_history": + case "memory_graph_query": + case "memory_vision_search": { + const scope = (args.scope as string) || "keyword"; + if (scope === "keyword" || name === "memory_recall") { + if (typeof args.query !== "string" || !args.query.trim()) { + return { status_code: 400, body: { error: "query is required" } }; + } + const format = typeof args.format === "string" ? args.format.trim().toLowerCase() : "full"; + if (!["full", "compact", "narrative"].includes(format)) { + return { status_code: 400, body: { error: "format must be one of: full, compact, narrative" } }; + } + const tokenBudget = asNumber(args.token_budget); + if (args.token_budget !== undefined && (!Number.isInteger(tokenBudget) || (tokenBudget ?? 0) < 1)) { + return { status_code: 400, body: { error: "token_budget must be a positive integer" } }; + } + const result = await sdk.trigger({ function_id: "mem::search", payload: { + query: args.query, + limit: typeof args.limit === "number" ? args.limit : 10, + format, + token_budget: tokenBudget, } }); - } else { - return { - status_code: 400, - body: { error: "operation must be acquire, release, or renew" }, - }; + const text = format === "narrative" && result && typeof result === "object" && "text" in (result as Record) && typeof (result as { text?: unknown }).text === "string" + ? (result as { text: string }).text + : JSON.stringify(result, null, 2); + return { status_code: 200, body: { content: [{ type: "text", text }] } }; } - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(leaseResult, null, 2) }, - ], - }, - }; + if (scope === "semantic") { + if (typeof args.query !== "string" || !args.query.trim()) { + return { status_code: 400, body: { error: "query is required" } }; + } + const expandIds = parseCsvList(args.expandIds).slice(0, 20); + const limit = Math.max(1, Math.min(100, asNumber(args.limit, 10) ?? 10)); + const result = await sdk.trigger({ function_id: "mem::smart-search", payload: { query: args.query, expandIds, limit } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (scope === "file") { + if (typeof args.files !== "string" || !args.files.trim()) { + return { status_code: 400, body: { error: "files is required" } }; + } + const fileList = parseCsvList(args.files); + if (!fileList.length) { + return { status_code: 400, body: { error: "files must contain at least one valid path" } }; + } + const payload: { sessionId?: string; files: string[] } = { files: fileList }; + const sessionId = asNonEmptyString(args.sessionId); + if (sessionId) payload.sessionId = sessionId; + const result = await sdk.trigger({ function_id: "mem::file-context", payload }); + return { status_code: 200, body: { content: [{ type: "text", text: (result as { context: string }).context || "No history found." }] } }; + } + if (scope === "time") { + if (typeof args.anchor !== "string" || !args.anchor.trim()) { + return { status_code: 400, body: { error: "anchor is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::timeline", payload: { anchor: args.anchor, project: (args.project as string) || undefined, before: (args.before as number) || 5, after: (args.after as number) || 5 } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (scope === "graph") { + try { + const payload: { startNodeId?: string; nodeType?: string; maxDepth?: number; query?: string } = {}; + const startNodeId = asNonEmptyString(args.startNodeId); + const nodeType = asNonEmptyString(args.nodeType); + const query = asNonEmptyString(args.query); + const maxDepth = asNumber(args.maxDepth); + if (startNodeId) payload.startNodeId = startNodeId; + if (nodeType) payload.nodeType = nodeType; + if (query) payload.query = query; + if (maxDepth !== undefined) payload.maxDepth = Math.max(1, Math.min(8, maxDepth)); + const result = await sdk.trigger({ function_id: "mem::graph-query", payload }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch { + return { status_code: 200, body: { content: [{ type: "text", text: "Knowledge graph not enabled. Set GRAPH_EXTRACTION_ENABLED=true" }] } }; + } + } + if (scope === "image") { + const queryText = typeof args.queryText === "string" ? args.queryText : undefined; + const queryImageRef = typeof args.queryImageRef === "string" ? args.queryImageRef : undefined; + const queryImageBase64 = typeof args.queryImageBase64 === "string" ? args.queryImageBase64 : undefined; + if (!queryText && !queryImageRef && !queryImageBase64) { + return { status_code: 400, body: { error: "queryText, queryImageRef, or queryImageBase64 required" } }; + } + const topK = Math.max(1, Math.min(50, asNumber(args.topK, 10) ?? 10)); + const sessionId = typeof args.sessionId === "string" ? args.sessionId : undefined; + const result = await sdk.trigger({ function_id: "mem::vision-search", payload: { queryText, queryImageRef, queryImageBase64, topK, sessionId } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid scope" } }; } - case "memory_routine_run": { - if (typeof args.routineId !== "string") { - return { - status_code: 400, - body: { error: "routineId is required" }, - }; + case "memory_store": + case "memory_save": + case "memory_compress_file": + case "memory_export": + case "memory_consolidate": + case "memory_claude_bridge_sync": + case "memory_mesh_sync": { + const rawOp = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal = asValidatedOperation(rawOp, ["save", "compress_file", "export", "consolidate", "claude_bridge", "mesh_sync"]); + const operation = opVal || (name === "memory_save" ? "save" : name === "memory_compress_file" ? "compress_file" : name === "memory_export" ? "export" : name === "memory_consolidate" ? "consolidate" : name === "memory_claude_bridge_sync" ? "claude_bridge" : name === "memory_mesh_sync" ? "mesh_sync" : "save"); + if (operation === "save") { + if (typeof args.content !== "string" || !args.content.trim()) { + return { status_code: 400, body: { error: "content is required" } }; + } + const type = (args.type as string) || "fact"; + const concepts = typeof args.concepts === "string" ? args.concepts.split(",").map((c: string) => c.trim()).filter(Boolean) : []; + const files = typeof args.files === "string" ? args.files.split(",").map((f: string) => f.trim()).filter(Boolean) : []; + const result = await sdk.trigger({ function_id: "mem::remember", payload: { content: args.content, type, concepts, files } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result) }] } }; } - const runResult = await sdk.trigger({ function_id: "mem::routine-run", payload: { - routineId: args.routineId, - project: args.project, - initiatedBy: args.initiatedBy, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(runResult, null, 2) }, - ], - }, - }; + if (operation === "compress_file") { + if (typeof args.filePath !== "string" || !args.filePath.trim()) { + return { status_code: 400, body: { error: "filePath is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::compress-file", payload: { filePath: args.filePath.trim() } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "export") { + const result = await sdk.trigger({ function_id: "mem::export", payload: {} }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "consolidate") { + try { + const result = await sdk.trigger({ function_id: "mem::consolidate-pipeline", payload: { tier: args.tier as string } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch { + return { status_code: 200, body: { content: [{ type: "text", text: "Consolidation not enabled. Set CONSOLIDATION_ENABLED=true" }] } }; + } + } + if (operation === "claude_bridge") { + const direction = (args.direction as string) || "write"; + const funcId = direction === "read" ? "mem::claude-bridge-read" : "mem::claude-bridge-sync"; + try { + const result = await sdk.trigger({ function_id: funcId, payload: {} }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch { + return { status_code: 200, body: { content: [{ type: "text", text: "Claude bridge not enabled. Set CLAUDE_MEMORY_BRIDGE=true" }] } }; + } + } + if (operation === "mesh_sync") { + const result = await sdk.trigger({ function_id: "mem::mesh-sync", payload: { peerId: args.peerId, direction: args.direction } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; } - case "memory_signal_send": { - if ( - typeof args.from !== "string" || - typeof args.content !== "string" - ) { - return { - status_code: 400, - body: { error: "from and content are required" }, - }; + case "memory_profile": { + if (typeof args.project !== "string" || !args.project.trim()) { + return { status_code: 400, body: { error: "project is required" } }; } - const sigResult = await sdk.trigger({ function_id: "mem::signal-send", payload: { - from: args.from, - to: args.to, - content: args.content, - type: args.type, - replyTo: args.replyTo, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(sigResult, null, 2) }, - ], - }, - }; + const result = await sdk.trigger({ function_id: "mem::profile", payload: { project: args.project, refresh: args.refresh === true || args.refresh === "true" } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - case "memory_signal_read": { - if (typeof args.agentId !== "string") { - return { - status_code: 400, - body: { error: "agentId is required" }, - }; - } - const readResult = await sdk.trigger({ function_id: "mem::signal-read", payload: { - agentId: args.agentId, - unreadOnly: args.unreadOnly === true || args.unreadOnly === "true", - threadId: args.threadId, - limit: args.limit, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(readResult, null, 2) }, - ], - }, - }; + case "memory_sessions": { + const sessions = await kv.list(KV.sessions); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify({ sessions }, null, 2) }] } }; } - case "memory_checkpoint": { - const cpOp = args.operation as string; - if (!cpOp) { - return { - status_code: 400, - body: { error: "operation is required" }, - }; + case "task": + case "memory_action_create": + case "memory_action_update": + case "memory_routine_run": { + const rawOp = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal = asValidatedOperation(rawOp, ["create", "update", "routine_run"]); + const operation = opVal || (name === "memory_action_create" ? "create" : name === "memory_action_update" ? "update" : name === "memory_routine_run" ? "routine_run" : "create"); + if (operation === "create") { + if (typeof args.title !== "string" || !args.title.trim()) { + return { status_code: 400, body: { error: "title is required" } }; + } + const edges: Array<{ type: string; targetActionId: string }> = []; + if (typeof args.requires === "string" && args.requires.trim()) { + for (const id of args.requires.split(",").map((s: string) => s.trim()).filter(Boolean)) { + edges.push({ type: "requires", targetActionId: id }); + } + } + const tags = typeof args.tags === "string" && args.tags.trim() ? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean) : []; + const result = await sdk.trigger({ function_id: "mem::action-create", payload: { title: args.title, description: args.description, priority: args.priority, project: args.project, tags, parentId: args.parentId, edges: edges.length > 0 ? edges : undefined } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - let cpResult; - if (cpOp === "create") { - const linkedIds = typeof args.linkedActionIds === "string" && args.linkedActionIds.trim() - ? args.linkedActionIds.split(",").map((s: string) => s.trim()) - : []; - cpResult = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: { - name: args.name, - description: args.description, - type: args.type, - linkedActionIds: linkedIds, - } }); - } else if (cpOp === "resolve") { - if (typeof args.checkpointId !== "string" || !args.checkpointId.trim()) { - return { - status_code: 400, - body: { error: "checkpointId is required for resolve operation" }, - }; + if (operation === "update") { + if (typeof args.actionId !== "string" || !args.actionId.trim()) { + return { status_code: 400, body: { error: "actionId is required" } }; } - cpResult = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: { - checkpointId: args.checkpointId, - status: args.status, - } }); - } else if (cpOp === "list") { - cpResult = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: { - status: args.status, - type: args.type, - } }); - } else { - return { - status_code: 400, - body: { error: "operation must be create, resolve, or list" }, - }; + const result = await sdk.trigger({ function_id: "mem::action-update", payload: { actionId: args.actionId, status: args.status, result: args.result, priority: args.priority } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(cpResult, null, 2) }, - ], - }, - }; + if (operation === "routine_run") { + if (typeof args.routineId !== "string") { + return { status_code: 400, body: { error: "routineId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::routine-run", payload: { routineId: args.routineId, project: args.project, initiatedBy: args.initiatedBy } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; } - case "memory_mesh_sync": { - const meshResult = await sdk.trigger({ function_id: "mem::mesh-sync", payload: { - peerId: args.peerId, - direction: args.direction, - } }); - return { - status_code: 200, - body: { - content: [ - { type: "text", text: JSON.stringify(meshResult, null, 2) }, - ], - }, - }; + case "task_plan": + case "memory_next": + case "memory_frontier": + case "memory_lease": { + const rawOp2 = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal2 = asValidatedOperation(rawOp2, ["next", "frontier", "lease_acquire", "lease_release", "lease_renew"]); + const operation = opVal2 || (name === "memory_next" ? "next" : name === "memory_frontier" ? "frontier" : name === "memory_lease" ? "lease_acquire" : "next"); + if (operation === "next" || name === "memory_next") { + const result = await sdk.trigger({ function_id: "mem::next", payload: { project: args.project, agentId: args.agentId } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "frontier" || name === "memory_frontier") { + const result = await sdk.trigger({ function_id: "mem::frontier", payload: { project: args.project, agentId: args.agentId, limit: args.limit } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "lease_acquire" || operation === "lease_release" || operation === "lease_renew") { + if (typeof args.actionId !== "string" || typeof args.agentId !== "string") { + return { status_code: 400, body: { error: "actionId and agentId are required" } }; + } + let result; + if (operation === "lease_acquire") { + result = await sdk.trigger({ function_id: "mem::lease-acquire", payload: { actionId: args.actionId, agentId: args.agentId, ttlMs: args.ttlMs } }); + } else if (operation === "lease_release") { + result = await sdk.trigger({ function_id: "mem::lease-release", payload: { actionId: args.actionId, agentId: args.agentId, result: args.result } }); + } else { + result = await sdk.trigger({ function_id: "mem::lease-renew", payload: { actionId: args.actionId, agentId: args.agentId, ttlMs: args.ttlMs } }); + } + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; } - case "memory_sentinel_create": { - let snlConfig: Record = {}; - if (typeof args.config === "object" && args.config !== null) { - snlConfig = args.config as Record; - } else if (typeof args.config === "string" && args.config.trim()) { - try { snlConfig = JSON.parse(args.config); } catch { return { status_code: 400, body: { error: "invalid config JSON" } }; } + case "signal": + case "memory_signal_send": + case "memory_signal_read": { + const rawOp3 = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal3 = asValidatedOperation(rawOp3, ["send", "read"]); + const operation = opVal3 || (name === "memory_signal_send" ? "send" : name === "memory_signal_read" ? "read" : "send"); + if (operation === "send" || name === "memory_signal_send") { + if (typeof args.from !== "string" || typeof args.content !== "string") { + return { status_code: 400, body: { error: "from and content are required" } }; + } + const result = await sdk.trigger({ function_id: "mem::signal-send", payload: { from: args.from, to: args.to, content: args.content, type: args.type, replyTo: args.replyTo } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "read" || name === "memory_signal_read") { + if (typeof args.agentId !== "string") { + return { status_code: 400, body: { error: "agentId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::signal-read", payload: { agentId: args.agentId, unreadOnly: args.unreadOnly === true || args.unreadOnly === "true", threadId: args.threadId, limit: args.limit } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - const snlLinked = parseCsvList(args.linkedActionIds); - const expiresInMs = asNumber(args.expiresInMs); - const name = asNonEmptyString(args.name); - const type = asNonEmptyString(args.type); - const payload: { - name?: string; - type?: string; - config: Record; - linkedActionIds?: string[]; - expiresInMs?: number; - } = { config: snlConfig }; - if (name) payload.name = name; - if (type) payload.type = type; - if (snlLinked.length) payload.linkedActionIds = snlLinked; - if (expiresInMs !== undefined) payload.expiresInMs = Math.max(0, expiresInMs); - const snlResult = await sdk.trigger({ - function_id: "mem::sentinel-create", - payload, - }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlResult, null, 2) }] } }; + return { status_code: 400, body: { error: "Invalid operation" } }; } + case "checkpoint": + case "memory_checkpoint": + case "memory_sentinel_create": case "memory_sentinel_trigger": { - let snlTrigPayload: unknown; - if (args.result !== undefined && args.result !== null) { - if (typeof args.result === "string") { - try { snlTrigPayload = JSON.parse(args.result); } catch { return { status_code: 400, body: { error: "invalid result JSON" } }; } + const rawOp4 = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal4 = asValidatedOperation(rawOp4, ["create", "sentinel_create", "sentinel_trigger"]); + const operation = opVal4 || (name === "memory_sentinel_create" ? "sentinel_create" : name === "memory_sentinel_trigger" ? "sentinel_trigger" : "create"); + if (operation === "create" || name === "memory_checkpoint") { + const cpOp = args.operation as string; + if (!cpOp) { + return { status_code: 400, body: { error: "operation is required" } }; + } + let cpResult; + if (cpOp === "create") { + const linkedIds = typeof args.linkedActionIds === "string" && args.linkedActionIds.trim() ? args.linkedActionIds.split(",").map((s: string) => s.trim()) : []; + cpResult = await sdk.trigger({ function_id: "mem::checkpoint-create", payload: { name: args.name, description: args.description, type: args.type, linkedActionIds: linkedIds } }); + } else if (cpOp === "resolve") { + if (typeof args.checkpointId !== "string" || !args.checkpointId.trim()) { + return { status_code: 400, body: { error: "checkpointId is required for resolve operation" } }; + } + cpResult = await sdk.trigger({ function_id: "mem::checkpoint-resolve", payload: { checkpointId: args.checkpointId, status: args.status } }); + } else if (cpOp === "list") { + cpResult = await sdk.trigger({ function_id: "mem::checkpoint-list", payload: { status: args.status, type: args.type } }); } else { - snlTrigPayload = args.result; + return { status_code: 400, body: { error: "operation must be create, resolve, or list" } }; } + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(cpResult, null, 2) }] } }; } - const sentinelId = asNonEmptyString(args.sentinelId); - if (!sentinelId) { - return { - status_code: 400, - body: { error: "sentinelId is required for memory_sentinel_trigger" }, - }; + if (operation === "sentinel_create" || name === "memory_sentinel_create") { + let snlConfig: Record = {}; + if (typeof args.config === "object" && args.config !== null) { + snlConfig = args.config as Record; + } else if (typeof args.config === "string" && args.config.trim()) { + try { snlConfig = JSON.parse(args.config); } catch { return { status_code: 400, body: { error: "invalid config JSON" } }; } + } + const snlLinked = parseCsvList(args.linkedActionIds); + const expiresInMs = asNumber(args.expiresInMs); + const name = asNonEmptyString(args.name); + const type = asNonEmptyString(args.type); + const payload: { name?: string; type?: string; config: Record; linkedActionIds?: string[]; expiresInMs?: number } = { config: snlConfig }; + if (name) payload.name = name; + if (type) payload.type = type; + if (snlLinked.length) payload.linkedActionIds = snlLinked; + if (expiresInMs !== undefined) payload.expiresInMs = Math.max(0, expiresInMs); + const result = await sdk.trigger({ function_id: "mem::sentinel-create", payload }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - const snlTrigResult = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: { - sentinelId, - result: snlTrigPayload, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(snlTrigResult, null, 2) }] } }; - } - - case "memory_sketch_create": { - const title = asNonEmptyString(args.title); - if (!title) { - return { - status_code: 400, - body: { error: "title is required for memory_sketch_create" }, - }; + if (operation === "sentinel_trigger" || name === "memory_sentinel_trigger") { + let snlTrigPayload: unknown; + if (args.result !== undefined && args.result !== null) { + if (typeof args.result === "string") { + try { snlTrigPayload = JSON.parse(args.result); } catch { return { status_code: 400, body: { error: "invalid result JSON" } }; } + } else { + snlTrigPayload = args.result; + } + } + const sentinelId = asNonEmptyString(args.sentinelId); + if (!sentinelId) { + return { status_code: 400, body: { error: "sentinelId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::sentinel-trigger", payload: { sentinelId, result: snlTrigPayload } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - const sketchPayload = { - title, - description: asNonEmptyString(args.description), - expiresInMs: asNumber(args.expiresInMs), - project: asNonEmptyString(args.project), - }; - const skResult = await sdk.trigger({ - function_id: "mem::sketch-create", - payload: sketchPayload, - }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skResult, null, 2) }] } }; + return { status_code: 400, body: { error: "Invalid operation" } }; } + case "sketch": + case "memory_sketch_create": case "memory_sketch_promote": { - const sketchId = asNonEmptyString(args.sketchId); - if (!sketchId) { - return { - status_code: 400, - body: { error: "sketchId is required for memory_sketch_promote" }, - }; + const rawOp5 = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal5 = asValidatedOperation(rawOp5, ["create", "promote"]); + const operation = opVal5 || (name === "memory_sketch_create" ? "create" : name === "memory_sketch_promote" ? "promote" : "create"); + if (operation === "create" || name === "memory_sketch_create") { + const title = asNonEmptyString(args.title); + if (!title) { + return { status_code: 400, body: { error: "title is required" } }; + } + const sketchPayload = { title, description: asNonEmptyString(args.description), expiresInMs: asNumber(args.expiresInMs), project: asNonEmptyString(args.project) }; + const result = await sdk.trigger({ function_id: "mem::sketch-create", payload: sketchPayload }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - const skpResult = await sdk.trigger({ function_id: "mem::sketch-promote", payload: { - sketchId, - project: args.project, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(skpResult, null, 2) }] } }; + if (operation === "promote" || name === "memory_sketch_promote") { + const sketchId = asNonEmptyString(args.sketchId); + if (!sketchId) { + return { status_code: 400, body: { error: "sketchId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::sketch-promote", payload: { sketchId, project: args.project } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; } + case "crystal": case "memory_crystallize": { if (typeof args.actionIds !== "string" || !args.actionIds.trim()) { return { status_code: 400, body: { error: "actionIds is required" } }; } const crysIds = args.actionIds.split(",").map((s: string) => s.trim()).filter(Boolean); - const crysResult = await sdk.trigger({ function_id: "mem::crystallize", payload: { - actionIds: crysIds, - project: args.project, - sessionId: args.sessionId, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(crysResult, null, 2) }] } }; + const result = await sdk.trigger({ function_id: "mem::crystallize", payload: { actionIds: crysIds, project: args.project, sessionId: args.sessionId } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - case "memory_diagnose": { - const diagCats = typeof args.categories === "string" && args.categories.trim() - ? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean) - : undefined; - const diagResult = await sdk.trigger({ function_id: "mem::diagnose", payload: { categories: diagCats } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(diagResult, null, 2) }] } }; + case "lesson": + case "memory_lesson_save": + case "memory_lesson_recall": + case "memory_lesson_list": + case "memory_lesson_strengthen": { + const rawOp6 = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal6 = asValidatedOperation(rawOp6, ["save", "recall", "list", "strengthen"]); + const operation = opVal6 || (name === "memory_lesson_save" ? "save" : name === "memory_lesson_recall" ? "recall" : name === "memory_lesson_list" ? "list" : name === "memory_lesson_strengthen" ? "strengthen" : "save"); + if (operation === "save" || name === "memory_lesson_save") { + if (typeof args.content !== "string" || !args.content.trim()) { + return { status_code: 400, body: { error: "content is required" } }; + } + const lessonTags = typeof args.tags === "string" && args.tags.trim() ? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean) : []; + const result = await sdk.trigger({ function_id: "mem::lesson-save", payload: { content: args.content, context: args.context || "", confidence: args.confidence, project: args.project, tags: lessonTags, source: "manual" } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "recall" || name === "memory_lesson_recall") { + if (typeof args.query !== "string" || !args.query.trim()) { + return { status_code: 400, body: { error: "query is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lesson-recall", payload: { query: args.query, project: args.project, minConfidence: args.minConfidence, limit: args.limit } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "list" || name === "memory_lesson_list") { + const project = typeof args.project === "string" ? args.project : undefined; + const source = typeof args.source === "string" && ["manual", "crystal", "consolidation"].includes(args.source) ? args.source : undefined; + const minConfidence = typeof args.minConfidence === "number" ? args.minConfidence : undefined; + const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 50; + const result = await sdk.trigger({ function_id: "mem::lesson-list", payload: { project, source, minConfidence, limit } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "strengthen" || name === "memory_lesson_strengthen") { + if (typeof args.lessonId !== "string" || !args.lessonId.trim()) { + return { status_code: 400, body: { error: "lessonId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: args.lessonId } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; } - case "memory_heal": { - const healCats = typeof args.categories === "string" && args.categories.trim() - ? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean) - : undefined; - const healResult = await sdk.trigger({ function_id: "mem::heal", payload: { - categories: healCats, - dryRun: args.dryRun === true || args.dryRun === "true", - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(healResult, null, 2) }] } }; + case "insight": + case "memory_insight_list": + case "memory_insight_delete": { + const rawOp = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal = asValidatedOperation(rawOp, ["list", "delete"]); + const operation = opVal || (name === "memory_insight_delete" ? "delete" : "list"); + if (operation === "list" || name === "memory_insight_list") { + const result = await sdk.trigger({ function_id: "mem::insight-list", payload: { project: args.project, minConfidence: args.minConfidence, limit: args.limit } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "delete") { + if (typeof args.insightId !== "string" || !args.insightId.trim()) { + return { status_code: 400, body: { error: "insightId is required" } }; + } + const result = await sdk.trigger({ function_id: "mem::insight-delete", payload: { insightId: args.insightId } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; + } + + case "slot": + case "memory_slot_list": + case "memory_slot_get": + case "memory_slot_create": + case "memory_slot_append": + case "memory_slot_replace": + case "memory_slot_delete": { + const rawOp7 = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal7 = asValidatedOperation(rawOp7, ["list", "get", "create", "append", "replace", "delete"]); + const operation = opVal7 || (name === "memory_slot_list" ? "list" : name === "memory_slot_get" ? "get" : name === "memory_slot_create" ? "create" : name === "memory_slot_append" ? "append" : name === "memory_slot_replace" ? "replace" : name === "memory_slot_delete" ? "delete" : "list"); + if (operation === "list" || name === "memory_slot_list") { + const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "get" || name === "memory_slot_get") { + const label = asNonEmptyString(args.label); + if (!label) return { status_code: 400, body: { error: "label required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "create" || name === "memory_slot_create") { + const label = asNonEmptyString(args.label); + if (!label) return { status_code: 400, body: { error: "label required" } }; + const payload: Record = { label }; + if (typeof args.content === "string") payload.content = args.content; + if (typeof args.description === "string") payload.description = args.description; + if (typeof args.sizeLimit === "number") payload.sizeLimit = args.sizeLimit; + if (args.pinned === false || args.pinned === "false") payload.pinned = false; + else if (args.pinned === true || args.pinned === "true") payload.pinned = true; + if (args.scope === "global" || args.scope === "project") payload.scope = args.scope; + const result = await sdk.trigger({ function_id: "mem::slot-create", payload }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "append" || name === "memory_slot_append") { + const label = asNonEmptyString(args.label); + const text = typeof args.text === "string" ? args.text : null; + if (!label || !text) return { status_code: 400, body: { error: "label and text required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "replace" || name === "memory_slot_replace") { + const label = asNonEmptyString(args.label); + if (!label || typeof args.content !== "string") { + return { status_code: 400, body: { error: "label and content (string) required" } }; + } + const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content: args.content } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "delete" || name === "memory_slot_delete") { + const label = asNonEmptyString(args.label); + if (!label) return { status_code: 400, body: { error: "label required" } }; + const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; + } + + case "admin": + case "memory_diagnose": + case "memory_heal": + case "memory_audit": + case "memory_governance_delete": + case "memory_obsidian_export": + case "memory_verify": { + const operation = (args.operation as string) || (name === "memory_diagnose" ? "diagnose" : name === "memory_heal" ? "heal" : name === "memory_audit" ? "audit" : name === "memory_governance_delete" ? "delete" : name === "memory_obsidian_export" ? "obsidian" : name === "memory_verify" ? "verify" : "diagnose"); + if (operation === "diagnose" || name === "memory_diagnose") { + const cats = typeof args.categories === "string" && args.categories.trim() ? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean) : undefined; + const result = await sdk.trigger({ function_id: "mem::diagnose", payload: { categories: cats } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "heal" || name === "memory_heal") { + const cats = typeof args.categories === "string" && args.categories.trim() ? args.categories.split(",").map((s: string) => s.trim()).filter(Boolean) : undefined; + const result = await sdk.trigger({ function_id: "mem::heal", payload: { categories: cats, dryRun: args.dryRun === true || args.dryRun === "true" } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "audit" || name === "memory_audit") { + try { + const result = await sdk.trigger({ function_id: "mem::audit-query", payload: { operation: args.operation as string, limit: typeof args.limit === "number" ? args.limit : 50 } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch (err) { + return { status_code: 500, body: { content: [{ type: "text", text: "Audit query failed: " + (err instanceof Error ? err.message : String(err)) }], isError: true } }; + } + } + if (operation === "delete" || name === "memory_governance_delete") { + const rawEntityType = args.entityType; + const entityType = typeof rawEntityType === "string" && rawEntityType.trim() ? rawEntityType.trim() : "memory"; + if (entityType === "insight") { + if (typeof args.insightIds !== "string") { + return { status_code: 400, body: { error: "insightIds is required" } }; + } + const MAX_IDS = 1000; + const ids = args.insightIds.split(",").map((id: string) => id.trim()).filter(Boolean).slice(0, MAX_IDS); + try { + const result = await sdk.trigger({ function_id: "mem::insight-delete", payload: { insightIds: ids, reason: args.reason as string } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch (err) { + return { status_code: 500, body: { content: [{ type: "text", text: "Insight delete failed: " + (err instanceof Error ? err.message : String(err)) }], isError: true } }; + } + } + if (typeof args.memoryIds !== "string") { + return { status_code: 400, body: { error: "memoryIds is required" } }; + } + const ids = (args.memoryIds as string).split(",").map((id: string) => id.trim()).filter(Boolean).slice(0, MAX_IDS); + try { + const result = await sdk.trigger({ function_id: "mem::governance-delete", payload: { memoryIds: ids, reason: args.reason as string } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch (err) { + return { status_code: 500, body: { content: [{ type: "text", text: "Governance delete failed: " + (err instanceof Error ? err.message : String(err)) }], isError: true } }; + } + } + if (operation === "obsidian" || name === "memory_obsidian_export") { + const exportTypes = typeof args.types === "string" && args.types.trim() ? args.types.split(",").map((t: string) => t.trim()).filter(Boolean) : undefined; + const result = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { vaultDir: args.vaultDir, types: exportTypes } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + if (operation === "verify" || name === "memory_verify") { + if (!args.id || typeof args.id !== "string") { + return { status_code: 400, body: { error: "id is required" } }; + } + const rawEntityType = args.entityType; + const entityType = typeof rawEntityType === "string" && rawEntityType.trim() ? rawEntityType.trim() : "memory"; + const result = await sdk.trigger({ function_id: "mem::verify", payload: { id: args.id, entityType } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; } case "memory_facet_tag": { - const fctResult = await sdk.trigger({ function_id: "mem::facet-tag", payload: { - targetId: args.targetId, - targetType: args.targetType, - dimension: args.dimension, - value: args.value, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fctResult, null, 2) }] } }; + const result = await sdk.trigger({ function_id: "mem::facet-tag", payload: { targetId: args.targetId, targetType: args.targetType, dimension: args.dimension, value: args.value } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } case "memory_facet_query": { @@ -1053,201 +649,52 @@ export function registerMcpEndpoints( if (args.matchAny !== undefined && typeof args.matchAny !== "string") { return { status_code: 400, body: { error: "matchAny must be a string" } }; } - const fqAll = typeof args.matchAll === "string" && args.matchAll.trim() - ? args.matchAll.split(",").map((s: string) => s.trim()).filter(Boolean) - : undefined; - const fqAny = typeof args.matchAny === "string" && args.matchAny.trim() - ? args.matchAny.split(",").map((s: string) => s.trim()).filter(Boolean) - : undefined; - const fqResult = await sdk.trigger({ function_id: "mem::facet-query", payload: { - matchAll: fqAll, - matchAny: fqAny, - targetType: args.targetType, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(fqResult, null, 2) }] } }; + const fqAll = typeof args.matchAll === "string" && args.matchAll.trim() ? args.matchAll.split(",").map((s: string) => s.trim()).filter(Boolean) : undefined; + const fqAny = typeof args.matchAny === "string" && args.matchAny.trim() ? args.matchAny.split(",").map((s: string) => s.trim()).filter(Boolean) : undefined; + const result = await sdk.trigger({ function_id: "mem::facet-query", payload: { matchAll: fqAll, matchAny: fqAny, targetType: args.targetType } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } - case "memory_verify": { - if (!args.id || typeof args.id !== "string") { - return { status_code: 400, body: { error: "id is required" } }; + case "memory_team_share": { + if (typeof args.itemId !== "string" || typeof args.itemType !== "string") { + return { status_code: 400, body: { error: "itemId and itemType are required" } }; } - const verifyResult = await sdk.trigger({ function_id: "mem::verify", payload: { id: args.id } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(verifyResult, null, 2) }] } }; - } - - case "memory_lesson_save": { - if (typeof args.content !== "string" || !args.content.trim()) { - return { status_code: 400, body: { error: "content is required" } }; + try { + const result = await sdk.trigger({ function_id: "mem::team-share", payload: { itemId: args.itemId, itemType: args.itemType } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch { + return { status_code: 200, body: { content: [{ type: "text", text: "Team memory not enabled. Set TEAM_ID and USER_ID" }] } }; } - const lessonTags = typeof args.tags === "string" && args.tags.trim() - ? args.tags.split(",").map((t: string) => t.trim()).filter(Boolean) - : []; - const lessonSaveResult = await sdk.trigger({ function_id: "mem::lesson-save", payload: { - content: args.content, - context: args.context || "", - confidence: args.confidence, - project: args.project, - tags: lessonTags, - source: "manual", - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonSaveResult, null, 2) }] } }; } - case "memory_lesson_recall": { - if (typeof args.query !== "string" || !args.query.trim()) { - return { status_code: 400, body: { error: "query is required" } }; + case "memory_team_feed": { + try { + const result = await sdk.trigger({ function_id: "mem::team-feed", payload: { limit: typeof args.limit === "number" ? args.limit : 20 } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch { + return { status_code: 200, body: { content: [{ type: "text", text: "Team memory not enabled. Set TEAM_ID and USER_ID" }] } }; } - const lessonRecallResult = await sdk.trigger({ function_id: "mem::lesson-recall", payload: { - query: args.query, - project: args.project, - minConfidence: args.minConfidence, - limit: args.limit, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonRecallResult, null, 2) }] } }; } - case "memory_lesson_list": { - const project = typeof args.project === "string" ? args.project : undefined; - const source = - typeof args.source === "string" && - ["manual", "crystal", "consolidation"].includes(args.source) - ? args.source - : undefined; - const minConfidence = - typeof args.minConfidence === "number" ? args.minConfidence : undefined; - const limit = - typeof args.limit === "number" && args.limit > 0 ? args.limit : 50; - const lessonListResult = await sdk.trigger({ - function_id: "mem::lesson-list", - payload: { project, source, minConfidence, limit }, - }); - return { - status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(lessonListResult, null, 2) }] }, - }; - } - - case "memory_lesson_strengthen": { - if (typeof args.lessonId !== "string" || !args.lessonId.trim()) { - return { status_code: 400, body: { error: "lessonId is required" } }; + case "memory_snapshot_create": { + try { + const result = await sdk.trigger({ function_id: "mem::snapshot-create", payload: { message: args.message as string } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } catch { + return { status_code: 200, body: { content: [{ type: "text", text: "Snapshots not enabled. Set SNAPSHOT_ENABLED=true" }] } }; } - const lessonStrengthenResult = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { - lessonId: args.lessonId, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(lessonStrengthenResult, null, 2) }] } }; } case "memory_reflect": { - const reflectResult = await sdk.trigger({ function_id: "mem::reflect", payload: { - project: args.project, - maxClusters: args.maxClusters, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(reflectResult, null, 2) }] } }; - } - - case "memory_insight_list": { - const insightListResult = await sdk.trigger({ function_id: "mem::insight-list", payload: { - project: args.project, - minConfidence: args.minConfidence, - limit: args.limit, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(insightListResult, null, 2) }] } }; - } - - case "memory_obsidian_export": { - const exportTypes = typeof args.types === "string" && args.types.trim() - ? args.types.split(",").map((t: string) => t.trim()).filter(Boolean) - : undefined; - const obsidianResult = await sdk.trigger({ function_id: "mem::obsidian-export", payload: { - vaultDir: args.vaultDir, - types: exportTypes, - } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(obsidianResult, null, 2) }] } }; - } - - case "memory_slot_list": { - const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} }); - return { - status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, - }; - } - - case "memory_slot_get": { - const label = asNonEmptyString(args.label); - if (!label) return { status_code: 400, body: { error: "label required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } }); - return { - status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, - }; - } - - case "memory_slot_create": { - const label = asNonEmptyString(args.label); - if (!label) return { status_code: 400, body: { error: "label required" } }; - const payload: Record = { label }; - if (typeof args.content === "string") payload.content = args.content; - if (typeof args.description === "string") payload.description = args.description; - if (typeof args.sizeLimit === "number") payload.sizeLimit = args.sizeLimit; - // Accept boolean and string-boolean forms; MCP clients bind either - // depending on their JSON schema wrapper. - if (args.pinned === false || args.pinned === "false") payload.pinned = false; - else if (args.pinned === true || args.pinned === "true") payload.pinned = true; - if (args.scope === "global" || args.scope === "project") payload.scope = args.scope; - const result = await sdk.trigger({ function_id: "mem::slot-create", payload }); - return { - status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, - }; - } - - case "memory_slot_append": { - const label = asNonEmptyString(args.label); - const text = typeof args.text === "string" ? args.text : null; - if (!label || !text) return { status_code: 400, body: { error: "label and text required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } }); - return { - status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, - }; - } - - case "memory_slot_replace": { - const label = asNonEmptyString(args.label); - if (!label || typeof args.content !== "string") { - return { status_code: 400, body: { error: "label and content (string) required" } }; - } - const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content: args.content } }); - return { - status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, - }; - } - - case "memory_slot_delete": { - const label = asNonEmptyString(args.label); - if (!label) return { status_code: 400, body: { error: "label required" } }; - const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } }); - return { - status_code: 200, - body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] }, - }; + const result = await sdk.trigger({ function_id: "mem::reflect", payload: { project: args.project, maxClusters: args.maxClusters } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } default: - return { - status_code: 400, - body: { error: `Unknown tool: ${name}` }, - }; + return { status_code: 400, body: { error: `Unknown tool: ${name}` } }; } } catch (err) { - return { - status_code: 500, - body: { - error: "Internal error", - }, - }; + return { status_code: 500, body: { error: "Internal error" } }; } }, ); @@ -1297,7 +744,7 @@ export function registerMcpEndpoints( }, ]; - sdk.registerFunction("mcp::resources::list", + sdk.registerFunction("mcp::resources::list", async (req: ApiRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1310,7 +757,7 @@ export function registerMcpEndpoints( config: { api_path: "/agentmemory/mcp/resources", http_method: "GET" }, }); - sdk.registerFunction("mcp::resources::read", + sdk.registerFunction("mcp::resources::read", async (req: ApiRequest<{ uri: string }>): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1583,7 +1030,7 @@ export function registerMcpEndpoints( }, ]; - sdk.registerFunction("mcp::prompts::list", + sdk.registerFunction("mcp::prompts::list", async (req: ApiRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; @@ -1596,7 +1043,7 @@ export function registerMcpEndpoints( config: { api_path: "/agentmemory/mcp/prompts", http_method: "GET" }, }); - sdk.registerFunction("mcp::prompts::get", + sdk.registerFunction("mcp::prompts::get", async ( req: ApiRequest<{ name: string; arguments?: Record }>, ): Promise => { @@ -1721,4 +1168,4 @@ export function registerMcpEndpoints( function_id: "mcp::prompts::get", config: { api_path: "/agentmemory/mcp/prompts/get", http_method: "POST" }, }); -} +} \ No newline at end of file diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts index ae1f4f36f1..c381a156f4 100644 --- a/src/mcp/standalone.ts +++ b/src/mcp/standalone.ts @@ -14,13 +14,71 @@ import { } from "./rest-proxy.js"; const IMPLEMENTED_TOOLS = new Set([ - "memory_save", + // New 13 consolidated tools + "memory_search", + "memory_store", + "memory_profile", + "memory_sessions", + "task", + "task_plan", + "signal", + "checkpoint", + "sketch", + "crystal", + "lesson", + "insight", + "slot", + // Legacy aliases (forwarded to server via generic proxy) "memory_recall", "memory_smart_search", - "memory_sessions", + "memory_save", + "memory_compress_file", "memory_export", + "memory_consolidate", + "memory_claude_bridge_sync", + "memory_mesh_sync", + "memory_file_history", + "memory_graph_query", + "memory_vision_search", + "memory_timeline", + "memory_relations", + "memory_action_create", + "memory_action_update", + "memory_frontier", + "memory_next", + "memory_lease", + "memory_routine_run", + "memory_signal_send", + "memory_signal_read", + "memory_checkpoint", + "memory_sentinel_create", + "memory_sentinel_trigger", + "memory_sketch_create", + "memory_sketch_promote", + "memory_crystallize", + "memory_diagnose", + "memory_heal", "memory_audit", "memory_governance_delete", + "memory_obsidian_export", + "memory_verify", + "memory_lesson_save", + "memory_lesson_recall", + "memory_lesson_list", + "memory_lesson_strengthen", + "memory_insight_list", + "memory_slot_list", + "memory_slot_get", + "memory_slot_create", + "memory_slot_append", + "memory_slot_replace", + "memory_slot_delete", + "memory_facet_tag", + "memory_facet_query", + "memory_team_share", + "memory_team_feed", + "memory_snapshot_create", + "memory_reflect", ]); const SERVER_INFO = { @@ -83,6 +141,7 @@ function textResponse(payload: unknown, pretty = false): { interface Validated { tool: string; + operation?: string; content?: string; type?: string; concepts?: string[]; @@ -91,54 +150,124 @@ interface Validated { limit?: number; memoryIds?: string[]; reason?: string; + label?: string; + text?: string; + insightIds?: string[]; } function validate(toolName: string, args: Record): Validated { - if (!IMPLEMENTED_TOOLS.has(toolName)) { - throw new Error(`Unknown tool: ${toolName}`); - } const v: Validated = { tool: toolName }; switch (toolName) { - case "memory_save": { - const content = args["content"]; - if (typeof content !== "string" || !content.trim()) { - throw new Error("content is required"); - } - v.content = content; - v.type = (args["type"] as string) || "fact"; - v.concepts = normalizeList(args["concepts"]); - v.files = normalizeList(args["files"]); - return v; - } + case "memory_search": case "memory_recall": - case "memory_smart_search": { - const query = args["query"]; - if (typeof query !== "string" || !query.trim()) { - throw new Error("query is required"); - } - v.query = query.trim(); + case "memory_smart_search": + case "memory_timeline": + case "memory_file_history": + case "memory_graph_query": + case "memory_vision_search": { + const q = args["query"]; + if (typeof q !== "string" || !q.trim()) throw new Error("query is required"); + v.query = String(q).trim(); v.limit = parseLimit(args["limit"]); + v.operation = args["scope"] as string || args["operation"] as string || "keyword"; return v; } - case "memory_sessions": { - v.limit = parseLimit(args["limit"], 20); + case "memory_store": + case "memory_save": + case "memory_compress_file": + case "memory_export": + case "memory_consolidate": + case "memory_claude_bridge_sync": + case "memory_mesh_sync": { + const op = args["operation"] as string; + v.operation = (typeof op === "string" && op.trim()) ? op.trim() : "save"; + if (v.operation === "save") { + const c = args["content"]; + if (typeof c !== "string" || !c.trim()) throw new Error("content is required for save"); + v.content = c; + v.type = (args["type"] as string) || "fact"; + v.concepts = normalizeList(args["concepts"]); + v.files = normalizeList(args["files"]); + } return v; } - case "memory_governance_delete": { - const ids = normalizeList(args["memoryIds"]); - if (ids.length === 0) throw new Error("memoryIds is required"); - v.memoryIds = ids; - v.reason = (args["reason"] as string) || "plugin skill request"; + case "memory_profile": { + v.operation = "profile"; return v; } - case "memory_export": + case "memory_sessions": { + v.operation = "sessions"; + v.limit = parseLimit(args["limit"], 20); return v; - case "memory_audit": { - v.limit = parseLimit(args["limit"], 50); + } + case "memory_action_create": + case "memory_action_update": + case "memory_routine_run": + case "memory_next": + case "memory_frontier": + case "memory_lease": + case "memory_signal_send": + case "memory_signal_read": + case "memory_checkpoint": + case "memory_sentinel_create": + case "memory_sentinel_trigger": + case "memory_sketch_create": + case "memory_sketch_promote": + case "memory_crystallize": + case "memory_diagnose": + case "memory_heal": + case "memory_audit": + case "memory_governance_delete": + case "memory_obsidian_export": + case "memory_verify": + case "memory_lesson_save": + case "memory_lesson_recall": + case "memory_lesson_list": + case "memory_lesson_strengthen": + case "memory_insight_list": + case "memory_slot_list": + case "memory_slot_get": + case "memory_slot_create": + case "memory_slot_append": + case "memory_slot_replace": + case "memory_slot_delete": + case "memory_facet_tag": + case "memory_facet_query": + case "memory_team_share": + case "memory_team_feed": + case "memory_snapshot_create": + case "memory_reflect": + case "memory_relations": + case "task": + case "task_plan": + case "signal": + case "checkpoint": + case "sketch": + case "crystal": + case "lesson": + case "insight": + case "slot": { + const op = args["operation"]; + if (typeof op !== "string" || !op.trim()) { + v.operation = toolName.replace(/^memory_/, "").replace(/^memory_/, ""); + return v; + } + v.operation = (op as string).trim(); + if (toolName === "slot" && (v.operation === "get" || v.operation === "delete")) { + const lbl = args["label"]; + if (typeof lbl !== "string" || !lbl.trim()) throw new Error("label is required"); + v.label = lbl; + } + if (toolName === "insight" && v.operation === "delete") { + v.insightIds = normalizeList(args["insightIds"]); + if (v.insightIds.length === 0) throw new Error("insightIds is required for delete"); + v.reason = (args["reason"] as string) || "plugin request"; + } return v; } - default: + default: { throw new Error(`Unknown tool: ${toolName}`); + } } } @@ -146,54 +275,46 @@ async function handleProxy( v: Validated, handle: ProxyHandle, ): Promise<{ content: Array<{ type: string; text: string }> }> { + // Map all tools (consolidated + legacy aliases) to REST endpoints or MCP call switch (v.tool) { - case "memory_save": { - const result = await handle.call("/agentmemory/remember", { - method: "POST", - body: JSON.stringify({ - content: v.content, - type: v.type, - concepts: v.concepts, - files: v.files, - }), - }); - return textResponse(result); - } + case "memory_search": case "memory_recall": case "memory_smart_search": { - const result = await handle.call("/agentmemory/smart-search", { + const scope = v.operation || "keyword"; + const endpoints: Record = { + keyword: "/agentmemory/smart-search", + semantic: "/agentmemory/smart-search", + recall: "/agentmemory/search", + smart_search: "/agentmemory/smart-search", + }; + const ep = endpoints[scope] || "/agentmemory/search"; + const result = await handle.call(ep, { method: "POST", body: JSON.stringify({ query: v.query, limit: v.limit }), }); return textResponse(result, true); } - case "memory_sessions": { - const result = await handle.call( - `/agentmemory/sessions?limit=${v.limit}`, - { method: "GET" }, - ); - return textResponse(result, true); - } - case "memory_governance_delete": { - const result = await handle.call("/agentmemory/governance/memories", { - method: "POST", - body: JSON.stringify({ memoryIds: v.memoryIds, reason: v.reason }), - }); - return textResponse(result); + case "memory_store": + case "memory_save": { + if (v.operation === "save") { + const result = await handle.call("/agentmemory/remember", { + method: "POST", + body: JSON.stringify({ content: v.content, type: v.type, concepts: v.concepts, files: v.files }), + }); + return textResponse(result); + } + throw new Error(`Unsupported memory_store operation: ${v.operation}`); } - case "memory_export": { - const result = await handle.call("/agentmemory/export", { method: "GET" }); + case "memory_profile": { + const result = await handle.call("/agentmemory/profile?project=" + encodeURIComponent(v.query || ""), { method: "GET" }); return textResponse(result, true); } - case "memory_audit": { - const result = await handle.call( - `/agentmemory/audit?limit=${v.limit}`, - { method: "GET" }, - ); + case "memory_sessions": { + const result = await handle.call("/agentmemory/sessions?limit=" + (v.limit ?? 20), { method: "GET" }); return textResponse(result, true); } default: - throw new Error(`Unknown tool: ${v.tool}`); + throw new Error(`Proxy not implemented for: ${v.tool}`); } } @@ -202,94 +323,45 @@ async function handleLocal( kvInstance: InMemoryKV, ): Promise<{ content: Array<{ type: string; text: string }> }> { switch (v.tool) { - case "memory_save": { - const id = generateId("mem"); - const isoNow = new Date().toISOString(); - await kvInstance.set("mem:memories", id, { - id, - type: v.type, - title: (v.content || "").slice(0, 80), - content: v.content, - concepts: v.concepts, - files: v.files, - createdAt: isoNow, - updatedAt: isoNow, - strength: 7, - version: 1, - isLatest: true, - sessionIds: [], - }); - kvInstance.persist(); - return textResponse({ saved: id }); - } - + case "memory_search": case "memory_recall": case "memory_smart_search": { const query = (v.query || "").toLowerCase(); const limit = v.limit ?? DEFAULT_LIMIT; - const all = - await kvInstance.list>("mem:memories"); + const all = await kvInstance.list>("mem:memories"); const results = all .filter((m) => { - const text = [ - typeof m["title"] === "string" ? m["title"] : "", - typeof m["content"] === "string" ? m["content"] : "", - Array.isArray(m["files"]) ? m["files"].join(" ") : "", - Array.isArray(m["concepts"]) ? m["concepts"].join(" ") : "", - Array.isArray(m["sessionIds"]) ? m["sessionIds"].join(" ") : "", - typeof m["id"] === "string" ? m["id"] : "", - ] - .join(" ") - .toLowerCase(); + const text = [typeof m["title"] === "string" ? m["title"] : "", typeof m["content"] === "string" ? m["content"] : "", Array.isArray(m["files"]) ? (m["files"] as string[]).join(" ") : "", Array.isArray(m["concepts"]) ? (m["concepts"] as string[]).join(" ") : ""].join(" ").toLowerCase(); return query.split(/\s+/).every((word) => text.includes(word)); }) .slice(0, limit); return textResponse({ mode: "compact", results }, true); } - - case "memory_sessions": { - const sessions = - await kvInstance.list>("mem:sessions"); - const limit = v.limit ?? 20; - return textResponse({ sessions: sessions.slice(0, limit) }, true); - } - - case "memory_governance_delete": { - let deleted = 0; - for (const id of v.memoryIds || []) { - const existing = await kvInstance.get("mem:memories", id); - if (existing) { - await kvInstance.delete("mem:memories", id); - deleted++; - } + case "memory_store": + case "memory_save": { + if (v.operation === "save") { + const id = generateId("mem"); + const isoNow = new Date().toISOString(); + await kvInstance.set("mem:memories", id, { + id, type: v.type, title: ((v.content || "") as string).slice(0, 80), content: v.content, + concepts: v.concepts, files: v.files, createdAt: isoNow, updatedAt: isoNow, + strength: 7, version: 1, isLatest: true, sessionIds: [], + }); + kvInstance.persist(); + return textResponse({ saved: id }); } - kvInstance.persist(); - return textResponse({ - deleted, - requested: (v.memoryIds || []).length, - reason: v.reason, - }); + throw new Error(`Unsupported operation: ${v.operation}`); } - - case "memory_export": { - const memories = await kvInstance.list("mem:memories"); - const sessions = await kvInstance.list("mem:sessions"); - return textResponse({ version: VERSION, memories, sessions }, true); + case "memory_profile": { + throw new Error("memory_profile not implemented in standalone local mode"); } - - case "memory_audit": { - const entries = await kvInstance.list("mem:audit"); - const limit = v.limit ?? 50; - return textResponse( - { - entries: (entries as Array>).slice(0, limit), - }, - true, - ); + case "memory_sessions": { + const sessions = await kvInstance.list>("mem:sessions"); + return textResponse({ sessions: sessions.slice(0, (v.limit ?? 20) as number) }, true); } - - default: + default: { throw new Error(`Unknown tool: ${v.tool}`); + } } } @@ -299,8 +371,8 @@ async function handleProxyGeneric( handle: ProxyHandle, ): Promise<{ content: Array<{ type: string; text: string }> }> { // Forward to the server's full MCP surface so non-Claude clients can - // reach all 51 tools (lessons, sentinels, slots, signals, graph, …) - // instead of being capped at the 7 IMPLEMENTED_TOOLS set baked into + // reach all 13 tools (lessons, sentinels, slots, signals, graph, …) + // instead of being capped at the 13 IMPLEMENTED_TOOLS set baked into // this shim. The server validates arguments per tool. const result = (await handle.call("/agentmemory/mcp/call", { method: "POST", @@ -341,14 +413,27 @@ export async function handleToolCall( } const validated = validate(toolName, args); + const localSet = new Set(["memory_search","memory_recall","memory_smart_search","memory_store","memory_save","memory_profile","memory_sessions"]); if (handle.mode === "proxy") { try { return await handleProxy(validated, handle); } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + if (!localSet.has(toolName) && (msg.startsWith("Proxy not implemented") || msg.startsWith("Unsupported"))) { + try { + return await handleProxyGeneric(toolName, args, handle); + } catch { + invalidateHandle(); + throw err; + } + } process.stderr.write( - `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}; invalidating handle and falling back to local KV\n`, + `[@agentmemory/mcp] proxy call failed for ${toolName}: ${msg}; invalidating handle and falling back to local KV\n`, ); invalidateHandle(); + if (!localSet.has(toolName)) { + throw err; + } } } return handleLocal(validated, kvInstance); @@ -396,7 +481,10 @@ export async function handleToolsList(): Promise<{ tools: unknown[] }> { invalidateHandle(); } } - const fallback = getAllTools().filter((t) => IMPLEMENTED_TOOLS.has(t.name)); + const fallback = getAllTools().filter((t) => { + const localSet = new Set(["memory_search", "memory_store"]); + return localSet.has(t.name); + }); if (debug) { process.stderr.write( `[@agentmemory/mcp] tools/list: returning ${fallback.length} local fallback tools (${fallback.map((t) => t.name).join(",")})\n`, diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts index fee91d6387..3a30feb022 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -10,941 +10,304 @@ export type McpToolDef = { export const CORE_TOOLS: McpToolDef[] = [ { - name: "memory_recall", + name: "memory_search", description: - "Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.", + "Multi-scope search across memories. scope: keyword (BM25), semantic (embeddings), file (file path history), time (chronological), graph (knowledge graph), image (CLIP). operation: backward-compatible alias (recall, smart_search, timeline, file_history, graph_query, image_search). Use scope for new code.", inputSchema: { type: "object", properties: { - query: { - type: "string", - description: "Search query (keywords, file names, concepts)", - }, - limit: { - type: "number", - description: "Max results to return (default 10)", - }, - format: { - type: "string", - description: "Result format: full, compact, or narrative (default full)", - }, - token_budget: { - type: "number", - description: "Optional token budget to trim returned results", - }, - }, - required: ["query"], - }, - }, - { - name: "memory_compress_file", - description: - "Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing.", - inputSchema: { - type: "object", - properties: { - filePath: { - type: "string", - description: "Path to the markdown file to compress", - }, - }, - required: ["filePath"], - }, - }, - { - name: "memory_save", - description: - "Explicitly save an important insight, decision, or pattern to long-term memory.", - inputSchema: { - type: "object", - properties: { - content: { - type: "string", - description: "The insight or decision to remember", - }, - type: { - type: "string", - description: - "Memory type: pattern, preference, architecture, bug, workflow, or fact", - }, - concepts: { + operation: { type: "string", - description: "Comma-separated key concepts", + description: "Alias for scope: recall, smart_search, timeline, file_history, graph_query, image_search", }, - files: { + scope: { type: "string", - description: "Comma-separated relevant file paths", + description: "keyword (default), semantic, file, time, graph, image", }, - }, - required: ["content"], - }, - }, - { - name: "memory_file_history", - description: "Get past observations about specific files.", - inputSchema: { - type: "object", - properties: { - files: { type: "string", description: "Comma-separated file paths" }, - sessionId: { - type: "string", - description: "Current session ID to exclude", - }, - }, - required: ["files"], - }, - }, - { - name: "memory_patterns", - description: "Detect recurring patterns across sessions.", - inputSchema: { - type: "object", - properties: { - project: { type: "string", description: "Project path to analyze" }, - }, - }, - }, - { - name: "memory_sessions", - description: - "List recent sessions with their status and observation counts.", - inputSchema: { type: "object", properties: {} }, - }, - { - name: "memory_smart_search", - description: "Hybrid semantic+keyword search with progressive disclosure.", - inputSchema: { - type: "object", - properties: { query: { type: "string", description: "Search query" }, - expandIds: { - type: "string", - description: "Comma-separated observation IDs to expand", - }, + files: { type: "string", description: "Comma-separated file paths (file scope)" }, + sessionId: { type: "string", description: "Session ID to exclude" }, + anchor: { type: "string", description: "Anchor: ISO date or keyword (time scope)" }, + before: { type: "number", description: "Observations before anchor (default 5)" }, + after: { type: "number", description: "Observations after anchor (default 5)" }, + startNodeId: { type: "string", description: "Starting node ID (graph scope)" }, + nodeType: { type: "string", description: "Filter by node type (graph scope)" }, + maxDepth: { type: "number", description: "Max BFS depth (graph scope, default 3)" }, + memoryId: { type: "string", description: "Memory ID for relations (keyword scope)" }, + maxHops: { type: "number", description: "Max traversal depth (default 2)" }, + minConfidence: { type: "number", description: "Min confidence 0-1" }, + queryText: { type: "string", description: "Text query (image scope)" }, + queryImageRef: { type: "string", description: "Path to stored image (image scope)" }, + queryImageBase64: { type: "string", description: "Base64 image or data URL (image scope)" }, + topK: { type: "number", description: "Max results (default 10, max 50)" }, + expandIds: { type: "string", description: "Comma-separated IDs to expand (semantic scope)" }, + project: { type: "string", description: "Project path (time/graph scope)" }, + format: { type: "string", description: "Result format: full, compact, narrative" }, + token_budget: { type: "number", description: "Token budget to trim results" }, limit: { type: "number", description: "Max results (default 10)" }, }, required: ["query"], }, }, { - name: "memory_vision_search", + name: "memory_store", description: - "Cross-modal image search via CLIP embeddings. Pass queryText to find screenshots matching a description, or queryImageBase64/queryImageRef to find similar images. Requires AGENTMEMORY_IMAGE_EMBEDDINGS=true.", + "Save and manage memories. operation: save (store a new memory), compress_file (compress a markdown file with .original.md backup), export (export all data as JSON), consolidate (run 4-tier pipeline: episodic/semantic/procedural), claude_bridge (sync with Claude Code MEMORY.md), mesh_sync (sync with peer instances).", inputSchema: { type: "object", properties: { - queryText: { type: "string", description: "Text query (e.g. 'login form with error banner')" }, - queryImageRef: { type: "string", description: "Absolute path to a stored image to match against" }, - queryImageBase64: { type: "string", description: "Raw base64 image bytes or data URL" }, - topK: { type: "number", description: "Max results (default 10, max 50)" }, - sessionId: { type: "string", description: "Filter to a single session" }, - }, - }, - }, - { - name: "memory_timeline", - description: "Chronological observations around an anchor point.", - inputSchema: { - type: "object", - properties: { - anchor: { + operation: { type: "string", - description: "Anchor point: ISO date or keyword", - }, - project: { type: "string", description: "Filter by project path" }, - before: { - type: "number", - description: "Observations before anchor (default 5)", + description: "save, compress_file, export, consolidate, claude_bridge, mesh_sync", }, - after: { - type: "number", - description: "Observations after anchor (default 5)", + content: { type: "string", description: "Memory content (save operation)" }, + type: { + type: "string", + description: "Memory type: pattern, preference, architecture, bug, workflow, fact (save operation)", }, + concepts: { type: "string", description: "Comma-separated key concepts (save operation)" }, + files: { type: "string", description: "Comma-separated relevant file paths (save operation)" }, + filePath: { type: "string", description: "Path to markdown file (compress_file operation)" }, + direction: { type: "string", description: "'read' or 'write' (claude_bridge operation)" }, + tier: { type: "string", description: "Target tier: episodic, semantic, or procedural (consolidate operation)" }, + peerId: { type: "string", description: "Specific peer ID (mesh_sync, omit for all)" }, + direction2: { type: "string", description: "push, pull, or both (mesh_sync operation)" }, }, - required: ["anchor"], + required: ["operation"], }, }, { name: "memory_profile", - description: "User/project profile with top concepts and file patterns.", + description: "User/project profile with top concepts, file patterns, and conventions.", inputSchema: { type: "object", properties: { project: { type: "string", description: "Project path" }, - refresh: { - type: "string", - description: "Set to 'true' to force rebuild", - }, + refresh: { type: "string", description: "Set to 'true' to force rebuild" }, }, required: ["project"], }, }, { - name: "memory_export", - description: "Export all memory data as JSON.", - inputSchema: { type: "object", properties: {} }, - }, - { - name: "memory_relations", - description: "Query the memory relationship graph.", - inputSchema: { - type: "object", - properties: { - memoryId: { - type: "string", - description: "Memory ID to find relations for", - }, - maxHops: { - type: "number", - description: "Max traversal depth (default 2)", - }, - minConfidence: { - type: "number", - description: "Min confidence (0-1, default 0)", - }, - }, - required: ["memoryId"], - }, - }, -]; - -export const V040_TOOLS: McpToolDef[] = [ - { - name: "memory_claude_bridge_sync", + name: "task", description: - "Sync memory state to/from Claude Code's native MEMORY.md file.", + "Create and update tasks/actions. operation: create (new task with optional parent/dependency edges), update (change status/priority/details, set status='done' to complete), routine_run (instantiate a frozen workflow routine).", inputSchema: { type: "object", properties: { - direction: { - type: "string", - description: - "'read' to import from MEMORY.md, 'write' to export to MEMORY.md", - }, - }, - required: ["direction"], - }, - }, - { - name: "memory_graph_query", - description: "Query the knowledge graph for entities and relationships.", - inputSchema: { - type: "object", - properties: { - startNodeId: { - type: "string", - description: "Starting node ID for traversal", - }, - nodeType: { type: "string", description: "Filter by node type" }, - maxDepth: { - type: "number", - description: "Max BFS depth (default 3, max 5)", - }, - query: { type: "string", description: "Search nodes by name" }, - }, - }, - }, - { - name: "memory_consolidate", - description: - "Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural).", - inputSchema: { - type: "object", - properties: { - tier: { - type: "string", - description: "Target tier: episodic, semantic, or procedural", - }, - }, - }, - }, - { - name: "memory_team_share", - description: "Share a memory or observation with team members.", - inputSchema: { - type: "object", - properties: { - itemId: { - type: "string", - description: "ID of memory or observation to share", - }, - itemType: { - type: "string", - description: "Type: observation, memory, or pattern", - }, - }, - required: ["itemId", "itemType"], - }, - }, - { - name: "memory_team_feed", - description: "Get recent shared items from all team members.", - inputSchema: { - type: "object", - properties: { - limit: { type: "number", description: "Max items (default 20)" }, - }, - }, - }, - { - name: "memory_audit", - description: "View the audit trail of memory operations.", - inputSchema: { - type: "object", - properties: { - operation: { type: "string", description: "Filter by operation type" }, - limit: { type: "number", description: "Max entries (default 50)" }, - }, - }, - }, - { - name: "memory_governance_delete", - description: "Delete specific memories with audit trail.", - inputSchema: { - type: "object", - properties: { - memoryIds: { - type: "string", - description: "Comma-separated memory IDs to delete", - }, - reason: { type: "string", description: "Reason for deletion" }, - }, - required: ["memoryIds"], - }, - }, - { - name: "memory_snapshot_create", - description: "Create a git-versioned snapshot of current memory state.", - inputSchema: { - type: "object", - properties: { - message: { type: "string", description: "Snapshot description" }, - }, - }, - }, -]; - -export const V050_TOOLS: McpToolDef[] = [ - { - name: "memory_action_create", - description: - "Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.", - inputSchema: { - type: "object", - properties: { - title: { type: "string", description: "Action title" }, - description: { - type: "string", - description: "Detailed description of the work", - }, - priority: { - type: "number", - description: "Priority 1-10 (10 highest)", - }, + operation: { type: "string", description: "create, update, or routine_run" }, + title: { type: "string", description: "Task title" }, + description: { type: "string", description: "Detailed description" }, + priority: { type: "number", description: "Priority 1-10 (10 highest)" }, project: { type: "string", description: "Project path" }, - tags: { - type: "string", - description: "Comma-separated tags", - }, - parentId: { - type: "string", - description: "Parent action ID for hierarchical actions", - }, - requires: { - type: "string", - description: - "Comma-separated action IDs that must complete before this", - }, - }, - required: ["title"], - }, - }, - { - name: "memory_action_update", - description: - "Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.", - inputSchema: { - type: "object", - properties: { - actionId: { type: "string", description: "Action ID to update" }, - status: { - type: "string", - description: "New status: pending, active, done, blocked, cancelled", - }, - result: { - type: "string", - description: "Outcome description (when completing)", - }, - priority: { type: "number", description: "New priority 1-10" }, - }, - required: ["actionId"], - }, - }, - { - name: "memory_frontier", - description: - "Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.", - inputSchema: { - type: "object", - properties: { - project: { type: "string", description: "Filter by project" }, - agentId: { - type: "string", - description: "Agent ID to check lease conflicts", - }, - limit: { type: "number", description: "Max results (default 20)" }, + tags: { type: "string", description: "Comma-separated tags" }, + parentId: { type: "string", description: "Parent task ID for hierarchical tasks" }, + requires: { type: "string", description: "Comma-separated task IDs that must complete before this" }, + actionId: { type: "string", description: "Task ID to update (update operation)" }, + status: { type: "string", description: "New status: pending, active, done, blocked, cancelled" }, + result: { type: "string", description: "Outcome description (when completing)" }, + routineId: { type: "string", description: "Routine template ID (routine_run operation)" }, + initiatedBy: { type: "string", description: "Agent starting the run" }, }, + required: ["operation"], }, }, { - name: "memory_next", + name: "task_plan", description: - "Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.", + "Plan and coordinate task work. operation: next (single most important task by priority+urgency), frontier (all unblocked tasks ranked), lease_acquire (claim a task with TTL), lease_release (finish and unblock dependents), lease_renew (extend TTL).", inputSchema: { type: "object", properties: { + operation: { type: "string", description: "next, frontier, lease_acquire, lease_release, or lease_renew" }, project: { type: "string", description: "Filter by project" }, - agentId: { type: "string", description: "Current agent ID" }, + agentId: { type: "string", description: "Current agent ID for priority scoring" }, + actionId: { type: "string", description: "Task ID (lease operations)" }, + result: { type: "string", description: "Result when releasing (marks task done)" }, + ttlMs: { type: "number", description: "Lease duration in ms (default 10min, max 1hr)" }, + limit: { type: "number", description: "Max results (frontier, default 20)" }, }, + required: ["operation"], }, }, { - name: "memory_lease", - description: - "Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.", - inputSchema: { - type: "object", - properties: { - actionId: { type: "string", description: "Action ID" }, - agentId: { type: "string", description: "Agent claiming the action" }, - operation: { - type: "string", - description: "acquire, release, or renew", - }, - result: { - type: "string", - description: "Result when releasing (marks action done)", - }, - ttlMs: { - type: "number", - description: "Lease duration in ms (default 10min, max 1hr)", - }, - }, - required: ["actionId", "agentId", "operation"], - }, - }, - { - name: "memory_routine_run", - description: - "Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.", - inputSchema: { - type: "object", - properties: { - routineId: { type: "string", description: "Routine template ID" }, - project: { type: "string", description: "Project context" }, - initiatedBy: { type: "string", description: "Agent starting the run" }, - }, - required: ["routineId"], - }, - }, - { - name: "memory_signal_send", + name: "signal", description: - "Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.", + "Send a message to another agent or broadcast, or read messages. operation: send (post a message with optional threading), read (retrieve messages for an agent, marks as read). Supports typed messages: info, request, response, alert, handoff.", inputSchema: { type: "object", properties: { - from: { type: "string", description: "Sender agent ID" }, - to: { - type: "string", - description: "Recipient agent ID (omit for broadcast)", - }, + operation: { type: "string", description: "send or read" }, + from: { type: "string", description: "Sender agent ID (send operation)" }, + to: { type: "string", description: "Recipient agent ID (omit for broadcast)" }, content: { type: "string", description: "Message content" }, - type: { - type: "string", - description: "Message type: info, request, response, alert, handoff", - }, - replyTo: { - type: "string", - description: "Signal ID to reply to (auto-threads)", - }, - }, - required: ["from", "content"], - }, - }, - { - name: "memory_signal_read", - description: - "Read messages for an agent. Marks delivered messages as read.", - inputSchema: { - type: "object", - properties: { - agentId: { type: "string", description: "Agent to read messages for" }, - unreadOnly: { - type: "string", - description: "Set to 'true' for unread only", - }, - threadId: { - type: "string", - description: "Filter by conversation thread", - }, - limit: { type: "number", description: "Max messages (default 50)" }, - }, - required: ["agentId"], - }, - }, - { - name: "memory_checkpoint", - description: - "Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.", - inputSchema: { - type: "object", - properties: { - operation: { - type: "string", - description: "create, resolve, or list", - }, - name: { type: "string", description: "Checkpoint name (for create)" }, - checkpointId: { - type: "string", - description: "Checkpoint ID (for resolve)", - }, - status: { - type: "string", - description: "passed or failed (for resolve)", - }, - type: { - type: "string", - description: "Checkpoint type: ci, approval, deploy, external, timer", - }, - linkedActionIds: { - type: "string", - description: - "Comma-separated action IDs this checkpoint gates (for create)", - }, + type: { type: "string", description: "info, request, response, alert, handoff" }, + replyTo: { type: "string", description: "Signal ID to reply to (auto-threads)" }, + agentId: { type: "string", description: "Agent to read messages for (read operation)" }, + unreadOnly: { type: "string", description: "Set to 'true' for unread only" }, + threadId: { type: "string", description: "Filter by conversation thread" }, + limit: { type: "number", description: "Max messages (read operation, default 50)" }, }, required: ["operation"], }, }, { - name: "memory_mesh_sync", + name: "checkpoint", description: - "Sync memories and actions with peer agentmemory instances for multi-agent collaboration.", + "Manage external checkpoints (CI, approval, deploy status) and event-driven sentinels. operation: create (make a checkpoint gating tasks), resolve (mark passed/failed, unblocks dependents), list (show checkpoints), sentinel_create (event-driven watch), sentinel_trigger (fire a sentinel externally).", inputSchema: { type: "object", properties: { - peerId: { - type: "string", - description: "Specific peer ID (omit for all)", - }, - direction: { - type: "string", - description: "push, pull, or both (default both)", - }, - }, - }, - }, -]; - -export const V051_TOOLS: McpToolDef[] = [ - { - name: "memory_sentinel_create", - description: - "Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.", - inputSchema: { - type: "object", - properties: { - name: { type: "string", description: "Sentinel name" }, - type: { - type: "string", - description: "Type: webhook, timer, threshold, pattern, approval, custom", - }, - config: { - type: "string", - description: "JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})", - }, - linkedActionIds: { - type: "string", - description: "Comma-separated action IDs to gate", - }, + operation: { type: "string", description: "create, resolve, list, sentinel_create, or sentinel_trigger" }, + name: { type: "string", description: "Checkpoint/sentinel name (create)" }, + checkpointId: { type: "string", description: "Checkpoint ID (resolve)" }, + status: { type: "string", description: "passed or failed (resolve)" }, + type: { type: "string", description: "ci, approval, deploy, external, timer, webhook, threshold, pattern, custom" }, + linkedActionIds: { type: "string", description: "Comma-separated task IDs this gates" }, + sentinelId: { type: "string", description: "Sentinel ID (sentinel_trigger)" }, + result: { type: "string", description: "JSON result payload (sentinel_trigger)" }, + config: { type: "string", description: "JSON config (sentinel_create): timer:{durationMs}, threshold:{metric,operator,value}, pattern:{pattern}, webhook:{path}" }, expiresInMs: { type: "number", description: "Auto-expire after ms" }, }, - required: ["name", "type"], - }, - }, - { - name: "memory_sentinel_trigger", - description: - "Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.", - inputSchema: { - type: "object", - properties: { - sentinelId: { type: "string", description: "Sentinel ID to trigger" }, - result: { type: "string", description: "JSON result payload" }, - }, - required: ["sentinelId"], + required: ["operation"], }, }, { - name: "memory_sketch_create", + name: "sketch", description: - "Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.", + "Manage ephemeral action graphs for exploratory work. operation: create (make a new sketch that auto-expires), promote (commit ephemeral actions as permanent). Sketches let you explore before committing.", inputSchema: { type: "object", properties: { + operation: { type: "string", description: "create or promote" }, title: { type: "string", description: "Sketch title" }, description: { type: "string", description: "What this sketch explores" }, expiresInMs: { type: "number", description: "TTL in ms (default 1 hour)" }, project: { type: "string", description: "Project context" }, - }, - required: ["title"], - }, - }, - { - name: "memory_sketch_promote", - description: - "Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.", - inputSchema: { - type: "object", - properties: { sketchId: { type: "string", description: "Sketch ID to promote" }, - project: { type: "string", description: "Override project for promoted actions" }, - }, - required: ["sketchId"], - }, - }, - { - name: "memory_crystallize", - description: - "Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.", - inputSchema: { - type: "object", - properties: { - actionIds: { - type: "string", - description: "Comma-separated completed action IDs to crystallize", - }, - project: { type: "string", description: "Project context" }, - sessionId: { type: "string", description: "Session context" }, - }, - required: ["actionIds"], - }, - }, - { - name: "memory_diagnose", - description: - "Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.", - inputSchema: { - type: "object", - properties: { - categories: { - type: "string", - description: "Comma-separated categories to check (default all)", - }, - }, - }, - }, - { - name: "memory_heal", - description: - "Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.", - inputSchema: { - type: "object", - properties: { - categories: { - type: "string", - description: "Comma-separated categories to heal (default all)", - }, - dryRun: { - type: "string", - description: "Set to 'true' for dry run (report but don't fix)", - }, - }, - }, - }, - { - name: "memory_facet_tag", - description: - "Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.", - inputSchema: { - type: "object", - properties: { - targetId: { type: "string", description: "ID of the target to tag" }, - targetType: { - type: "string", - description: "Type: action, memory, or observation", - }, - dimension: { type: "string", description: "Tag dimension (e.g., priority, team, status)" }, - value: { type: "string", description: "Tag value (e.g., urgent, backend, reviewed)" }, - }, - required: ["targetId", "targetType", "dimension", "value"], - }, - }, - { - name: "memory_facet_query", - description: - "Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.", - inputSchema: { - type: "object", - properties: { - matchAll: { - type: "string", - description: "Comma-separated dimension:value pairs (AND logic)", - }, - matchAny: { - type: "string", - description: "Comma-separated dimension:value pairs (OR logic)", - }, - targetType: { - type: "string", - description: "Filter by type: action, memory, or observation", - }, }, + required: ["operation", "title"], }, }, ]; -export const V061_TOOLS: McpToolDef[] = [ +export const V040_TOOLS: McpToolDef[] = [ { - name: "memory_verify", + name: "crystal", description: - "Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.", + "Crystallize completed task chains into compact narrative digests via LLM summarization, or list existing crystals. operation: list (show existing crystals), crystallize (compress task chains into narrative with key outcomes, files, and lessons).", inputSchema: { type: "object", properties: { - id: { - type: "string", - description: "Memory ID or observation ID to verify", - }, + operation: { type: "string", description: "list or crystallize" }, + actionIds: { type: "string", description: "Comma-separated completed task IDs to crystallize" }, + project: { type: "string", description: "Project context" }, + sessionId: { type: "string", description: "Session context" }, + limit: { type: "number", description: "Max results (list operation, default 50)" }, }, - required: ["id"], }, }, -]; - -export const V070_TOOLS: McpToolDef[] = [ { - name: "memory_lesson_save", + name: "lesson", description: - "Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson.", + "Manage learned lessons with confidence scores. Scores strengthen when reinforced, decay when unused. Duplicate content auto-strengthens existing lesson. operation: save, recall (search), list (browse), strengthen (boost confidence).", inputSchema: { type: "object", properties: { - content: { - type: "string", - description: "The lesson learned (what worked, what to avoid, when to use X approach)", - }, - context: { - type: "string", - description: "When/where this lesson applies", - }, - confidence: { - type: "number", - description: "Initial confidence 0.0-1.0 (default 0.5)", - }, + operation: { type: "string", description: "save, recall, list, or strengthen" }, + content: { type: "string", description: "The lesson learned (save operation)" }, + context: { type: "string", description: "When/where this lesson applies (save operation)" }, + confidence: { type: "number", description: "Initial confidence 0.0-1.0 (save, default 0.5)" }, project: { type: "string", description: "Project this lesson is about" }, - tags: { type: "string", description: "Comma-separated tags" }, - }, - required: ["content"], - }, - }, - { - name: "memory_lesson_recall", - description: - "Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.", - inputSchema: { - type: "object", - properties: { - query: { type: "string", description: "Search query" }, - project: { type: "string", description: "Filter by project" }, - minConfidence: { - type: "number", - description: "Minimum confidence threshold (default 0.1)", - }, + tags: { type: "string", description: "Comma-separated tags (save operation)" }, + query: { type: "string", description: "Search query (recall operation)" }, + minConfidence: { type: "number", description: "Minimum confidence (recall/list operations)" }, limit: { type: "number", description: "Max results (default 10)" }, + source: { type: "string", description: "Filter by source: 'manual', 'crystal', 'consolidation' (list operation)" }, + lessonId: { type: "string", description: "Lesson ID (strengthen operation)" }, }, - required: ["query"], - }, - }, - { - name: "memory_lesson_list", - description: - "List all lessons, optionally filtered by project, source, or minimum confidence. Use to browse or review stored lessons.", - inputSchema: { - type: "object", - properties: { - project: { type: "string", description: "Filter by project" }, - source: { - type: "string", - description: "Filter by source: 'manual', 'crystal', or 'consolidation'", - }, - minConfidence: { - type: "number", - description: "Minimum confidence threshold (default 0)", - }, - limit: { type: "number", description: "Max results (default 50)" }, - }, - }, - }, - { - name: "memory_lesson_strengthen", - description: - "Boost the confidence of an existing lesson by its ID. Use when a lesson is particularly relevant or verified.", - inputSchema: { - type: "object", - properties: { - lessonId: { type: "string", description: "The ID of the lesson to strengthen" }, - }, - required: ["lessonId"], - }, - }, - { - name: "memory_obsidian_export", - description: - "Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.", - inputSchema: { - type: "object", - properties: { - vaultDir: { - type: "string", - description: "Output directory (default ~/.agentmemory/vault/)", - }, - types: { - type: "string", - description: "Comma-separated types to export: memories,lessons,crystals,sessions (default all)", - }, - }, - }, - }, -]; - -export const V073_TOOLS: McpToolDef[] = [ - { - name: "memory_reflect", - description: - "Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.", - inputSchema: { - type: "object", - properties: { - project: { type: "string", description: "Filter by project" }, - maxClusters: { - type: "number", - description: "Max concept clusters to process (default 10, max 20)", - }, - }, + required: ["operation"], }, }, { - name: "memory_insight_list", + name: "insight", description: - "List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.", + "Manage synthesized insights derived from memory patterns via LLM traversal and concept clustering. operation: list (show insights sorted by confidence), delete (soft-delete with audit trail). Insights are higher-order observations.", inputSchema: { type: "object", properties: { + operation: { type: "string", description: "list or delete" }, project: { type: "string", description: "Filter by project" }, - minConfidence: { - type: "number", - description: "Minimum confidence threshold (default 0)", - }, + minConfidence: { type: "number", description: "Minimum confidence threshold (default 0)" }, limit: { type: "number", description: "Max results (default 50)" }, + insightIds: { type: "string", description: "Comma-separated insight IDs to delete" }, + reason: { type: "string", description: "Reason for deletion" }, }, + required: ["operation"], }, }, -]; - -export const V010_SLOTS_TOOLS: McpToolDef[] = [ { - name: "memory_slot_list", + name: "slot", description: - "List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions.", - inputSchema: { type: "object", properties: {} }, - }, - { - name: "memory_slot_get", - description: "Read a single slot by label.", - inputSchema: { - type: "object", - properties: { - label: { type: "string", description: "Slot label (e.g. 'persona', 'pending_items')" }, - }, - required: ["label"], - }, - }, - { - name: "memory_slot_create", - description: "Create a new slot. Reject if a slot with the same label already exists.", + "Manage memory slots — editable, size-limited memory units readable/writable across sessions. operation: list (show all slots), get (read one by label), create (make new, reject on duplicate), append (add text, fails 413 if over limit), replace (replace content), delete (remove slot). Pinned slots auto-inject into context.", inputSchema: { type: "object", properties: { + operation: { type: "string", description: "list, get, create, append, replace, or delete" }, label: { type: "string", description: "Slot label — lowercase, starts with letter, [a-z0-9_]" }, - content: { type: "string", description: "Initial content (default empty)" }, - sizeLimit: { type: "number", description: "Max chars (default 2000, hard cap 20000)" }, - description: { type: "string", description: "What this slot is for" }, - pinned: { type: "string", description: "'false' to exclude from context injection; default true" }, - scope: { type: "string", description: "'project' (default) or 'global' (shared across projects)" }, + content: { type: "string", description: "Initial or new content (create/replace operation)" }, + text: { type: "string", description: "Text to append (append operation)" }, + sizeLimit: { type: "number", description: "Max chars (create operation, default 2000, hard cap 20000)" }, + description: { type: "string", description: "What this slot is for (create operation)" }, + pinned: { type: "string", description: "'false' to exclude from context injection (create, default true)" }, + scope: { type: "string", description: "'project' (default) or 'global' (create operation)" }, }, - required: ["label"], + required: ["operation"], }, }, { - name: "memory_slot_append", + name: "admin", description: - "Append text to an existing slot. Fails with 413 if the append would exceed the slot's sizeLimit — agent must compact via memory_slot_replace first.", - inputSchema: { - type: "object", - properties: { - label: { type: "string", description: "Slot label" }, - text: { type: "string", description: "Text to append" }, - }, - required: ["label", "text"], - }, - }, - { - name: "memory_slot_replace", - description: "Replace slot content in place. Fails if content exceeds sizeLimit.", - inputSchema: { - type: "object", - properties: { - label: { type: "string", description: "Slot label" }, - content: { type: "string", description: "New full content" }, - }, - required: ["label", "content"], - }, - }, - { - name: "memory_slot_delete", - description: "Delete a slot. Seeded default slots can be deleted unless marked readOnly.", + "Admin and governance operations. operation: diagnose (health checks across all subsystems), heal (auto-fix issues, dryRun supported), audit (view audit trail), delete (soft-delete memories or insights, use entityType to route), consolidate (run pipeline), mesh (sync with peers), obsidian (export to Obsidian vault with YAML frontmatter), verify (trace citation chain back to source observations).", inputSchema: { type: "object", properties: { - label: { type: "string", description: "Slot label" }, + operation: { type: "string", description: "diagnose, heal, audit, delete, consolidate, mesh, obsidian, or verify" }, + categories: { type: "string", description: "Comma-separated categories (diagnose/heal operations)" }, + dryRun: { type: "string", description: "Set to 'true' for dry run (heal operation)" }, + operation_filter: { type: "string", description: "Filter by operation type (audit operation)" }, + limit: { type: "number", description: "Max entries (audit operation, default 50)" }, + entityType: { type: "string", description: "'memory' or 'insight' (delete operation only)" }, + memoryIds: { type: "string", description: "Comma-separated memory IDs to delete" }, + insightIds: { type: "string", description: "Comma-separated insight IDs to delete" }, + reason: { type: "string", description: "Reason for deletion (delete operation)" }, + tier: { type: "string", description: "Target tier (consolidate operation)" }, + peerId: { type: "string", description: "Specific peer ID (mesh operation, omit for all)" }, + direction: { type: "string", description: "push, pull, or both (mesh operation)" }, + vaultDir: { type: "string", description: "Output directory (obsidian operation, default ~/.agentmemory/vault/)" }, + types: { type: "string", description: "Comma-separated types: memories,lessons,crystals,sessions (obsidian operation)" }, + id: { type: "string", description: "Memory/insight ID to verify (verify operation)" }, }, - required: ["label"], + required: ["operation"], }, }, ]; const ESSENTIAL_TOOLS = new Set([ - "memory_save", - "memory_recall", - "memory_consolidate", - "memory_smart_search", - "memory_sessions", - "memory_diagnose", - "memory_lesson_save", - "memory_reflect", + "memory_search", + "memory_store", + "memory_profile", + "task", + "task_plan", + "signal", + "lesson", + "insight", ]); export function getAllTools(): McpToolDef[] { return [ ...CORE_TOOLS, ...V040_TOOLS, - ...V050_TOOLS, - ...V051_TOOLS, - ...V061_TOOLS, - ...V070_TOOLS, - ...V073_TOOLS, - ...V010_SLOTS_TOOLS, ]; } @@ -952,4 +315,4 @@ export function getVisibleTools(): McpToolDef[] { const mode = process.env["AGENTMEMORY_TOOLS"] || "core"; if (mode === "all") return getAllTools(); return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name)); -} +} \ No newline at end of file diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts index 6522691d2a..17a21631c4 100644 --- a/test/mcp-standalone-proxy.test.ts +++ b/test/mcp-standalone-proxy.test.ts @@ -256,20 +256,15 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => { const before = await handleToolsList(); const beforeTools = before.tools as Array<{ name: string }>; expect(beforeTools.map((t) => t.name).sort()).toEqual([ - "memory_audit", - "memory_export", - "memory_governance_delete", - "memory_recall", - "memory_save", - "memory_sessions", - "memory_smart_search", + "memory_search", + "memory_store", ]); - expect(beforeTools).toHaveLength(7); + expect(beforeTools).toHaveLength(2); resetHandleForTests(); process.env["AGENTMEMORY_TOOLS"] = "core"; const core = await handleToolsList(); - expect((core.tools as unknown[]).length).toBe(7); + expect((core.tools as unknown[]).length).toBe(2); delete process.env["AGENTMEMORY_TOOLS"]; }); diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts index 59bd985eef..69ef7b132c 100644 --- a/test/mcp-standalone.test.ts +++ b/test/mcp-standalone.test.ts @@ -19,6 +19,11 @@ vi.mock("../src/config.js", () => ({ getStandalonePersistPath: vi.fn(() => "/tmp/test-standalone.json"), })); +vi.mock("../src/mcp/rest-proxy.js", () => ({ + resolveHandle: vi.fn(() => Promise.resolve({ mode: "local", baseUrl: "" })), + invalidateHandle: vi.fn(), +})); + import { getAllTools, CORE_TOOLS, @@ -31,27 +36,34 @@ import { writeFileSync } from "node:fs"; describe("Tools Registry", () => { it("getAllTools returns all tools with unique names", () => { const tools = getAllTools(); - expect(tools.length).toBeGreaterThanOrEqual(41); + expect(tools.length).toBeGreaterThanOrEqual(13); const names = new Set(tools.map((t) => t.name)); expect(names.size).toBe(tools.length); for (const required of [ - "memory_verify", - "memory_lesson_save", - "memory_lesson_recall", - "memory_obsidian_export", - "memory_save", - "memory_recall", + "memory_search", + "memory_store", + "memory_profile", + "task", + "task_plan", + "signal", + "checkpoint", + "sketch", + "crystal", + "lesson", + "insight", + "slot", + "admin", ]) { expect(tools.some((t) => t.name === required)).toBe(true); } }); - it("CORE_TOOLS has 12 items", () => { - expect(CORE_TOOLS.length).toBe(12); + it("CORE_TOOLS has 8 items", () => { + expect(CORE_TOOLS.length).toBe(8); }); - it("V040_TOOLS has 8 items", () => { - expect(V040_TOOLS.length).toBe(8); + it("V040_TOOLS has 5 items", () => { + expect(V040_TOOLS.length).toBe(5); }); it("all tools have required name, description, inputSchema fields", () => { @@ -67,6 +79,19 @@ describe("Tools Registry", () => { expect(tool.inputSchema.properties).toBeDefined(); } }); + + it("all consolidated tools have 'operation' param", () => { + const consolidatedTools = [ + "memory_search", "memory_store", "task", "task_plan", "signal", + "checkpoint", "sketch", "crystal", "lesson", "insight", "slot", "admin", + ]; + const tools = getAllTools(); + for (const name of consolidatedTools) { + const tool = tools.find((t) => t.name === name); + expect(tool).toBeDefined(); + expect(tool!.inputSchema.properties.operation).toBeDefined(); + } + }); }); describe("InMemoryKV", () => { @@ -124,11 +149,11 @@ describe("handleToolCall", () => { vi.mocked(writeFileSync).mockClear(); }); - it("memory_save persists to disk immediately after saving", async () => { + it("memory_store save persists to disk immediately after saving", async () => { const kv = new InMemoryKV("/tmp/test-handle.json"); const result = await handleToolCall( - "memory_save", - { content: "Test memory content" }, + "memory_store", + { operation: "save", content: "Test memory content" }, kv, ); const parsed = JSON.parse(result.content[0].text); @@ -140,35 +165,34 @@ describe("handleToolCall", () => { ); }); - it("memory_save without persist path does not call writeFileSync", async () => { + it("memory_store save without persist path does not call writeFileSync", async () => { const kv = new InMemoryKV(); - await handleToolCall("memory_save", { content: "No persist path" }, kv); + await handleToolCall("memory_store", { operation: "save", content: "No persist path" }, kv); expect(writeFileSync).not.toHaveBeenCalled(); }); - it("memory_save throws when content is missing", async () => { + it("memory_store save throws when content is missing", async () => { const kv = new InMemoryKV(); await expect( - handleToolCall("memory_save", {}, kv), + handleToolCall("memory_store", { operation: "save" }, kv), ).rejects.toThrow("content is required"); }); - it("memory_save rejects non-string content safely (no runtime TypeError)", async () => { + it("memory_store save rejects non-string content safely (no runtime TypeError)", async () => { const kv = new InMemoryKV(); - // These would have crashed on .trim() before the type-guard fix. for (const bogus of [42, {}, [], null, undefined, true]) { await expect( - handleToolCall("memory_save", { content: bogus }, kv), + handleToolCall("memory_store", { operation: "save", content: bogus }, kv), ).rejects.toThrow("content is required"); } }); - it("memory_recall returns matching memories", async () => { + it("memory_search returns matching memories", async () => { const kv = new InMemoryKV(); - await handleToolCall("memory_save", { content: "TypeScript is great" }, kv); - await handleToolCall("memory_save", { content: "Python is also great" }, kv); + await handleToolCall("memory_store", { operation: "save", content: "TypeScript is great" }, kv); + await handleToolCall("memory_store", { operation: "save", content: "Python is also great" }, kv); const result = await handleToolCall( - "memory_recall", + "memory_search", { query: "typescript" }, kv, ); @@ -177,11 +201,12 @@ describe("handleToolCall", () => { expect(parsed.results[0].content).toBe("TypeScript is great"); }); - it("memory_save accepts concepts/files as arrays (plugin skill format, #139)", async () => { + it("memory_store save accepts concepts/files as arrays (plugin skill format, #139)", async () => { const kv = new InMemoryKV(); const result = await handleToolCall( - "memory_save", + "memory_store", { + operation: "save", content: "Use HMAC for API auth", concepts: ["hmac", "api-auth", "security"], files: ["src/auth.ts", "src/middleware.ts"], @@ -197,11 +222,12 @@ describe("handleToolCall", () => { expect(mem?.files).toEqual(["src/auth.ts", "src/middleware.ts"]); }); - it("memory_save still accepts concepts/files as comma-separated strings (legacy)", async () => { + it("memory_store save still accepts concepts/files as comma-separated strings (legacy)", async () => { const kv = new InMemoryKV(); const result = await handleToolCall( - "memory_save", + "memory_store", { + operation: "save", content: "JWT refresh rotation", concepts: "jwt, refresh, rotation", files: "src/auth.ts", @@ -217,20 +243,20 @@ describe("handleToolCall", () => { expect(mem?.files).toEqual(["src/auth.ts"]); }); - it("memory_smart_search falls back to substring match in the standalone shim (#139)", async () => { + it("memory_search falls back to substring match in the standalone shim (#139)", async () => { const kv = new InMemoryKV(); await handleToolCall( - "memory_save", - { content: "Use bcrypt for password hashing" }, + "memory_store", + { operation: "save", content: "Use bcrypt for password hashing" }, kv, ); await handleToolCall( - "memory_save", - { content: "Use argon2id for new projects" }, + "memory_store", + { operation: "save", content: "Use argon2id for new projects" }, kv, ); const result = await handleToolCall( - "memory_smart_search", + "memory_search", { query: "bcrypt", limit: 5 }, kv, ); @@ -239,38 +265,38 @@ describe("handleToolCall", () => { expect(parsed.results[0].content).toBe("Use bcrypt for password hashing"); }); - it("memory_smart_search rejects empty query to prevent match-all in forget flow (#139)", async () => { + it("memory_search rejects empty query to prevent match-all in forget flow (#139)", async () => { const kv = new InMemoryKV(); - await handleToolCall("memory_save", { content: "anything" }, kv); + await handleToolCall("memory_store", { operation: "save", content: "anything" }, kv); await expect( - handleToolCall("memory_smart_search", {}, kv), + handleToolCall("memory_search", {}, kv), ).rejects.toThrow("query is required"); await expect( - handleToolCall("memory_smart_search", { query: "" }, kv), + handleToolCall("memory_search", { query: "" }, kv), ).rejects.toThrow("query is required"); await expect( - handleToolCall("memory_smart_search", { query: " " }, kv), + handleToolCall("memory_search", { query: " " }, kv), ).rejects.toThrow("query is required"); }); - it("memory_smart_search searches files and concepts, not just title/content (#139)", async () => { + it("memory_search searches files and concepts, not just title/content (#139)", async () => { const kv = new InMemoryKV(); await handleToolCall( - "memory_save", + "memory_store", { + operation: "save", content: "generic note", concepts: ["oauth", "token-rotation"], files: ["src/auth/refresh.ts"], }, kv, ); - await handleToolCall("memory_save", { content: "unrelated" }, kv); + await handleToolCall("memory_store", { operation: "save", content: "unrelated" }, kv); - // Find by file path const byFile = JSON.parse( ( await handleToolCall( - "memory_smart_search", + "memory_search", { query: "src/auth/refresh.ts" }, kv, ) @@ -279,11 +305,10 @@ describe("handleToolCall", () => { expect(byFile.results).toHaveLength(1); expect(byFile.results[0].files).toContain("src/auth/refresh.ts"); - // Find by concept const byConcept = JSON.parse( ( await handleToolCall( - "memory_smart_search", + "memory_search", { query: "token-rotation" }, kv, ) @@ -312,96 +337,37 @@ describe("handleToolCall", () => { it("parseLimit clamps bad/malicious limit values to a safe range", async () => { const kv = new InMemoryKV(); for (let i = 0; i < 150; i++) { - await handleToolCall("memory_save", { content: `mem ${i}` }, kv); + await handleToolCall("memory_store", { operation: "save", content: `mem ${i}` }, kv); } - // Negative / NaN / Infinity / string / object — all should fall back - // to the default (10) for memory_smart_search. for (const bogus of [-1, NaN, Infinity, "abc", {}, true]) { const r = await handleToolCall( - "memory_smart_search", + "memory_search", { query: "mem", limit: bogus }, kv, ); expect(JSON.parse(r.content[0].text).results).toHaveLength(10); } - // An absurdly large limit gets clamped to MAX_LIMIT (100). const huge = await handleToolCall( - "memory_smart_search", + "memory_search", { query: "mem", limit: 99999 }, kv, ); expect(JSON.parse(huge.content[0].text).results).toHaveLength(100); }); - it("memory_governance_delete removes memories by id array (#139)", async () => { - const kv = new InMemoryKV(); - const a = JSON.parse( - (await handleToolCall("memory_save", { content: "one" }, kv)).content[0] - .text, - ); - const b = JSON.parse( - (await handleToolCall("memory_save", { content: "two" }, kv)).content[0] - .text, - ); - const c = JSON.parse( - (await handleToolCall("memory_save", { content: "three" }, kv)).content[0] - .text, - ); - const result = await handleToolCall( - "memory_governance_delete", - { memoryIds: [a.saved, c.saved] }, - kv, - ); - const parsed = JSON.parse(result.content[0].text); - expect(parsed.deleted).toBe(2); - expect(parsed.requested).toBe(2); - - const remaining = await kv.list>("mem:memories"); - expect(remaining).toHaveLength(1); - expect((remaining[0] as { id: string }).id).toBe(b.saved); - }); - - it("memory_governance_delete accepts CSV-string memoryIds too", async () => { - const kv = new InMemoryKV(); - const saved = JSON.parse( - (await handleToolCall("memory_save", { content: "x" }, kv)).content[0] - .text, - ); - const result = await handleToolCall( - "memory_governance_delete", - { memoryIds: saved.saved, reason: "test csv" }, - kv, - ); - const parsed = JSON.parse(result.content[0].text); - expect(parsed.deleted).toBe(1); - expect(parsed.reason).toBe("test csv"); - }); - - it("memory_governance_delete throws when memoryIds is missing or empty", async () => { + it("slot get requires label", async () => { const kv = new InMemoryKV(); await expect( - handleToolCall("memory_governance_delete", {}, kv), - ).rejects.toThrow("memoryIds is required"); - await expect( - handleToolCall("memory_governance_delete", { memoryIds: [] }, kv), - ).rejects.toThrow("memoryIds is required"); + handleToolCall("slot", { operation: "get" }, kv), + ).rejects.toThrow("label is required"); }); - it("memory_governance_delete silently skips unknown ids", async () => { + it("insight delete requires insightIds", async () => { const kv = new InMemoryKV(); - const saved = JSON.parse( - (await handleToolCall("memory_save", { content: "real" }, kv)).content[0] - .text, - ); - const result = await handleToolCall( - "memory_governance_delete", - { memoryIds: [saved.saved, "mem_does_not_exist"] }, - kv, - ); - const parsed = JSON.parse(result.content[0].text); - expect(parsed.deleted).toBe(1); - expect(parsed.requested).toBe(2); + await expect( + handleToolCall("insight", { operation: "delete" }, kv), + ).rejects.toThrow("insightIds is required for delete"); }); -}); +}); \ No newline at end of file From af4f76d37fc871d7f91e2a6b2aa501fe40a67c97 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 16:48:58 -0400 Subject: [PATCH 18/24] fix(governance): soft-delete memories and insights --- src/functions/governance.ts | 41 +++++++++++++++++++--- src/functions/reflect.ts | 29 ++++++++++++++++ src/functions/search.ts | 2 ++ src/types.ts | 2 ++ test/governance.test.ts | 69 +++++++++++++++++++++++++++++++++---- 5 files changed, 132 insertions(+), 11 deletions(-) diff --git a/src/functions/governance.ts b/src/functions/governance.ts index 60813dd4cb..5f6ec555c2 100644 --- a/src/functions/governance.ts +++ b/src/functions/governance.ts @@ -1,13 +1,38 @@ import type { ISdk } from "iii-sdk"; -import type { Memory, GovernanceFilter, AuditEntry } from "../types.js"; +import type { Memory, GovernanceFilter, AuditEntry, GraphNode, GraphEdge } from "../types.js"; import { KV } from "../state/schema.js"; import type { StateKV } from "../state/kv.js"; import { recordAudit, safeAudit, queryAudit } from "./audit.js"; import { deleteAccessLog } from "./access-tracker.js"; import { logger } from "../logger.js"; +async function cascadeStale(kv: StateKV, memoryId: string): Promise { + const now = new Date().toISOString(); + const nodes = await kv.list(KV.graphNodes); + const edges = await kv.list(KV.graphEdges); + + const nodeUpdates: Promise[] = []; + for (const node of nodes) { + if (!node.stale && node.sourceObservationIds.includes(memoryId)) { + node.stale = true; + node.updatedAt = now; + nodeUpdates.push(kv.set(KV.graphNodes, node.id, node)); + } + } + + const edgeUpdates: Promise[] = []; + for (const edge of edges) { + if (!edge.stale && edge.sourceObservationIds.includes(memoryId)) { + edge.stale = true; + edgeUpdates.push(kv.set(KV.graphEdges, edge.id, edge)); + } + } + + await Promise.all([...nodeUpdates, ...edgeUpdates]); +} + export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { - sdk.registerFunction("mem::governance-delete", + sdk.registerFunction("mem::governance-delete", async (data: { memoryIds: string[]; reason?: string }) => { if ( !data.memoryIds || @@ -20,9 +45,12 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { let deleted = 0; for (const id of data.memoryIds) { const mem = await kv.get(KV.memories, id); - if (mem) { - await kv.delete(KV.memories, id); + if (mem && !mem.deleted) { + mem.deleted = true; + mem.updatedAt = new Date().toISOString(); + await kv.set(KV.memories, id, mem); await deleteAccessLog(kv, id); + await cascadeStale(kv, id); deleted++; } } @@ -105,8 +133,11 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { const batch = candidates.slice(i, i + BATCH_SIZE); const results = await Promise.allSettled( batch.map(async (mem) => { - await kv.delete(KV.memories, mem.id); + mem.deleted = true; + mem.updatedAt = new Date().toISOString(); + await kv.set(KV.memories, mem.id, mem); await deleteAccessLog(kv, mem.id); + await cascadeStale(kv, mem.id); }), ); results.forEach((result, j) => { diff --git a/src/functions/reflect.ts b/src/functions/reflect.ts index 3a2af82934..05d4478355 100644 --- a/src/functions/reflect.ts +++ b/src/functions/reflect.ts @@ -474,4 +474,33 @@ export function registerReflectFunctions( return { success: true, decayed, softDeleted, total: items.length }; }, ); + + sdk.registerFunction("mem::insight-delete", + async (data: { + insightId?: string; + insightIds?: string[]; + reason?: string; + }) => { + const ids = data.insightId ? [data.insightId] : (data.insightIds ?? []); + if (!ids.length) { + return { success: false, error: "insightId or insightIds is required" }; + } + let deleted = 0; + const now = new Date().toISOString(); + for (const id of ids) { + const insight = await kv.get(KV.insights, id); + if (insight) { + insight.deleted = true; + insight.updatedAt = now; + await kv.set(KV.insights, id, insight); + deleted++; + } + } + await recordAudit(kv, "delete", "mem::insight-delete", ids, { + reason: data.reason || "manual deletion", + deleted, + }); + return { success: true, deleted, total: ids.length }; + }, + ); } diff --git a/src/functions/search.ts b/src/functions/search.ts index edfa522b4c..b6bb76fe8f 100644 --- a/src/functions/search.ts +++ b/src/functions/search.ts @@ -29,6 +29,7 @@ export async function rebuildIndex(kv: StateKV): Promise { for (const memory of memories) { if (memory.isLatest === false) continue if (!memory.title || !memory.content) continue + if (memory.deleted) continue idx.add(memoryToObservation(memory)) count++ } @@ -157,6 +158,7 @@ export function registerSearchFunction(sdk: ISdk, kv: StateKV): void { const mem = await kv .get(KV.memories, r.obsId) .catch(() => null) + if (mem?.deleted) return null return mem ? memoryToObservation(mem) : null }) ) diff --git a/src/types.ts b/src/types.ts index dd8620bb89..809305f715 100644 --- a/src/types.ts +++ b/src/types.ts @@ -84,6 +84,7 @@ export interface Memory { forgetAfter?: string; imageRef?: string; imageData?: string; + deleted?: boolean; } export interface SessionSummary { @@ -489,6 +490,7 @@ export interface AuditEntry { | "export" | "action_create" | "action_update" + | "action_suggest" | "lease_acquire" | "lease_release" | "routine_run" diff --git a/test/governance.test.ts b/test/governance.test.ts index 2255416493..458bab6d21 100644 --- a/test/governance.test.ts +++ b/test/governance.test.ts @@ -77,7 +77,7 @@ describe("Governance Functions", () => { await kv.set("mem:memories", "mem_3", makeMemory("mem_3", "pattern")); }); - it("governance-delete removes specified memories", async () => { + it("governance-delete soft-deletes specified memories", async () => { const result = (await sdk.trigger("mem::governance-delete", { memoryIds: ["mem_1"], reason: "outdated", @@ -88,7 +88,12 @@ describe("Governance Functions", () => { expect(result.total).toBe(1); const remaining = await kv.list("mem:memories"); - expect(remaining.length).toBe(2); + expect(remaining.length).toBe(3); + const deleted = remaining.find((m: any) => m.id === "mem_1"); + expect(deleted).toBeDefined(); + expect((deleted as any).deleted).toBe(true); + const surviving = remaining.filter((m: any) => m.id !== "mem_1"); + expect(surviving.length).toBe(2); }); it("governance-delete handles non-existent IDs gracefully", async () => { @@ -104,17 +109,25 @@ describe("Governance Functions", () => { expect(remaining.length).toBe(3); }); - it("governance-bulk deletes by type filter", async () => { +it("governance-bulk soft-deletes by type filter", async () => { const result = (await sdk.trigger("mem::governance-bulk", { type: ["pattern"], - })) as { success: boolean; deleted: number }; + })) as { success: boolean; deleted: number; failed: number }; expect(result.success).toBe(true); expect(result.deleted).toBe(2); + expect(result.failed).toBe(0); const remaining = await kv.list("mem:memories"); - expect(remaining.length).toBe(1); - expect(remaining[0].type).toBe("bug"); + expect(remaining.length).toBe(3); + const activeMemories = remaining.filter((m: Memory) => !m.deleted); + expect(activeMemories.length).toBe(1); + expect(activeMemories[0].type).toBe("bug"); + const deletedMemories = remaining.filter((m: Memory) => m.deleted); + expect(deletedMemories.length).toBe(2); + for (const m of deletedMemories) { + expect(m.type).toBe("pattern"); + } }); it("governance-bulk respects dryRun", async () => { @@ -145,4 +158,48 @@ describe("Governance Functions", () => { expect(entries[0].operation).toBe("delete"); expect(entries[0].functionId).toBe("mem::governance-delete"); }); + + it("governance-delete is idempotent", async () => { + const r1 = (await sdk.trigger("mem::governance-delete", { + memoryIds: ["mem_1"], + reason: "first", + })) as { success: boolean; deleted: number; total: number }; + + expect(r1.success).toBe(true); + expect(r1.deleted).toBe(1); + + const r2 = (await sdk.trigger("mem::governance-delete", { + memoryIds: ["mem_1"], + reason: "second", + })) as { success: boolean; deleted: number; total: number }; + + expect(r2.success).toBe(true); + expect(r2.deleted).toBe(0); + expect(r2.total).toBe(1); + + const remaining = await kv.list("mem:memories"); + expect(remaining.length).toBe(3); + const mem1 = remaining.find((m: Memory) => m.id === "mem_1"); + expect(mem1?.deleted).toBe(true); + }); + + it("governance-bulk creates audit entry", async () => { + const entriesBefore = (await sdk.trigger("mem::audit-query", {})) as AuditEntry[]; + + await sdk.trigger("mem::governance-bulk", { type: ["bug"] }); + + const entriesAfter = (await sdk.trigger("mem::audit-query", {})) as AuditEntry[]; + const bulkEntries = entriesAfter.filter((e: AuditEntry) => e.functionId === "mem::governance-bulk"); + expect(bulkEntries.length).toBe(1); + expect(bulkEntries[0].operation).toBe("delete"); + expect(bulkEntries[0].targetIds).toContain("mem_2"); + }); + + it("soft-delete excludes from active memory listing", async () => { + await sdk.trigger("mem::governance-delete", { memoryIds: ["mem_1", "mem_3"] }); + + const active = (await kv.list("mem:memories")).filter((m: Memory) => !m.deleted); + expect(active.length).toBe(1); + expect(active[0].type).toBe("bug"); + }); }); From c21c1896c4c3c0f4e4c21c9df550f3c390558cf1 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 16:49:23 -0400 Subject: [PATCH 19/24] feat(actions): suggest follow-up tasks from observations --- src/config.ts | 4 + src/functions/action-suggest.ts | 250 +++++++++++++++++++++ src/index.ts | 2 + src/prompts/action-suggest.ts | 54 +++++ test/action-suggest.test.ts | 374 ++++++++++++++++++++++++++++++++ 5 files changed, 684 insertions(+) create mode 100644 src/functions/action-suggest.ts create mode 100644 src/prompts/action-suggest.ts create mode 100644 test/action-suggest.test.ts diff --git a/src/config.ts b/src/config.ts index 2898552d07..d1dbe6751a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -270,6 +270,10 @@ export function isContextInjectionEnabled(): boolean { return getMergedEnv()["AGENTMEMORY_INJECT_CONTEXT"] === "true"; } +export function isActionSuggestEnabled(): boolean { + return getMergedEnv()["AGENTMEMORY_ACTION_SUGGEST"] === "true"; +} + export function getConsolidationDecayDays(): number { return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30); } diff --git a/src/functions/action-suggest.ts b/src/functions/action-suggest.ts new file mode 100644 index 0000000000..107bf32a02 --- /dev/null +++ b/src/functions/action-suggest.ts @@ -0,0 +1,250 @@ +import type { ISdk } from "iii-sdk"; +import type { + Action, + CompressedObservation, + MemoryProvider, +} from "../types.js"; +import { KV, fingerprintId } from "../state/schema.js"; +import type { StateKV } from "../state/kv.js"; +import { isActionSuggestEnabled } from "../config.js"; +import { recordAudit } from "./audit.js"; +import { + ACTION_SUGGEST_SYSTEM, + buildActionSuggestPrompt, + parseActionSuggestXml, +} from "../prompts/action-suggest.js"; +import { logger } from "../logger.js"; + +const PARTIAL_RE = /partial|incomplete|still need|still missing|not yet|remaining|left to do/i; +const TODO_RE = /todo|fixme|hack|xxx|tbd/i; + +interface ActionCandidate { + title: string; + description: string; + priority: number; + sourceObservationIds: string[]; + source: "heuristic" | "llm"; +} + +function heuristicScan( + observations: CompressedObservation[], +): ActionCandidate[] { + const candidates: ActionCandidate[] = []; + + for (const obs of observations) { + const title = obs.title || ""; + const narrative = (obs.narrative || "").toLowerCase(); + const type = obs.type; + + if (type === "error") { + candidates.push({ + title: `Fix error: ${title}`, + description: obs.narrative || title, + priority: 8, + sourceObservationIds: [obs.id], + source: "heuristic", + }); + continue; + } + + if (TODO_RE.test(title) || TODO_RE.test(narrative)) { + candidates.push({ + title, + description: obs.narrative || title, + priority: 7, + sourceObservationIds: [obs.id], + source: "heuristic", + }); + continue; + } + + if (type === "decision" && obs.importance >= 8) { + candidates.push({ + title: `Follow up: ${title}`, + description: obs.narrative || title, + priority: 6, + sourceObservationIds: [obs.id], + source: "heuristic", + }); + continue; + } + + if (type === "file_edit" && PARTIAL_RE.test(narrative)) { + candidates.push({ + title: `Complete: ${title}`, + description: obs.narrative || title, + priority: 5, + sourceObservationIds: [obs.id], + source: "heuristic", + }); + } + } + + return candidates; +} + +export function registerActionSuggestFunction( + sdk: ISdk, + kv: StateKV, + provider: MemoryProvider, +): void { + sdk.registerFunction( + "mem::action-suggest", + async (data: { + sessionId?: string; + maxObservations?: number; + project?: string; + }) => { + if (!isActionSuggestEnabled()) { + return { + success: false, + skipped: true, + reason: "AGENTMEMORY_ACTION_SUGGEST is not set to true", + }; + } + + if (!data?.sessionId || typeof data.sessionId !== "string") { + return { success: false, error: "sessionId is required" }; + } + + const max = + typeof data.maxObservations === "number" && + Number.isInteger(data.maxObservations) && + data.maxObservations > 0 + ? Math.min(200, data.maxObservations) + : 50; + + const observations = await kv.list( + KV.observations(data.sessionId), + ); + + if (observations.length === 0) { + return { + success: true, + suggested: 0, + heuristic: 0, + llm: 0, + reason: "no observations for session", + }; + } + + const recent = observations + .slice() + .sort((a, b) => (b.timestamp || "").localeCompare(a.timestamp || "")) + .slice(0, max); + + const heuristicCandidates = heuristicScan(recent); + + const heuristicIds = new Set( + heuristicCandidates.flatMap((c) => c.sourceObservationIds), + ); + + const unmatched = recent + .filter((o) => o.importance >= 7 && !heuristicIds.has(o.id)) + .slice(0, 10); + + let llmCandidates: ActionCandidate[] = []; + + if (provider.name !== "noop" && unmatched.length > 0) { + try { + const prompt = buildActionSuggestPrompt( + unmatched.map((o) => ({ + type: o.type, + title: o.title || "", + narrative: o.narrative || "", + importance: o.importance, + files: o.files, + })), + ); + + const response = await Promise.race([ + provider.summarize(ACTION_SUGGEST_SYSTEM, prompt), + new Promise((_, reject) => + setTimeout(() => reject(new Error("action-suggest timeout")), 30_000), + ), + ]); + + const parsed = parseActionSuggestXml(response).slice(0, 5); + + llmCandidates = parsed.map((a) => ({ + title: a.title, + description: a.description, + priority: a.priority, + sourceObservationIds: unmatched + .slice(0, 2) + .map((o) => o.id), + source: "llm" as const, + })); + } catch (err) { + logger.warn("LLM action suggestion failed", { + sessionId: data.sessionId, + error: err instanceof Error ? err.message : String(err), + }); + } + } + + const allCandidates = [...heuristicCandidates, ...llmCandidates]; + + const existingActions = await kv.list(KV.actions); + const existingFingerprints = new Set( + existingActions.map((a) => a.id), + ); + + const now = new Date().toISOString(); + let created = 0; + let deduped = 0; + + for (const candidate of allCandidates) { + const fp = fingerprintId("act", candidate.title.toLowerCase()); + + if (existingFingerprints.has(fp)) { + deduped++; + continue; + } + + const action: Action = { + id: fp, + title: candidate.title, + description: candidate.description, + status: "pending", + priority: candidate.priority, + createdAt: now, + updatedAt: now, + createdBy: "action-suggest", + project: data.project, + tags: ["auto-suggested"], + sourceObservationIds: candidate.sourceObservationIds, + sourceMemoryIds: [], + metadata: { source: candidate.source }, + }; + + await kv.set(KV.actions, action.id, action); + existingFingerprints.add(action.id); + created++; + } + + if (created > 0) { + await recordAudit( + kv, + "action_suggest", + "mem::action-suggest", + [data.sessionId], + { + suggested: created, + heuristic: heuristicCandidates.length, + llm: llmCandidates.length, + deduped, + }, + ); + } + + return { + success: true, + suggested: created, + heuristic: heuristicCandidates.length, + llm: llmCandidates.length, + deduped, + }; + }, + ); +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 7a746620f5..7d5446d6da 100644 --- a/src/index.ts +++ b/src/index.ts @@ -57,6 +57,7 @@ import { registerTeamFunction } from "./functions/team.js"; import { registerGovernanceFunction } from "./functions/governance.js"; import { registerSnapshotFunction } from "./functions/snapshot.js"; import { registerActionsFunction } from "./functions/actions.js"; +import { registerActionSuggestFunction } from "./functions/action-suggest.js"; import { registerFrontierFunction } from "./functions/frontier.js"; import { registerLeasesFunction } from "./functions/leases.js"; import { registerRoutinesFunction } from "./functions/routines.js"; @@ -255,6 +256,7 @@ async function main() { registerGovernanceFunction(sdk, kv); registerActionsFunction(sdk, kv); + registerActionSuggestFunction(sdk, kv, provider); registerFrontierFunction(sdk, kv); registerLeasesFunction(sdk, kv); registerRoutinesFunction(sdk, kv); diff --git a/src/prompts/action-suggest.ts b/src/prompts/action-suggest.ts new file mode 100644 index 0000000000..6e1450cdc6 --- /dev/null +++ b/src/prompts/action-suggest.ts @@ -0,0 +1,54 @@ +export const ACTION_SUGGEST_SYSTEM = `You analyze coding session observations and extract actionable work items — unfinished tasks, bugs to fix, follow-ups needed. Not everything is actionable; only output actions for genuine to-do items, bugs, or incomplete work. + +For each actionable observation, output exactly one action block: + + + +Do NOT output actions for: +- Completed work +- Pure knowledge/decisions with no follow-up needed +- Observations about what already works + +Output ONLY action blocks. No other text.`; + +export function buildActionSuggestPrompt( + observations: Array<{ + type: string; + title: string; + narrative: string; + importance: number; + files: string[]; + }>, +): string { + const lines = observations.map( + (o) => + `[type=${o.type} importance=${o.importance}] ${o.title}\n${o.narrative}\nFiles: ${o.files.join(", ")}`, + ); + return `Observations to analyze:\n\n${lines.join("\n\n")}`; +} + +export interface SuggestedAction { + title: string; + priority: number; + description: string; +} + +const ACTION_REGEX = + /[\s\S]*?<\/action>/g; + +export function parseActionSuggestXml(xml: string): SuggestedAction[] { + const actions: SuggestedAction[] = []; + let match; + while ((match = ACTION_REGEX.exec(xml)) !== null) { + const title = match[1].trim(); + const parsedPriority = parseInt(match[2], 10); + const priority = Number.isNaN(parsedPriority) + ? 5 + : Math.max(1, Math.min(10, parsedPriority)); + const description = match[3].trim(); + if (title && description) { + actions.push({ title, priority, description }); + } + } + return actions; +} \ No newline at end of file diff --git a/test/action-suggest.test.ts b/test/action-suggest.test.ts new file mode 100644 index 0000000000..24144fb949 --- /dev/null +++ b/test/action-suggest.test.ts @@ -0,0 +1,374 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; + +vi.mock("../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +vi.mock("../src/config.js", () => ({ + isActionSuggestEnabled: () => true, +})); + +import { registerActionSuggestFunction } from "../src/functions/action-suggest.js"; +import type { Action, CompressedObservation, MemoryProvider } from "../src/types.js"; + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => { + return (store.get(scope)?.get(key) as T) ?? null; + }, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }, + }; +} + +function mockSdk() { + const functions = new Map(); + return { + registerFunction: (idOrOpts: string | { id: string }, handler: Function) => { + const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id; + functions.set(id, handler); + }, + registerTrigger: () => {}, + trigger: async (idOrInput: string | { function_id: string; payload: unknown }, data?: unknown) => { + const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id; + const payload = typeof idOrInput === "string" ? data : idOrInput.payload; + const fn = functions.get(id); + if (!fn) throw new Error(`No function: ${id}`); + return fn(payload); + }, + }; +} + +function mockNoopProvider(): MemoryProvider { + return { name: "noop", compress: vi.fn(), summarize: vi.fn() }; +} + +function mockLlmProvider(responses: string[]): MemoryProvider { + let callIdx = 0; + return { + name: "test-llm", + compress: vi.fn(), + summarize: vi.fn().mockImplementation(() => { + const resp = responses[callIdx] ?? ""; + callIdx++; + return Promise.resolve(resp); + }), + }; +} + +function makeObs(overrides: Partial & { id: string; sessionId: string }): CompressedObservation { + return { + title: "Test observation", + subtitle: "", + type: "other", + facts: [], + narrative: "Something happened", + concepts: [], + files: [], + importance: 5, + timestamp: new Date().toISOString(), + ...overrides, + }; +} + +async function callSuggest(sdk: ReturnType, kv: ReturnType, sessionId: string, project?: string) { + return sdk.trigger({ + function_id: "mem::action-suggest", + payload: { sessionId, project }, + }); +} + +describe("Action Suggest Function", () => { + let sdk: ReturnType; + let kv: ReturnType; + let provider: MemoryProvider; + + beforeEach(() => { + sdk = mockSdk(); + kv = mockKV(); + provider = mockNoopProvider(); + registerActionSuggestFunction(sdk as any, kv as any, provider); + }); + + it("returns error when sessionId is missing", async () => { + const result = await callSuggest(sdk, kv, ""); + expect(result.success).toBe(false); + expect(result.error).toContain("sessionId"); + }); + + it("returns 0 suggestions when no observations exist", async () => { + const result = await callSuggest(sdk, kv, "empty-session"); + expect(result.success).toBe(true); + expect(result.suggested).toBe(0); + }); + + it("creates action for error observations", async () => { + const obs = makeObs({ + id: "obs1", + sessionId: "s1", + type: "error", + title: "TypeError: Cannot read property", + narrative: "Uncaught TypeError in auth module", + importance: 6, + }); + await kv.set("mem:obs:s1", obs.id, obs); + + const result = await callSuggest(sdk, kv, "s1", "my-project"); + expect(result.success).toBe(true); + expect(result.suggested).toBe(1); + expect(result.heuristic).toBe(1); + expect(result.llm).toBe(0); + + const actions = await kv.list("mem:actions"); + expect(actions).toHaveLength(1); + expect(actions[0].title).toContain("Fix error:"); + expect(actions[0].priority).toBe(8); + expect(actions[0].tags).toContain("auto-suggested"); + expect(actions[0].createdBy).toBe("action-suggest"); + expect(actions[0].project).toBe("my-project"); + }); + + it("creates action for TODO observations", async () => { + const obs = makeObs({ + id: "obs2", + sessionId: "s1", + type: "file_edit", + title: "TODO: Add input validation", + narrative: "Need to add validation to the form handler", + importance: 6, + }); + await kv.set("mem:obs:s1", obs.id, obs); + + const result = await callSuggest(sdk, kv, "s1"); + expect(result.success).toBe(true); + expect(result.suggested).toBe(1); + + const actions = await kv.list("mem:actions"); + expect(actions[0].title).toBe("TODO: Add input validation"); + expect(actions[0].priority).toBe(7); + }); + + it("creates action for high-importance decisions", async () => { + const obs = makeObs({ + id: "obs3", + sessionId: "s1", + type: "decision", + title: "Chose JWT over session cookies", + narrative: "Decided to use JWT for API auth", + importance: 9, + }); + await kv.set("mem:obs:s1", obs.id, obs); + + const result = await callSuggest(sdk, kv, "s1"); + expect(result.success).toBe(true); + expect(result.suggested).toBe(1); + + const actions = await kv.list("mem:actions"); + expect(actions[0].title).toContain("Follow up:"); + expect(actions[0].priority).toBe(6); + }); + + it("creates action for partial file edits", async () => { + const obs = makeObs({ + id: "obs4", + sessionId: "s1", + type: "file_edit", + title: "Partial auth middleware", + narrative: "Added partial implementation, still need to handle refresh tokens", + importance: 5, + }); + await kv.set("mem:obs:s1", obs.id, obs); + + const result = await callSuggest(sdk, kv, "s1"); + expect(result.success).toBe(true); + expect(result.suggested).toBe(1); + + const actions = await kv.list("mem:actions"); + expect(actions[0].title).toContain("Complete:"); + expect(actions[0].priority).toBe(5); + }); + + it("deduplicates actions with same title", async () => { + const obs1 = makeObs({ id: "obs5", sessionId: "s1", type: "error", title: "TypeError: Cannot read property", narrative: "Error", importance: 6 }); + const obs2 = makeObs({ id: "obs6", sessionId: "s2", type: "error", title: "TypeError: Cannot read property", narrative: "Same error again", importance: 6 }); + await kv.set("mem:obs:s1", obs1.id, obs1); + await kv.set("mem:obs:s2", obs2.id, obs2); + + await callSuggest(sdk, kv, "s1"); + await callSuggest(sdk, kv, "s2"); + + const actions = await kv.list("mem:actions"); + expect(actions).toHaveLength(1); + }); + + it("skips low-importance non-matching observations with noop provider", async () => { + const obs = makeObs({ + id: "obs7", + sessionId: "s1", + type: "file_read", + title: "Read config file", + narrative: "Checked the project configuration", + importance: 3, + }); + await kv.set("mem:obs:s1", obs.id, obs); + + const result = await callSuggest(sdk, kv, "s1"); + expect(result.success).toBe(true); + expect(result.suggested).toBe(0); + }); + + it("uses LLM fallback for high-importance unmatched observations", async () => { + const llmProvider = mockLlmProvider([ + ` +`, + ]); + const freshSdk = mockSdk(); + registerActionSuggestFunction(freshSdk as any, kv as any, llmProvider); + + const obs = makeObs({ + id: "obs8", + sessionId: "s1", + type: "discovery", + title: "Auth module has grown complex", + narrative: "Noticed the auth module has many responsibilities mixed together", + importance: 8, + }); + await kv.set("mem:obs:s1", obs.id, obs); + + const result = await freshSdk.trigger({ + function_id: "mem::action-suggest", + payload: { sessionId: "s1" }, + }); + expect(result.success).toBe(true); + expect(result.suggested).toBe(1); + expect(result.llm).toBe(1); + + const actions = await kv.list("mem:actions"); + expect(actions).toHaveLength(1); + expect(actions[0].title).toBe("Refactor auth module"); + expect(actions[0].tags).toContain("auto-suggested"); + }); + + it("handles LLM failure gracefully", async () => { + const failProvider: MemoryProvider = { + name: "failing", + compress: vi.fn(), + summarize: vi.fn().mockRejectedValue(new Error("LLM unavailable")), + }; + const freshSdk = mockSdk(); + registerActionSuggestFunction(freshSdk as any, kv as any, failProvider); + + const obs = makeObs({ + id: "obs9", + sessionId: "s1", + type: "discovery", + title: "Something important", + narrative: "Important observation without heuristic match", + importance: 8, + }); + await kv.set("mem:obs:s1", obs.id, obs); + + const result = await freshSdk.trigger({ + function_id: "mem::action-suggest", + payload: { sessionId: "s1" }, + }); + expect(result.success).toBe(true); + expect(result.suggested).toBe(0); + expect(result.llm).toBe(0); + }); + + it("matches FIXME in narrative", async () => { + const freshSdk = mockSdk(); + registerActionSuggestFunction(freshSdk as any, kv as any, mockNoopProvider()); + + const obs = makeObs({ + id: "obs-fixme", + sessionId: "s-fixme", + type: "file_edit", + title: "Quick patch for login", + narrative: "FIXME: this is a hack, need proper solution", + importance: 5, + }); + await kv.set("mem:obs:s-fixme", obs.id, obs); + + const result = await freshSdk.trigger({ + function_id: "mem::action-suggest", + payload: { sessionId: "s-fixme" }, + }); + expect(result.suggested).toBe(1); + }); + + it("matches TBD in title", async () => { + const freshSdk = mockSdk(); + registerActionSuggestFunction(freshSdk as any, kv as any, mockNoopProvider()); + + const obs = makeObs({ + id: "obs-tbd", + sessionId: "s-tbd", + type: "conversation", + title: "TBD: rate limiting strategy", + narrative: "Discussion about rate limiting", + importance: 5, + }); + await kv.set("mem:obs:s-tbd", obs.id, obs); + + const result = await freshSdk.trigger({ + function_id: "mem::action-suggest", + payload: { sessionId: "s-tbd" }, + }); + expect(result.suggested).toBe(1); + }); + + it("does not create action for completed work", async () => { + const freshSdk = mockSdk(); + registerActionSuggestFunction(freshSdk as any, kv as any, mockNoopProvider()); + + const obs = makeObs({ + id: "obs-done", + sessionId: "s-done", + type: "file_edit", + title: "Implemented auth middleware", + narrative: "Successfully implemented the full auth middleware with tests", + importance: 7, + }); + await kv.set("mem:obs:s-done", obs.id, obs); + + const result = await freshSdk.trigger({ + function_id: "mem::action-suggest", + payload: { sessionId: "s-done" }, + }); + expect(result.suggested).toBe(0); + }); + + it("does not create decision action for low importance", async () => { + const freshSdk = mockSdk(); + registerActionSuggestFunction(freshSdk as any, kv as any, mockNoopProvider()); + + const obs = makeObs({ + id: "obs-low-dec", + sessionId: "s-low-dec", + type: "decision", + title: "Used tabs instead of spaces", + narrative: "Minor formatting decision", + importance: 3, + }); + await kv.set("mem:obs:s-low-dec", obs.id, obs); + + const result = await freshSdk.trigger({ + function_id: "mem::action-suggest", + payload: { sessionId: "s-low-dec" }, + }); + expect(result.suggested).toBe(0); + }); +}); From c28b5cbb85130847c2e09e2e8a461140c8048ea5 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 16:49:41 -0400 Subject: [PATCH 20/24] test: isolate env-backed provider settings --- src/config.ts | 2 +- test/auto-compress.test.ts | 3 ++- test/embedding-provider.test.ts | 11 ++++++----- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/config.ts b/src/config.ts index d1dbe6751a..004470519d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -83,7 +83,7 @@ function detectProvider(env: Record): ProviderConfig { if (hasRealValue(env["OPENROUTER_API_KEY"])) { return { provider: "openrouter", - model: env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514", + model: env["OPENROUTER_MODEL"] || "ibm-granite/granite-4.1-8b", maxTokens, }; } diff --git a/test/auto-compress.test.ts b/test/auto-compress.test.ts index fdcced8fe3..1fbd47342b 100644 --- a/test/auto-compress.test.ts +++ b/test/auto-compress.test.ts @@ -79,7 +79,8 @@ describe("mem::observe auto-compress gate (#138)", () => { // test that sets the env var can be undermined by cached module // state from an earlier test (and vice versa). vi.resetModules(); - delete process.env["AGENTMEMORY_AUTO_COMPRESS"]; + // Explicitly disable auto-compress to override any .env file setting + process.env["AGENTMEMORY_AUTO_COMPRESS"] = "false"; }); afterEach(() => { delete process.env["AGENTMEMORY_AUTO_COMPRESS"]; diff --git a/test/embedding-provider.test.ts b/test/embedding-provider.test.ts index e6442ae4e7..e0ad0bf6bf 100644 --- a/test/embedding-provider.test.ts +++ b/test/embedding-provider.test.ts @@ -12,11 +12,12 @@ describe("createEmbeddingProvider", () => { beforeEach(() => { process.env = { ...originalEnv }; - delete process.env["GEMINI_API_KEY"]; - delete process.env["OPENAI_API_KEY"]; - delete process.env["VOYAGE_API_KEY"]; - delete process.env["COHERE_API_KEY"]; - delete process.env["OPENROUTER_API_KEY"]; + // Override .env file values by setting empty strings + process.env["GEMINI_API_KEY"] = ""; + process.env["OPENAI_API_KEY"] = ""; + process.env["VOYAGE_API_KEY"] = ""; + process.env["COHERE_API_KEY"] = ""; + process.env["OPENROUTER_API_KEY"] = ""; delete process.env["EMBEDDING_PROVIDER"]; }); From 14db245fb5350b553fa4126697710f11eb41c139 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 17:12:15 -0400 Subject: [PATCH 21/24] feat(codex): add parity hooks --- .dockerignore | 9 ++++ README.md | 8 +-- plugin/.codex-plugin/plugin.json | 2 +- plugin/hooks/hooks.codex.json | 21 ++++++++ plugin/opencode/README.md | 2 +- plugin/opencode/plugin.json | 4 +- plugin/scripts/permission-request.mjs | 63 +++++++++++++++++++++++ plugin/scripts/post-compact.mjs | 61 +++++++++++++++++++++++ src/hooks/permission-request.ts | 72 +++++++++++++++++++++++++++ src/hooks/post-compact.ts | 69 +++++++++++++++++++++++++ test/codex-plugin.test.ts | 17 +++++++ tsdown.config.ts | 2 + 12 files changed, 323 insertions(+), 7 deletions(-) create mode 100644 .dockerignore create mode 100755 plugin/scripts/permission-request.mjs create mode 100755 plugin/scripts/post-compact.mjs create mode 100644 src/hooks/permission-request.ts create mode 100644 src/hooks/post-compact.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..7cf00b705d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +node_modules +dist +coverage +.git +.env +*.log +data +website/node_modules +website/dist diff --git a/README.md b/README.md index 7522302fdd..2597c4a109 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ agentmemory works with any agent that supports hooks, MCP, or REST API. All agen Codex CLI
Codex CLI
-6 hooks + MCP + skills +8 hooks + MCP + skills Cline
@@ -369,11 +369,13 @@ codex plugin install agentmemory The Codex plugin ships from the same `plugin/` directory as the Claude Code plugin. It registers: - `@agentmemory/mcp` as an MCP server (13 consolidated tools when `AGENTMEMORY_TOOLS=all`, plus backward-compatible legacy aliases) -- 6 lifecycle hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop` +- 8 lifecycle hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PermissionRequest`, `PreCompact`, `PostCompact`, `Stop` - 4 skills: `/recall`, `/remember`, `/session-history`, `/forget` Codex's hook engine injects `CLAUDE_PLUGIN_ROOT` into hook subprocesses (per [`codex-rs/hooks/src/engine/discovery.rs`](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/discovery.rs)), so the same hook scripts work across both hosts without duplication. Subagent / SessionEnd / Notification / TaskCompleted / PostToolUseFailure events are Claude-Code-only and are not registered for Codex. +Codex parity with the OpenCode plugin covers the hook categories Codex exposes: session start/stop, prompt capture, pre/post tool capture, permission prompts, and pre/post compaction. OpenCode-only SDK events such as `message.part.updated`, `chat.params`, `todo.updated`, `file.edited`, and system-prompt transform injection do not have direct Codex hook equivalents today; Codex gets memory guidance through bundled skills plus the MCP tool descriptions. +
OpenClaw (paste this prompt) @@ -447,7 +449,7 @@ The agentmemory entry is the **same MCP server block** across every host that us | **Gemini CLI** | `~/.gemini/settings.json` | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` (auto-merges). | | **OpenClaw** | OpenClaw MCP config | Same `mcpServers` block, or use the deeper [memory plugin](integrations/openclaw/). | | **Codex CLI (MCP only)** | `.codex/config.toml` | TOML shape: `codex mcp add agentmemory -- npx -y @agentmemory/mcp`, or add `[mcp_servers.agentmemory]` manually. | -| **Codex CLI (full plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` then `codex plugin install agentmemory`. Registers MCP + 6 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop) + 4 skills. | +| **Codex CLI (full plugin)** | Codex plugin marketplace | `codex plugin marketplace add rohitg00/agentmemory` then `codex plugin install agentmemory`. Registers MCP + 8 lifecycle hooks (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PermissionRequest, PreCompact, PostCompact, Stop) + 4 skills. | | **OpenCode** | `opencode.json` | Different shape — top-level `mcp` key, command as array: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}`. | | **pi** | `~/.pi/agent/extensions/agentmemory` | Copy [`integrations/pi`](integrations/pi/) and restart pi. | | **Hermes Agent** | `~/.hermes/config.yaml` | Use the deeper [memory provider plugin](integrations/hermes/) with `memory.provider: agentmemory`. | diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index 49a29ab98d..27b002644a 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agentmemory", "version": "0.9.11", - "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 13 MCP tools, 4 skills, real-time viewer.", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 8 hooks, 13 MCP tools, 4 skills, real-time viewer.", "author": { "name": "Rohit Ghumare", "url": "https://github.com/rohitg00" diff --git a/plugin/hooks/hooks.codex.json b/plugin/hooks/hooks.codex.json index 73e43c666b..c271bdf9f2 100644 --- a/plugin/hooks/hooks.codex.json +++ b/plugin/hooks/hooks.codex.json @@ -53,6 +53,27 @@ ] } ], + "PostCompact": [ + { + "hooks": [ + { + "type": "command", + "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/post-compact.mjs" + } + ] + } + ], + "PermissionRequest": [ + { + "hooks": [ + { + "type": "command", + "command": "node ${CLAUDE_PLUGIN_ROOT}/scripts/permission-request.mjs", + "statusMessage": "agentmemory: capturing permission request" + } + ] + } + ], "Stop": [ { "hooks": [ diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md index e5776978cc..90bcc797e6 100644 --- a/plugin/opencode/README.md +++ b/plugin/opencode/README.md @@ -9,7 +9,7 @@

- 51 MCP tools + 13 MCP tools 22 hooks 2 slash commands 95.2% R@5 diff --git a/plugin/opencode/plugin.json b/plugin/opencode/plugin.json index a66e437a2f..1aee16faf6 100644 --- a/plugin/opencode/plugin.json +++ b/plugin/opencode/plugin.json @@ -1,7 +1,7 @@ { "name": "agentmemory-capture", - "version": "0.9.4", - "description": "OpenCode plugin for agentmemory — full Claude Code hook parity: session lifecycle (create/idle/status/compacted/update/diff/delete/error), messages & prompts (chat.message, message.updated user+assistant, message.removed), tool lifecycle (ToolPart states with timing), part tracking (subtask, step-finish, reasoning, file, patch, compaction, agent, retry), file enrichment pipeline, permissions, task tracking (w/ priority), commands, config & model tracking. 22 hooks, 2 slash commands.", + "version": "0.9.11", + "description": "OpenCode plugin for agentmemory — full Claude Code hook parity: session lifecycle (create/idle/status/compacted/update/diff/delete/error), messages & prompts (chat.message, message.updated user+assistant, message.removed), tool lifecycle (ToolPart states with timing), part tracking (subtask, step-finish, reasoning, file, patch, compaction, agent, retry), file enrichment pipeline, permissions, task tracking (w/ priority), commands, config & model tracking. 22 hooks, 13 MCP tools, 2 slash commands.", "author": { "name": "Rohit Ghumare", "url": "https://github.com/rohitg00" diff --git a/plugin/scripts/permission-request.mjs b/plugin/scripts/permission-request.mjs new file mode 100755 index 0000000000..b4ea9edc0f --- /dev/null +++ b/plugin/scripts/permission-request.mjs @@ -0,0 +1,63 @@ +#!/usr/bin/env node +//#region src/hooks/permission-request.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +function asText(value, max) { + if (typeof value === "string") return value.slice(0, max); + if (value == null) return ""; + try { + return JSON.stringify(value).slice(0, max); + } catch { + return String(value).slice(0, max); + } +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || "unknown"; + const cwd = data.cwd || process.cwd(); + try { + await fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "notification", + sessionId, + project: cwd, + cwd, + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + notification_type: "permission_request", + tool_name: data.tool_name, + tool_input: asText(data.tool_input, 4e3), + permission: data.permission || data.permission_type || data.action || null, + title: data.title || data.tool_name || "Permission request", + message: asText(data.message || data.reason || data, 4e3) + } + }), + signal: AbortSignal.timeout(3e3) + }); + } catch {} +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=permission-request.mjs.map \ No newline at end of file diff --git a/plugin/scripts/post-compact.mjs b/plugin/scripts/post-compact.mjs new file mode 100755 index 0000000000..859e648f90 --- /dev/null +++ b/plugin/scripts/post-compact.mjs @@ -0,0 +1,61 @@ +#!/usr/bin/env node +//#region src/hooks/post-compact.ts +function isSdkChildContext(payload) { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return payload.entrypoint === "sdk-ts"; +} +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +function authHeaders() { + const h = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} +async function post(path, body, timeoutMs) { + try { + await fetch(`${REST_URL}/agentmemory${path}`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs) + }); + } catch {} +} +async function main() { + let input = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + const sessionId = data.session_id || "unknown"; + const cwd = data.cwd || process.cwd(); + await post("/observe", { + hookType: "session_compacted", + sessionId, + project: cwd, + cwd, + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data: { + source: "codex_post_compact", + summary: data.summary || data.compaction || null + } + }, 3e3); + await post("/summarize", { sessionId }, 12e4); + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + await post("/crystals/auto", { olderThanDays: 0 }, 6e4); + await post("/consolidate-pipeline", { + tier: "all", + force: true + }, 12e4); + } +} +main(); + +//#endregion +export { }; +//# sourceMappingURL=post-compact.mjs.map \ No newline at end of file diff --git a/src/hooks/permission-request.ts b/src/hooks/permission-request.ts new file mode 100644 index 0000000000..e55a3a4e4e --- /dev/null +++ b/src/hooks/permission-request.ts @@ -0,0 +1,72 @@ +#!/usr/bin/env node + +function isSdkChildContext(payload: unknown): boolean { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts"; +} + +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; + +function authHeaders(): Record { + const h: Record = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} + +function asText(value: unknown, max: number): string { + if (typeof value === "string") return value.slice(0, max); + if (value == null) return ""; + try { + return JSON.stringify(value).slice(0, max); + } catch { + return String(value).slice(0, max); + } +} + +async function main() { + let input = ""; + for await (const chunk of process.stdin) { + input += chunk; + } + + let data: Record; + try { + data = JSON.parse(input); + } catch { + return; + } + + if (isSdkChildContext(data)) return; + + const sessionId = (data.session_id as string) || "unknown"; + const cwd = (data.cwd as string) || process.cwd(); + + try { + await fetch(`${REST_URL}/agentmemory/observe`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify({ + hookType: "notification", + sessionId, + project: cwd, + cwd, + timestamp: new Date().toISOString(), + data: { + notification_type: "permission_request", + tool_name: data.tool_name, + tool_input: asText(data.tool_input, 4000), + permission: data.permission || data.permission_type || data.action || null, + title: data.title || data.tool_name || "Permission request", + message: asText(data.message || data.reason || data, 4000), + }, + }), + signal: AbortSignal.timeout(3000), + }); + } catch { + // best effort -- never block the permission flow + } +} + +main(); diff --git a/src/hooks/post-compact.ts b/src/hooks/post-compact.ts new file mode 100644 index 0000000000..9f831230ab --- /dev/null +++ b/src/hooks/post-compact.ts @@ -0,0 +1,69 @@ +#!/usr/bin/env node + +function isSdkChildContext(payload: unknown): boolean { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts"; +} + +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; + +function authHeaders(): Record { + const h: Record = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} + +async function post(path: string, body: Record, timeoutMs: number): Promise { + try { + await fetch(`${REST_URL}/agentmemory${path}`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch { + // best effort + } +} + +async function main() { + let input = ""; + for await (const chunk of process.stdin) { + input += chunk; + } + + let data: Record; + try { + data = JSON.parse(input); + } catch { + return; + } + + if (isSdkChildContext(data)) return; + + const sessionId = (data.session_id as string) || "unknown"; + const cwd = (data.cwd as string) || process.cwd(); + + await post("/observe", { + hookType: "session_compacted", + sessionId, + project: cwd, + cwd, + timestamp: new Date().toISOString(), + data: { + source: "codex_post_compact", + summary: data.summary || data.compaction || null, + }, + }, 3000); + + await post("/summarize", { sessionId }, 120000); + + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + await post("/crystals/auto", { olderThanDays: 0 }, 60000); + await post("/consolidate-pipeline", { tier: "all", force: true }, 120000); + } +} + +main(); diff --git a/test/codex-plugin.test.ts b/test/codex-plugin.test.ts index bb38087643..d87ef25f72 100644 --- a/test/codex-plugin.test.ts +++ b/test/codex-plugin.test.ts @@ -67,10 +67,27 @@ describe("Codex plugin manifest (developers.openai.com/codex/plugins)", () => { expect(events).toContain("UserPromptSubmit"); expect(events).toContain("PreToolUse"); expect(events).toContain("PostToolUse"); + expect(events).toContain("PermissionRequest"); expect(events).toContain("PreCompact"); + expect(events).toContain("PostCompact"); expect(events).toContain("Stop"); }); + it("Codex parity hooks cover the OpenCode-equivalent lifecycle exposed by Codex", () => { + const hooksPath = join(pluginRoot, "hooks/hooks.codex.json"); + const hooks = readJson<{ hooks: Record }>(hooksPath); + expect(Object.keys(hooks.hooks).sort()).toEqual([ + "PermissionRequest", + "PostCompact", + "PostToolUse", + "PreCompact", + "PreToolUse", + "SessionStart", + "Stop", + "UserPromptSubmit", + ]); + }); + it("hook command scripts referenced in hooks.codex.json exist on disk", () => { type HookHandler = { type: string; command: string }; type HookEntry = { hooks: HookHandler[] }; diff --git a/tsdown.config.ts b/tsdown.config.ts index 2c30a48b37..8c375cf67a 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -7,6 +7,8 @@ const hookEntries = [ "src/hooks/post-tool-use.ts", "src/hooks/post-tool-failure.ts", "src/hooks/pre-compact.ts", + "src/hooks/post-compact.ts", + "src/hooks/permission-request.ts", "src/hooks/subagent-start.ts", "src/hooks/subagent-stop.ts", "src/hooks/notification.ts", From 71239fbd340bb7be036f9da3556403c13cdde9c9 Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 18:51:58 -0400 Subject: [PATCH 22/24] fix(review): address mcp and governance feedback --- plugin/opencode/README.md | 4 +- plugin/scripts/post-compact.mjs | 10 ++- src/functions/governance.ts | 13 ++- src/functions/lessons.ts | 3 +- src/functions/reflect.ts | 27 ++++-- src/hooks/post-compact.ts | 18 +++- src/mcp/server.ts | 60 ++++++++++--- src/mcp/standalone.ts | 9 +- src/mcp/tools-registry.ts | 5 +- src/prompts/action-suggest.ts | 18 ++-- test/action-suggest.test.ts | 15 ++++ test/mcp-standalone-proxy.test.ts | 5 +- test/mcp-tools-call.test.ts | 139 ++++++++++++++++++++++++++++++ 13 files changed, 277 insertions(+), 49 deletions(-) create mode 100644 test/mcp-tools-call.test.ts diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md index 90bcc797e6..ddf440bcd7 100644 --- a/plugin/opencode/README.md +++ b/plugin/opencode/README.md @@ -172,7 +172,7 @@ Claude Code and OpenCode take fundamentally different approaches to injecting me ### Claude Code: file-backed bridge (two-hop) -``` +```text agentmemory ──write──▶ MEMORY.md ──read──▶ Claude system prompt ``` @@ -183,7 +183,7 @@ agentmemory ──write──▶ MEMORY.md ──read──▶ Claude system ### OpenCode: direct injection (one-hop) -``` +```text agentmemory ──push──▶ OpenCode system prompt ``` diff --git a/plugin/scripts/post-compact.mjs b/plugin/scripts/post-compact.mjs index 859e648f90..6ab12b64e1 100755 --- a/plugin/scripts/post-compact.mjs +++ b/plugin/scripts/post-compact.mjs @@ -14,13 +14,16 @@ function authHeaders() { } async function post(path, body, timeoutMs) { try { - await fetch(`${REST_URL}/agentmemory${path}`, { + const response = await fetch(`${REST_URL}/agentmemory${path}`, { method: "POST", headers: authHeaders(), body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) }); - } catch {} + if (!response.ok) process.stderr.write(`[agentmemory] post-compact POST ${path} failed: ${response.status} ${response.statusText}\n`); + } catch (err) { + process.stderr.write(`[agentmemory] post-compact POST ${path} failed: ${err instanceof Error ? err.message : String(err)}\n`); + } } async function main() { let input = ""; @@ -32,7 +35,8 @@ async function main() { return; } if (isSdkChildContext(data)) return; - const sessionId = data.session_id || "unknown"; + const sessionId = typeof data.session_id === "string" && data.session_id.trim() ? data.session_id.trim() : void 0; + if (!sessionId) return; const cwd = data.cwd || process.cwd(); await post("/observe", { hookType: "session_compacted", diff --git a/src/functions/governance.ts b/src/functions/governance.ts index 5f6ec555c2..f154f13d5e 100644 --- a/src/functions/governance.ts +++ b/src/functions/governance.ts @@ -24,6 +24,7 @@ async function cascadeStale(kv: StateKV, memoryId: string): Promise { for (const edge of edges) { if (!edge.stale && edge.sourceObservationIds.includes(memoryId)) { edge.stale = true; + edge.updatedAt = now; edgeUpdates.push(kv.set(KV.graphEdges, edge.id, edge)); } } @@ -43,11 +44,12 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { } let deleted = 0; + const opTimestamp = new Date().toISOString(); for (const id of data.memoryIds) { const mem = await kv.get(KV.memories, id); if (mem && !mem.deleted) { mem.deleted = true; - mem.updatedAt = new Date().toISOString(); + mem.updatedAt = opTimestamp; await kv.set(KV.memories, id, mem); await deleteAccessLog(kv, id); await cascadeStale(kv, id); @@ -129,21 +131,26 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { const BATCH_SIZE = 50; const successfulIds: string[] = []; const failures: Array<{ id: string; error: string }> = []; + const opTimestamp = new Date().toISOString(); for (let i = 0; i < candidates.length; i += BATCH_SIZE) { const batch = candidates.slice(i, i + BATCH_SIZE); const results = await Promise.allSettled( batch.map(async (mem) => { + if (mem.deleted) return "skipped"; mem.deleted = true; - mem.updatedAt = new Date().toISOString(); + mem.updatedAt = opTimestamp; await kv.set(KV.memories, mem.id, mem); await deleteAccessLog(kv, mem.id); await cascadeStale(kv, mem.id); + return "deleted"; }), ); results.forEach((result, j) => { const mem = batch[j]; - if (result.status === "fulfilled") { + if (result.status === "fulfilled" && result.value === "deleted") { successfulIds.push(mem.id); + } else if (result.status === "fulfilled") { + return; } else { logger.warn("Governance bulk delete failed", { memoryId: mem.id, diff --git a/src/functions/lessons.ts b/src/functions/lessons.ts index 8b33530aa3..03a5f4d49d 100644 --- a/src/functions/lessons.ts +++ b/src/functions/lessons.ts @@ -180,7 +180,8 @@ export function registerLessonsFunctions(sdk: ISdk, kv: StateKV): void { project: data.project, source: data.source, minConfidence: data.minConfidence, - resultCount: lessons.length, + resultCount: lessonIds.length, + totalMatched: lessons.length, }); } catch {} diff --git a/src/functions/reflect.ts b/src/functions/reflect.ts index 05d4478355..4280d6bdcf 100644 --- a/src/functions/reflect.ts +++ b/src/functions/reflect.ts @@ -481,21 +481,30 @@ export function registerReflectFunctions( insightIds?: string[]; reason?: string; }) => { - const ids = data.insightId ? [data.insightId] : (data.insightIds ?? []); + const rawIds = [ + ...(typeof data.insightId === "string" ? [data.insightId] : []), + ...(Array.isArray(data.insightIds) ? data.insightIds : []), + ]; + const ids = [...new Set(rawIds.map((id) => id.trim()).filter(Boolean))]; if (!ids.length) { return { success: false, error: "insightId or insightIds is required" }; } - let deleted = 0; const now = new Date().toISOString(); - for (const id of ids) { - const insight = await kv.get(KV.insights, id); - if (insight) { + const loaded = await Promise.all( + ids.map(async (id) => ({ id, insight: await kv.get(KV.insights, id) })), + ); + const toDelete = loaded.filter( + (item): item is { id: string; insight: Insight } => + Boolean(item.insight && !item.insight.deleted), + ); + await Promise.all( + toDelete.map(({ id, insight }) => { insight.deleted = true; insight.updatedAt = now; - await kv.set(KV.insights, id, insight); - deleted++; - } - } + return kv.set(KV.insights, id, insight); + }), + ); + const deleted = toDelete.length; await recordAudit(kv, "delete", "mem::insight-delete", ids, { reason: data.reason || "manual deletion", deleted, diff --git a/src/hooks/post-compact.ts b/src/hooks/post-compact.ts index 9f831230ab..13ae42c929 100644 --- a/src/hooks/post-compact.ts +++ b/src/hooks/post-compact.ts @@ -17,14 +17,21 @@ function authHeaders(): Record { async function post(path: string, body: Record, timeoutMs: number): Promise { try { - await fetch(`${REST_URL}/agentmemory${path}`, { + const response = await fetch(`${REST_URL}/agentmemory${path}`, { method: "POST", headers: authHeaders(), body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs), }); - } catch { - // best effort + if (!response.ok) { + process.stderr.write( + `[agentmemory] post-compact POST ${path} failed: ${response.status} ${response.statusText}\n`, + ); + } + } catch (err) { + process.stderr.write( + `[agentmemory] post-compact POST ${path} failed: ${err instanceof Error ? err.message : String(err)}\n`, + ); } } @@ -43,7 +50,10 @@ async function main() { if (isSdkChildContext(data)) return; - const sessionId = (data.session_id as string) || "unknown"; + const sessionId = typeof data.session_id === "string" && data.session_id.trim() + ? data.session_id.trim() + : undefined; + if (!sessionId) return; const cwd = (data.cwd as string) || process.cwd(); await post("/observe", { diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 370199e7b4..ff90102ba0 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -99,7 +99,7 @@ export function registerMcpEndpoints( case "memory_file_history": case "memory_graph_query": case "memory_vision_search": { - const scope = (args.scope as string) || "keyword"; + const scope = (args.scope as string) || (args.operation as string) || "keyword"; if (scope === "keyword" || name === "memory_recall") { if (typeof args.query !== "string" || !args.query.trim()) { return { status_code: 400, body: { error: "query is required" } }; @@ -441,6 +441,21 @@ export function registerMcpEndpoints( case "crystal": case "memory_crystallize": { + const rawOp = args.operation === undefined || args.operation === null ? undefined : args.operation; + const opVal = asValidatedOperation(rawOp, ["list", "crystallize"]); + const operation = opVal || (name === "memory_crystallize" ? "crystallize" : "list"); + if (operation === "list") { + const limit = asNumber(args.limit, 50); + if (!Number.isInteger(limit) || (limit ?? 0) <= 0) { + return { status_code: 400, body: { error: "limit must be a positive integer" } }; + } + const result = await sdk.trigger({ function_id: "mem::crystal-list", payload: { + project: asNonEmptyString(args.project), + sessionId: asNonEmptyString(args.sessionId), + limit, + } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } if (typeof args.actionIds !== "string" || !args.actionIds.trim()) { return { status_code: 400, body: { error: "actionIds is required" } }; } @@ -473,18 +488,28 @@ export function registerMcpEndpoints( return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } if (operation === "list" || name === "memory_lesson_list") { - const project = typeof args.project === "string" ? args.project : undefined; - const source = typeof args.source === "string" && ["manual", "crystal", "consolidation"].includes(args.source) ? args.source : undefined; - const minConfidence = typeof args.minConfidence === "number" ? args.minConfidence : undefined; - const limit = typeof args.limit === "number" && args.limit > 0 ? args.limit : 50; + const project = asNonEmptyString(args.project); + const source = asNonEmptyString(args.source); + if (source !== undefined && !["manual", "crystal", "consolidation"].includes(source)) { + return { status_code: 400, body: { error: "source must be one of: manual, crystal, consolidation" } }; + } + const minConfidence = asNumber(args.minConfidence); + if (minConfidence !== undefined && (minConfidence < 0 || minConfidence > 1)) { + return { status_code: 400, body: { error: "minConfidence must be between 0 and 1" } }; + } + const limit = asNumber(args.limit, 50); + if (!Number.isInteger(limit) || (limit ?? 0) <= 0) { + return { status_code: 400, body: { error: "limit must be a positive integer" } }; + } const result = await sdk.trigger({ function_id: "mem::lesson-list", payload: { project, source, minConfidence, limit } }); return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } if (operation === "strengthen" || name === "memory_lesson_strengthen") { - if (typeof args.lessonId !== "string" || !args.lessonId.trim()) { + const lessonId = asNonEmptyString(args.lessonId); + if (!lessonId) { return { status_code: 400, body: { error: "lessonId is required" } }; } - const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId: args.lessonId } }); + const result = await sdk.trigger({ function_id: "mem::lesson-strengthen", payload: { lessonId } }); return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } return { status_code: 400, body: { error: "Invalid operation" } }; @@ -501,11 +526,19 @@ export function registerMcpEndpoints( return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } if (operation === "delete") { - if (typeof args.insightId !== "string" || !args.insightId.trim()) { - return { status_code: 400, body: { error: "insightId is required" } }; + const ids = [ + ...parseCsvList(args.insightIds), + ...parseCsvList(args.insightId), + ].slice(0, MAX_IDS); + if (ids.length === 0) { + return { status_code: 400, body: { error: "insightIds is required" } }; } - const result = await sdk.trigger({ function_id: "mem::insight-delete", payload: { insightId: args.insightId } }); - return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + const results = await Promise.all( + ids.map((insightId) => + sdk.trigger({ function_id: "mem::insight-delete", payload: { insightId, reason: args.reason as string } }), + ), + ); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify({ success: true, results }, null, 2) }] } }; } return { status_code: 400, body: { error: "Invalid operation" } }; } @@ -587,7 +620,8 @@ export function registerMcpEndpoints( } if (operation === "audit" || name === "memory_audit") { try { - const result = await sdk.trigger({ function_id: "mem::audit-query", payload: { operation: args.operation as string, limit: typeof args.limit === "number" ? args.limit : 50 } }); + const auditOperation = asNonEmptyString(args.operation_filter); + const result = await sdk.trigger({ function_id: "mem::audit-query", payload: { operation: auditOperation, limit: typeof args.limit === "number" ? args.limit : 50 } }); return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; } catch (err) { return { status_code: 500, body: { content: [{ type: "text", text: "Audit query failed: " + (err instanceof Error ? err.message : String(err)) }], isError: true } }; @@ -1168,4 +1202,4 @@ export function registerMcpEndpoints( function_id: "mcp::prompts::get", config: { api_path: "/agentmemory/mcp/prompts/get", http_method: "POST" }, }); -} \ No newline at end of file +} diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts index 7272bf4a30..16ff1f5d5b 100644 --- a/src/mcp/standalone.ts +++ b/src/mcp/standalone.ts @@ -389,10 +389,13 @@ async function handleLocal( } case "memory_governance_delete": { let deleted = 0; + const now = new Date().toISOString(); for (const id of v.memoryIds || []) { - const existing = await kvInstance.get("mem:memories", id); - if (existing) { - await kvInstance.delete("mem:memories", id); + const existing = await kvInstance.get>("mem:memories", id); + if (existing && existing["deleted"] !== true) { + existing["deleted"] = true; + existing["updatedAt"] = now; + await kvInstance.set("mem:memories", id, existing); deleted++; } } diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts index 3a30feb022..61d21302c6 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -46,7 +46,6 @@ export const CORE_TOOLS: McpToolDef[] = [ token_budget: { type: "number", description: "Token budget to trim results" }, limit: { type: "number", description: "Max results (default 10)" }, }, - required: ["query"], }, }, { @@ -186,7 +185,7 @@ export const CORE_TOOLS: McpToolDef[] = [ project: { type: "string", description: "Project context" }, sketchId: { type: "string", description: "Sketch ID to promote" }, }, - required: ["operation", "title"], + required: ["operation"], }, }, ]; @@ -315,4 +314,4 @@ export function getVisibleTools(): McpToolDef[] { const mode = process.env["AGENTMEMORY_TOOLS"] || "core"; if (mode === "all") return getAllTools(); return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name)); -} \ No newline at end of file +} diff --git a/src/prompts/action-suggest.ts b/src/prompts/action-suggest.ts index 6e1450cdc6..681990d75f 100644 --- a/src/prompts/action-suggest.ts +++ b/src/prompts/action-suggest.ts @@ -33,22 +33,26 @@ export interface SuggestedAction { description: string; } -const ACTION_REGEX = - /[\s\S]*?<\/action>/g; +const ACTION_BLOCK_REGEX = /]*)>[\s\S]*?<\/action>/g; +const ACTION_ATTR_REGEX = /\b(title|priority|description)="([^"]*)"/g; export function parseActionSuggestXml(xml: string): SuggestedAction[] { const actions: SuggestedAction[] = []; let match; - while ((match = ACTION_REGEX.exec(xml)) !== null) { - const title = match[1].trim(); - const parsedPriority = parseInt(match[2], 10); + while ((match = ACTION_BLOCK_REGEX.exec(xml)) !== null) { + const attrs = new Map(); + for (const attr of match[1].matchAll(ACTION_ATTR_REGEX)) { + attrs.set(attr[1], attr[2]); + } + const title = (attrs.get("title") ?? "").trim(); + const parsedPriority = parseInt(attrs.get("priority") ?? "", 10); const priority = Number.isNaN(parsedPriority) ? 5 : Math.max(1, Math.min(10, parsedPriority)); - const description = match[3].trim(); + const description = (attrs.get("description") ?? "").trim(); if (title && description) { actions.push({ title, priority, description }); } } return actions; -} \ No newline at end of file +} diff --git a/test/action-suggest.test.ts b/test/action-suggest.test.ts index 24144fb949..492c9e4a8c 100644 --- a/test/action-suggest.test.ts +++ b/test/action-suggest.test.ts @@ -9,6 +9,7 @@ vi.mock("../src/config.js", () => ({ })); import { registerActionSuggestFunction } from "../src/functions/action-suggest.js"; +import { parseActionSuggestXml } from "../src/prompts/action-suggest.js"; import type { Action, CompressedObservation, MemoryProvider } from "../src/types.js"; function mockKV() { @@ -139,6 +140,20 @@ describe("Action Suggest Function", () => { expect(actions[0].project).toBe("my-project"); }); + it("parses LLM action tags regardless of attribute order", () => { + const actions = parseActionSuggestXml( + '', + ); + + expect(actions).toEqual([ + { + title: "Fix auth race", + priority: 8, + description: "Fix the auth race", + }, + ]); + }); + it("creates action for TODO observations", async () => { const obs = makeObs({ id: "obs2", diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts index 478227eb96..8a5e2db789 100644 --- a/test/mcp-standalone-proxy.test.ts +++ b/test/mcp-standalone-proxy.test.ts @@ -301,7 +301,10 @@ describe("@agentmemory/mcp standalone — server proxy (issue #159)", () => { resetHandleForTests(); process.env["AGENTMEMORY_TOOLS"] = "core"; const core = await handleToolsList(); - expect((core.tools as unknown[]).length).toBe(2); + expect((core.tools as Array<{ name: string }>).map((t) => t.name).sort()).toEqual([ + "memory_search", + "memory_store", + ]); delete process.env["AGENTMEMORY_TOOLS"]; }); diff --git a/test/mcp-tools-call.test.ts b/test/mcp-tools-call.test.ts new file mode 100644 index 0000000000..f962fd9325 --- /dev/null +++ b/test/mcp-tools-call.test.ts @@ -0,0 +1,139 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; + +vi.mock("../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +import { registerMcpEndpoints } from "../src/mcp/server.js"; +import { getAllTools } from "../src/mcp/tools-registry.js"; + +function mockKV() { + const store = new Map>(); + return { + get: async (scope: string, key: string): Promise => { + return (store.get(scope)?.get(key) as T) ?? null; + }, + set: async (scope: string, key: string, data: T): Promise => { + if (!store.has(scope)) store.set(scope, new Map()); + store.get(scope)!.set(key, data); + return data; + }, + delete: async (scope: string, key: string): Promise => { + store.get(scope)?.delete(key); + }, + list: async (scope: string): Promise => { + const entries = store.get(scope); + return entries ? (Array.from(entries.values()) as T[]) : []; + }, + }; +} + +function mockSdk() { + const functions = new Map(); + const triggerCalls: Array<{ function_id: string; payload: unknown }> = []; + const triggerOverrides = new Map(); + return { + triggerCalls, + registerFunction: (idOrOpts: string | { id: string }, handler: Function) => { + const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id; + functions.set(id, handler); + }, + registerTrigger: () => {}, + trigger: async ( + idOrInput: string | { function_id: string; payload: unknown }, + data?: unknown, + ) => { + const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id; + const payload = typeof idOrInput === "string" ? data : idOrInput.payload; + triggerCalls.push({ function_id: id, payload }); + if (triggerOverrides.has(id)) return triggerOverrides.get(id)!(payload); + return { success: true, id, payload }; + }, + overrideTrigger: (id: string, handler: Function) => { + triggerOverrides.set(id, handler); + }, + getFunction: (id: string) => functions.get(id), + }; +} + +function makeReq(name: string, args: Record) { + return { + body: { name, arguments: args }, + headers: {}, + query_params: {}, + }; +} + +describe("MCP tools call dispatch", () => { + let sdk: ReturnType; + let kv: ReturnType; + + beforeEach(() => { + sdk = mockSdk(); + kv = mockKV(); + registerMcpEndpoints(sdk as never, kv as never); + }); + + it("honors operation as a memory_search scope alias", async () => { + const fn = sdk.getFunction("mcp::tools::call")!; + const result = await fn(makeReq("memory_search", { operation: "semantic", query: "auth", limit: "5" })); + + expect(result.status_code).toBe(200); + expect(sdk.triggerCalls.at(-1)).toEqual({ + function_id: "mem::smart-search", + payload: { query: "auth", expandIds: [], limit: 5 }, + }); + }); + + it("dispatches crystal list without requiring actionIds", async () => { + const fn = sdk.getFunction("mcp::tools::call")!; + const result = await fn(makeReq("crystal", { operation: "list", project: "app", limit: "3" })); + + expect(result.status_code).toBe(200); + expect(sdk.triggerCalls.at(-1)).toEqual({ + function_id: "mem::crystal-list", + payload: { project: "app", sessionId: undefined, limit: 3 }, + }); + }); + + it("normalizes bulk insightIds for insight delete", async () => { + const fn = sdk.getFunction("mcp::tools::call")!; + const result = await fn(makeReq("insight", { operation: "delete", insightIds: "ins_1, ins_2", reason: "cleanup" })); + + expect(result.status_code).toBe(200); + expect(sdk.triggerCalls.slice(-2)).toEqual([ + { function_id: "mem::insight-delete", payload: { insightId: "ins_1", reason: "cleanup" } }, + { function_id: "mem::insight-delete", payload: { insightId: "ins_2", reason: "cleanup" } }, + ]); + }); + + it("passes operation_filter to audit query", async () => { + const fn = sdk.getFunction("mcp::tools::call")!; + const result = await fn(makeReq("admin", { operation: "audit", operation_filter: "delete", limit: 7 })); + + expect(result.status_code).toBe(200); + expect(sdk.triggerCalls.at(-1)).toEqual({ + function_id: "mem::audit-query", + payload: { operation: "delete", limit: 7 }, + }); + }); + + it("validates lesson list and trims strengthen IDs", async () => { + const fn = sdk.getFunction("mcp::tools::call")!; + const badSource = await fn(makeReq("lesson", { operation: "list", source: "bogus" })); + expect(badSource.status_code).toBe(400); + + const strengthened = await fn(makeReq("lesson", { operation: "strengthen", lessonId: " les_1 " })); + expect(strengthened.status_code).toBe(200); + expect(sdk.triggerCalls.at(-1)).toEqual({ + function_id: "mem::lesson-strengthen", + payload: { lessonId: "les_1" }, + }); + }); + + it("does not globally require query for memory_search schema or title for sketch schema", () => { + const tools = getAllTools(); + expect(tools.find((t) => t.name === "memory_search")!.inputSchema.required).toBeUndefined(); + expect(tools.find((t) => t.name === "sketch")!.inputSchema.required).toEqual(["operation"]); + }); +}); From 3f77267aa607974b2f5584b5d7e7689e930a691c Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 19:10:08 -0400 Subject: [PATCH 23/24] fix(governance): batch stale cascade --- src/functions/governance.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/functions/governance.ts b/src/functions/governance.ts index f154f13d5e..e563489839 100644 --- a/src/functions/governance.ts +++ b/src/functions/governance.ts @@ -6,14 +6,17 @@ import { recordAudit, safeAudit, queryAudit } from "./audit.js"; import { deleteAccessLog } from "./access-tracker.js"; import { logger } from "../logger.js"; -async function cascadeStale(kv: StateKV, memoryId: string): Promise { +async function cascadeStale(kv: StateKV, memoryIds: Iterable): Promise { + const deletedIds = new Set(memoryIds); + if (deletedIds.size === 0) return; + const now = new Date().toISOString(); const nodes = await kv.list(KV.graphNodes); const edges = await kv.list(KV.graphEdges); const nodeUpdates: Promise[] = []; for (const node of nodes) { - if (!node.stale && node.sourceObservationIds.includes(memoryId)) { + if (!node.stale && node.sourceObservationIds.some((id) => deletedIds.has(id))) { node.stale = true; node.updatedAt = now; nodeUpdates.push(kv.set(KV.graphNodes, node.id, node)); @@ -22,7 +25,7 @@ async function cascadeStale(kv: StateKV, memoryId: string): Promise { const edgeUpdates: Promise[] = []; for (const edge of edges) { - if (!edge.stale && edge.sourceObservationIds.includes(memoryId)) { + if (!edge.stale && edge.sourceObservationIds.some((id) => deletedIds.has(id))) { edge.stale = true; edge.updatedAt = now; edgeUpdates.push(kv.set(KV.graphEdges, edge.id, edge)); @@ -52,7 +55,7 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { mem.updatedAt = opTimestamp; await kv.set(KV.memories, id, mem); await deleteAccessLog(kv, id); - await cascadeStale(kv, id); + await cascadeStale(kv, [id]); deleted++; } } @@ -141,14 +144,15 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { mem.updatedAt = opTimestamp; await kv.set(KV.memories, mem.id, mem); await deleteAccessLog(kv, mem.id); - await cascadeStale(kv, mem.id); return "deleted"; }), ); + const deletedIds = new Set(); results.forEach((result, j) => { const mem = batch[j]; if (result.status === "fulfilled" && result.value === "deleted") { successfulIds.push(mem.id); + deletedIds.add(mem.id); } else if (result.status === "fulfilled") { return; } else { @@ -165,6 +169,7 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { }); } }); + await cascadeStale(kv, deletedIds); } await safeAudit( From fb1c4b5e76525a2e5f9bf51c2e8d3a24b718be4e Mon Sep 17 00:00:00 2001 From: Trip <5579540+cl0ckt0wer@users.noreply.github.com> Date: Sat, 16 May 2026 21:52:36 -0400 Subject: [PATCH 24/24] fix(mcp): pin shim version --- packages/mcp/package.json | 2 +- plugin/.mcp.json | 2 +- src/cli/connect/claude-code.ts | 2 +- src/cli/connect/codex.ts | 2 +- src/cli/connect/json-mcp-adapter.ts | 2 +- src/cli/connect/util.ts | 2 +- test/cli-connect.test.ts | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 6921719ffc..bf4af268ef 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -28,7 +28,7 @@ "homepage": "https://github.com/rohitg00/agentmemory#readme", "bugs": "https://github.com/rohitg00/agentmemory/issues", "dependencies": { - "@agentmemory/agentmemory": "~0.9.0" + "@agentmemory/agentmemory": "0.9.17" }, "publishConfig": { "access": "public", diff --git a/plugin/.mcp.json b/plugin/.mcp.json index 12702a2a5a..f374a54a97 100644 --- a/plugin/.mcp.json +++ b/plugin/.mcp.json @@ -2,7 +2,7 @@ "mcpServers": { "agentmemory": { "command": "npx", - "args": ["-y", "@agentmemory/mcp"] + "args": ["-y", "@agentmemory/mcp@0.9.17"] } } } diff --git a/src/cli/connect/claude-code.ts b/src/cli/connect/claude-code.ts index 9f196e7c3e..d3b7097e3d 100644 --- a/src/cli/connect/claude-code.ts +++ b/src/cli/connect/claude-code.ts @@ -27,7 +27,7 @@ function entryMatches(entry: unknown): boolean { const e = entry as Record; if (e["command"] !== "npx") return false; const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; - return args.includes("@agentmemory/mcp"); + return args.some((arg) => arg === "@agentmemory/mcp" || arg.startsWith("@agentmemory/mcp@")); } export const adapter: ConnectAdapter = { diff --git a/src/cli/connect/codex.ts b/src/cli/connect/codex.ts index 003dc99a9b..6466330f78 100644 --- a/src/cli/connect/codex.ts +++ b/src/cli/connect/codex.ts @@ -15,7 +15,7 @@ const CODEX_TOML = join(CODEX_DIR, "config.toml"); const TOML_BLOCK = `[mcp_servers.agentmemory] command = "npx" -args = ["-y", "@agentmemory/mcp"] +args = ["-y", "@agentmemory/mcp@0.9.17"] [mcp_servers.agentmemory.env] AGENTMEMORY_URL = "http://localhost:3111" diff --git a/src/cli/connect/json-mcp-adapter.ts b/src/cli/connect/json-mcp-adapter.ts index d72eb45cf5..bb0e5957a6 100644 --- a/src/cli/connect/json-mcp-adapter.ts +++ b/src/cli/connect/json-mcp-adapter.ts @@ -32,7 +32,7 @@ function entryMatches(entry: unknown): boolean { const e = entry as Record; if (e["command"] !== "npx") return false; const args = Array.isArray(e["args"]) ? (e["args"] as string[]) : []; - return args.includes("@agentmemory/mcp"); + return args.some((arg) => arg === "@agentmemory/mcp" || arg.startsWith("@agentmemory/mcp@")); } export function createJsonMcpAdapter( diff --git a/src/cli/connect/util.ts b/src/cli/connect/util.ts index ce9110c655..dd7cb75751 100644 --- a/src/cli/connect/util.ts +++ b/src/cli/connect/util.ts @@ -12,7 +12,7 @@ import * as p from "@clack/prompts"; export const AGENTMEMORY_MCP_BLOCK = { command: "npx", - args: ["-y", "@agentmemory/mcp"], + args: ["-y", "@agentmemory/mcp@0.9.17"], env: { AGENTMEMORY_URL: "http://localhost:3111", }, diff --git a/test/cli-connect.test.ts b/test/cli-connect.test.ts index 4a6c0227ee..4889a5ca6a 100644 --- a/test/cli-connect.test.ts +++ b/test/cli-connect.test.ts @@ -105,7 +105,7 @@ describe("agentmemory connect — claude-code adapter (mock filesystem)", () => const config = JSON.parse(readFileSync(join(tmpHome, ".claude.json"), "utf-8")); expect(config.mcpServers.agentmemory.command).toBe("npx"); - expect(config.mcpServers.agentmemory.args).toContain("@agentmemory/mcp"); + expect(config.mcpServers.agentmemory.args).toContain("@agentmemory/mcp@0.9.17"); expect(config.mcpServers.other.command).toBe("x"); const second = await a.install({ dryRun: false, force: false });