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/AGENTS.md b/AGENTS.md index ebcf35844b..a00d9331c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,9 +109,9 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). - Test files go in `test/` with `.test.ts` extension - Follow existing patterns in `test/crystallize.test.ts` for function tests -## Current Stats (v0.9.16) +## Current Stats (v0.9.21) -- 53 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all) +- 15 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all) - 124 REST endpoints - 6 MCP resources, 3 MCP prompts - 12 hooks, 4 skills diff --git a/README.md b/README.md index e84183b61c..1da2ef3e3a 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@

95.2% retrieval R@5 92% fewer tokens - 53 MCP tools + 15 MCP tools 12 auto hooks 0 external DBs 950+ tests passing @@ -412,7 +412,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 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. +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 15 consolidated MCP tools (memory_search, memory_store, memory_profile, task, task_plan, signal, checkpoint, sketch, memory_commit_lookup, memory_commits, crystal, lesson, insight, slot, admin) with operation sub-dispatch — plus backward-compatible aliases for legacy tool names. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. ``` #### Claude Code without the plugin install (MCP-standalone path) @@ -441,8 +441,8 @@ codex plugin add agentmemory@agentmemory The Codex plugin ships from the same `plugin/` directory as the Claude Code plugin. It registers: -- `@agentmemory/mcp` as an MCP server (proxies all 51 tools when `AGENTMEMORY_URL` points at a running agentmemory server; falls back to 7 tools locally when no server is reachable) -- 6 lifecycle hooks: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PreCompact`, `Stop` +- `@agentmemory/mcp` as an MCP server (13 consolidated tools when `AGENTMEMORY_TOOLS=all`, plus backward-compatible legacy aliases) +- 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. @@ -459,11 +459,13 @@ agentmemory connect codex --with-hooks This adds an idempotent block to `~/.codex/hooks.json` referencing absolute paths to the bundled scripts (no `${CLAUDE_PLUGIN_ROOT}` expansion needed at user-scope). Re-run the same command after upgrading agentmemory to refresh paths. User entries in the same file are preserved; only previous agentmemory entries are replaced. +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) ``` -Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 51 memory tools: +Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with the 13 consolidated memory tools: { "mcpServers": { @@ -488,7 +490,7 @@ Full guide: [`integrations/openclaw/`](integrations/openclaw/) Hermes Agent (paste this prompt) ``` -Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 51 memory tools: +Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with the 13 consolidated memory tools: mcp_servers: agentmemory: @@ -816,11 +818,11 @@ npm install @xenova/transformers

MCP Server

-53 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent. +15 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent. -> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 51-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag — setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`. +> **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 15-tool consolidated surface when it can reach a running agentmemory server via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a minimal local set (`memory_search`, `memory_store`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag — setting it in the shim's `env` block has no effect. If you see only the local fallback tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`. -### 51 Tools +### Consolidated Tools
Core tools (always available) @@ -842,7 +844,7 @@ npm install @xenova/transformers
-Extended tools (51 total — set AGENTMEMORY_TOOLS=all) +Extended operations and legacy aliases — set AGENTMEMORY_TOOLS=all | Tool | Description | |------|-------------| @@ -1233,7 +1235,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" (15 tools) # AGENTMEMORY_TOOLS=core ``` diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 96da3ae478..9c69f2eda9 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.21" }, "publishConfig": { "access": "public", diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index e53f8088d2..bcea9be137 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agentmemory", "version": "0.9.21", - "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, 15 MCP tools, 4 skills, real-time viewer.", "author": { "name": "Rohit Ghumare", "url": "https://github.com/rohitg00" diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index 0a7cc17357..45c767ebfd 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agentmemory", "version": "0.9.21", - "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, 15 MCP tools, 4 skills, real-time viewer.", "author": { "name": "Rohit Ghumare", "url": "https://github.com/rohitg00" diff --git a/plugin/.mcp.json b/plugin/.mcp.json index f7c3760336..8a6acb0972 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.21"], "env": { "AGENTMEMORY_URL": "${AGENTMEMORY_URL}", "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET}" diff --git a/plugin/hooks/hooks.codex.json b/plugin/hooks/hooks.codex.json index d2c3a3b6da..eef79d06f8 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 60f5e5bb94..454fb31576 100644 --- a/plugin/opencode/README.md +++ b/plugin/opencode/README.md @@ -9,7 +9,7 @@

- 53 MCP tools + 15 MCP tools 22 hooks 2 slash commands 95.2% R@5 @@ -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 ``` @@ -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..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", {}); } } @@ -253,8 +259,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 +641,10 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => { output.context.push(ctx); } } + + if (process.env["CONSOLIDATION_ENABLED"] === "true") { + post("/crystals/auto", { olderThanDays: 0 }, 30000); + } }, // ── config ── diff --git a/plugin/opencode/plugin.json b/plugin/opencode/plugin.json index 1472752e93..2a63e0cf27 100644 --- a/plugin/opencode/plugin.json +++ b/plugin/opencode/plugin.json @@ -1,7 +1,7 @@ { "name": "agentmemory-capture", "version": "0.9.20", - "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.", + "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, 15 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..6ab12b64e1 --- /dev/null +++ b/plugin/scripts/post-compact.mjs @@ -0,0 +1,65 @@ +#!/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 { + const response = await fetch(`${REST_URL}/agentmemory${path}`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs) + }); + 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 = ""; + for await (const chunk of process.stdin) input += chunk; + let data; + try { + data = JSON.parse(input); + } catch { + return; + } + if (isSdkChildContext(data)) return; + 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", + 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/cli.ts b/src/cli.ts index e1ea975754..82bfe0a96b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -215,7 +215,7 @@ export async function discoverViewerPort(): Promise { function getViewerUrl(): string { const envUrl = process.env["AGENTMEMORY_VIEWER_URL"]; if (envUrl) return envUrl.replace(/\/+$/, ""); - + if (discoveredViewerPort !== null) { try { const u = new URL(getBaseUrl()); @@ -224,7 +224,7 @@ function getViewerUrl(): string { return `http://localhost:${discoveredViewerPort}`; } } - + try { const u = new URL(getBaseUrl()); const vPort = diff --git a/src/cli/connect/claude-code.ts b/src/cli/connect/claude-code.ts index 76df149203..cd291ded6b 100644 --- a/src/cli/connect/claude-code.ts +++ b/src/cli/connect/claude-code.ts @@ -33,7 +33,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 c85808da68..d38908bb2e 100644 --- a/src/cli/connect/codex.ts +++ b/src/cli/connect/codex.ts @@ -23,7 +23,7 @@ const CODEX_HOOKS = join(CODEX_DIR, "hooks.json"); const TOML_BLOCK = `[mcp_servers.agentmemory] command = "npx" -args = ["-y", "@agentmemory/mcp"] +args = ["-y", "@agentmemory/mcp@0.9.21"] [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 6d5f61ac98..820fed86cc 100644 --- a/src/cli/connect/util.ts +++ b/src/cli/connect/util.ts @@ -19,7 +19,7 @@ import * as p from "@clack/prompts"; // without doctor-warning duplicates (#375). export const AGENTMEMORY_MCP_BLOCK = { command: "npx", - args: ["-y", "@agentmemory/mcp"], + args: ["-y", "@agentmemory/mcp@0.9.21"], env: { AGENTMEMORY_URL: "${AGENTMEMORY_URL}", AGENTMEMORY_SECRET: "${AGENTMEMORY_SECRET}", diff --git a/src/config.ts b/src/config.ts index eed5725ef1..a17ff7e30c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -93,7 +93,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, }; } @@ -286,6 +286,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/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/governance.ts b/src/functions/governance.ts index 60813dd4cb..e563489839 100644 --- a/src/functions/governance.ts +++ b/src/functions/governance.ts @@ -1,13 +1,42 @@ 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, 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.some((id) => deletedIds.has(id))) { + 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.some((id) => deletedIds.has(id))) { + edge.stale = true; + edge.updatedAt = now; + 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 || @@ -18,11 +47,15 @@ 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) { - await kv.delete(KV.memories, id); + if (mem && !mem.deleted) { + mem.deleted = true; + mem.updatedAt = opTimestamp; + await kv.set(KV.memories, id, mem); await deleteAccessLog(kv, id); + await cascadeStale(kv, [id]); deleted++; } } @@ -101,18 +134,27 @@ 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) => { - await kv.delete(KV.memories, mem.id); + if (mem.deleted) return "skipped"; + mem.deleted = true; + mem.updatedAt = opTimestamp; + await kv.set(KV.memories, mem.id, mem); await deleteAccessLog(kv, mem.id); + return "deleted"; }), ); + const deletedIds = new Set(); results.forEach((result, j) => { const mem = batch[j]; - if (result.status === "fulfilled") { + if (result.status === "fulfilled" && result.value === "deleted") { successfulIds.push(mem.id); + deletedIds.add(mem.id); + } else if (result.status === "fulfilled") { + return; } else { logger.warn("Governance bulk delete failed", { memoryId: mem.id, @@ -127,6 +169,7 @@ export function registerGovernanceFunction(sdk: ISdk, kv: StateKV): void { }); } }); + await cascadeStale(kv, deletedIds); } await safeAudit( diff --git a/src/functions/lessons.ts b/src/functions/lessons.ts index 9e69f464fd..03a5f4d49d 100644 --- a/src/functions/lessons.ts +++ b/src/functions/lessons.ts @@ -174,6 +174,17 @@ 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: lessonIds.length, + totalMatched: lessons.length, + }); + } catch {} + return { success: true, lessons: lessons.slice(0, limit) }; }, ); diff --git a/src/functions/reflect.ts b/src/functions/reflect.ts index 3a2af82934..4280d6bdcf 100644 --- a/src/functions/reflect.ts +++ b/src/functions/reflect.ts @@ -474,4 +474,42 @@ 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 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" }; + } + const now = new Date().toISOString(); + 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; + 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, + }); + return { success: true, deleted, total: ids.length }; + }, + ); } diff --git a/src/functions/search.ts b/src/functions/search.ts index b4444b48e4..15d4437f8a 100644 --- a/src/functions/search.ts +++ b/src/functions/search.ts @@ -220,6 +220,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)) await enqueue({ id: memory.id, @@ -366,6 +367,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/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..13ae42c929 --- /dev/null +++ b/src/hooks/post-compact.ts @@ -0,0 +1,79 @@ +#!/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 { + const response = await fetch(`${REST_URL}/agentmemory${path}`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + 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 = ""; + 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 = 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", { + 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/src/index.ts b/src/index.ts index 704d480932..f143732a9d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -60,6 +60,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"; @@ -274,6 +275,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/mcp/rest-proxy.ts b/src/mcp/rest-proxy.ts index 1adbb46e83..74a693b1ab 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"]; @@ -137,6 +160,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 b3b0585d4a..a7e23f16f4 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,980 +77,603 @@ 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 => { const authErr = checkAuth(req, secret); if (authErr) return authErr; - 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, + 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_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) || (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" } }; + } + 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": { + 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" } }; } 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 "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 = 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") { + 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 } }); + return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } }; + } + return { status_code: 400, body: { error: "Invalid operation" } }; } - 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 "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") { + 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 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" } }; } - 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 "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 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 } }; + } + } + 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,155 +683,45 @@ 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_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" } }; + 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 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) }] }, - }; + case "memory_reflect": { + 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) }] } }; } case "memory_commit_lookup": { @@ -1242,18 +762,10 @@ export function registerMcpEndpoints( } 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" } }; } }, ); @@ -1303,7 +815,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; @@ -1316,7 +828,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; @@ -1589,7 +1101,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; @@ -1602,7 +1114,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 => { diff --git a/src/mcp/standalone.ts b/src/mcp/standalone.ts index f4683747f0..b7c72575c6 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 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 = { @@ -94,6 +152,7 @@ function textResponse(payload: unknown, pretty = false): { interface Validated { tool: string; + operation?: string; content?: string; type?: string; concepts?: string[]; @@ -104,33 +163,26 @@ interface Validated { tokenBudget?: 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"; const fmt = args["format"]; if (typeof fmt === "string" && fmt.trim()) { v.format = fmt.trim().toLowerCase(); @@ -144,8 +196,23 @@ function validate(toolName: string, args: Record): Validated { } 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": { @@ -155,14 +222,86 @@ function validate(toolName: string, args: Record): Validated { v.reason = (args["reason"] as string) || "plugin skill request"; return v; } - case "memory_export": - return v; case "memory_audit": { + v.operation = "audit"; v.limit = parseLimit(args["limit"], 50); return v; } - default: + case "memory_profile": { + v.operation = "profile"; + return v; + } + case "memory_sessions": { + v.operation = "sessions"; + v.limit = parseLimit(args["limit"], 20); + return v; + } + 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_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: { throw new Error(`Unknown tool: ${toolName}`); + } } } @@ -170,47 +309,53 @@ 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_recall": { + case "memory_search": + case "memory_recall": + case "memory_smart_search": { + const scope = v.tool === "memory_recall" + ? "recall" + : v.tool === "memory_smart_search" + ? "smart_search" + : 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 body: Record = { query: v.query, limit: v.limit, - format: v.format ?? "full", }; + if (v.tool === "memory_recall") body["format"] = v.format ?? "full"; + else if (v.format != null) body["format"] = v.format; if (v.tokenBudget != null) body["token_budget"] = v.tokenBudget; - const result = await handle.call("/agentmemory/search", { + const result = await handle.call(ep, { method: "POST", body: JSON.stringify(body), }); return textResponse(result, true); } - case "memory_smart_search": { - const body: Record = { query: v.query, limit: v.limit }; - if (v.format != null) body["format"] = v.format; - if (v.tokenBudget != null) body["token_budget"] = v.tokenBudget; - const result = await handle.call("/agentmemory/smart-search", { - method: "POST", - body: JSON.stringify(body), - }); + 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_profile": { + const result = await handle.call("/agentmemory/profile?project=" + encodeURIComponent(v.query || ""), { method: "GET" }); return textResponse(result, true); } case "memory_sessions": { - const result = await handle.call( - `/agentmemory/sessions?limit=${v.limit}`, - { method: "GET" }, - ); + const result = await handle.call("/agentmemory/sessions?limit=" + (v.limit ?? 20), { method: "GET" }); return textResponse(result, true); } case "memory_governance_delete": { @@ -232,7 +377,7 @@ async function handleProxy( return textResponse(result, true); } default: - throw new Error(`Unknown tool: ${v.tool}`); + throw new Error(`Proxy not implemented for: ${v.tool}`); } } @@ -241,64 +386,51 @@ 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_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 }); + } + throw new Error(`Unsupported operation: ${v.operation}`); + } + case "memory_profile": { + throw new Error("memory_profile not implemented in standalone local mode"); + } case "memory_sessions": { - const sessions = - await kvInstance.list>("mem:sessions"); - const limit = v.limit ?? 20; - return textResponse({ sessions: sessions.slice(0, limit) }, true); + const sessions = await kvInstance.list>("mem:sessions"); + return textResponse({ sessions: sessions.slice(0, (v.limit ?? 20) as number) }, true); } - 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++; } } @@ -309,26 +441,22 @@ async function handleLocal( reason: v.reason, }); } - 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_audit": { const entries = await kvInstance.list("mem:audit"); const limit = v.limit ?? 50; return textResponse( - { - entries: (entries as Array>).slice(0, limit), - }, + { entries: (entries as Array>).slice(0, limit) }, true, ); } - - default: + default: { throw new Error(`Unknown tool: ${v.tool}`); + } } } @@ -338,8 +466,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 15 consolidated tools (lessons, sentinels, slots, signals, graph, …) + // instead of being capped at the IMPLEMENTED_TOOLS set baked into // this shim. The server validates arguments per tool. const result = (await handle.call("/agentmemory/mcp/call", { method: "POST", @@ -380,14 +508,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); @@ -435,7 +576,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 3001cae75d..42eb1bc1f9 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -10,934 +10,328 @@ 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", + description: "save, compress_file, export, consolidate, claude_bridge, mesh_sync", }, - project: { type: "string", description: "Filter by project path" }, - before: { - type: "number", - description: "Observations before anchor (default 5)", - }, - 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"], - }, - }, - { - name: "memory_commit_lookup", - description: - "Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.", - inputSchema: { - type: "object", - properties: { - sha: { type: "string", description: "Full git commit SHA" }, - }, - required: ["sha"], - }, - }, - { - name: "memory_commits", - description: - "List recent commits linked to agent sessions, optionally filtered by branch or repo.", - inputSchema: { - type: "object", - properties: { - branch: { type: "string", description: "Filter by branch name" }, - repo: { type: "string", description: "Filter by remote URL" }, - limit: { type: "number", description: "Max results (default 100, max 500)" }, - }, - }, - }, -]; - -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)", - }, }, + required: ["operation"], }, }, { - name: "memory_facet_tag", + name: "memory_commit_lookup", description: - "Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.", + "Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.", 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)" }, + sha: { type: "string", description: "Full git commit SHA" }, }, - required: ["targetId", "targetType", "dimension", "value"], + required: ["sha"], }, }, { - name: "memory_facet_query", + name: "memory_commits", description: - "Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.", + "List recent commits linked to agent sessions, optionally filtered by branch or repo.", 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", - }, + branch: { type: "string", description: "Filter by branch name" }, + repo: { type: "string", description: "Filter by remote URL" }, + limit: { type: "number", description: "Max results (default 100, max 500)" }, }, }, }, ]; -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_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, ]; } diff --git a/src/prompts/action-suggest.ts b/src/prompts/action-suggest.ts new file mode 100644 index 0000000000..681990d75f --- /dev/null +++ b/src/prompts/action-suggest.ts @@ -0,0 +1,58 @@ +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_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_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 = (attrs.get("description") ?? "").trim(); + if (title && description) { + actions.push({ title, priority, description }); + } + } + return actions; +} diff --git a/src/providers/openai.ts b/src/providers/openai.ts index 88e1082972..445b95b474 100644 --- a/src/providers/openai.ts +++ b/src/providers/openai.ts @@ -146,7 +146,6 @@ export class OpenAIProvider implements MemoryProvider { ); } } - // Resolves the outbound-fetch timeout for the OpenAI LLM path. // Precedence (preserving v0.9.17 behaviour): // 1. OPENAI_TIMEOUT_MS — OpenAI-scoped alias (back-compat) @@ -175,4 +174,3 @@ function parsePositiveInt(raw: string | null | undefined): number | undefined { const n = Number(trimmed); return Number.isFinite(n) && n > 0 ? n : undefined; } - diff --git a/src/types.ts b/src/types.ts index 72e347b348..96b3eebcab 100644 --- a/src/types.ts +++ b/src/types.ts @@ -98,6 +98,7 @@ export interface Memory { forgetAfter?: string; imageRef?: string; imageData?: string; + deleted?: boolean; } export interface SessionSummary { @@ -513,6 +514,7 @@ export interface AuditEntry { | "export" | "action_create" | "action_update" + | "action_suggest" | "lease_acquire" | "lease_release" | "routine_run" @@ -534,6 +536,7 @@ export interface AuditEntry { | "lesson_save" | "lesson_recall" | "lesson_strengthen" + | "lesson_list" | "obsidian_export" | "reflect" | "insight_search" diff --git a/src/viewer/index.html b/src/viewer/index.html index a4a3561cd7..e09bd1fc65 100644 --- a/src/viewer/index.html +++ b/src/viewer/index.html @@ -2235,7 +2235,7 @@

agentmemory

const normalizedSearch = (search || '') .normalize("NFKC") .toLowerCase(); - + const normalizedTitle = (m.title || '') .normalize("NFKC") .toLowerCase(); diff --git a/test/action-suggest.test.ts b/test/action-suggest.test.ts new file mode 100644 index 0000000000..492c9e4a8c --- /dev/null +++ b/test/action-suggest.test.ts @@ -0,0 +1,389 @@ +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 { parseActionSuggestXml } from "../src/prompts/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("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", + 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); + }); +}); 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/cli-connect.test.ts b/test/cli-connect.test.ts index 99174dacbc..d843d59adc 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.21"); expect(config.mcpServers.other.command).toBe("x"); const second = await a.install({ dryRun: false, force: false }); diff --git a/test/codex-plugin.test.ts b/test/codex-plugin.test.ts index 63aa1803fa..f0b5451f0d 100644 --- a/test/codex-plugin.test.ts +++ b/test/codex-plugin.test.ts @@ -108,10 +108,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", () => { const hooks = readJson<{ hooks: Record }>( join(pluginRoot, "hooks/hooks.codex.json"), 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"]; }); diff --git a/test/fetch-timeout.test.ts b/test/fetch-timeout.test.ts index 58cd211195..30413a6905 100644 --- a/test/fetch-timeout.test.ts +++ b/test/fetch-timeout.test.ts @@ -73,7 +73,6 @@ describe("fetchWithTimeout", () => { return p; }); }); - // ───────────────────────────────────────────────────────────── // Provider hang regression tests // Each provider must call fetchWithTimeout, which honours the @@ -275,4 +274,3 @@ describe("OpenAIProvider timeout env precedence (#446)", () => { } }); }); - 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"); + }); }); diff --git a/test/mcp-standalone-proxy.test.ts b/test/mcp-standalone-proxy.test.ts index dc08a024ee..bc734b131e 100644 --- a/test/mcp-standalone-proxy.test.ts +++ b/test/mcp-standalone-proxy.test.ts @@ -348,20 +348,18 @@ 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 Array<{ name: string }>).map((t) => t.name).sort()).toEqual([ + "memory_search", + "memory_store", + ]); delete process.env["AGENTMEMORY_TOOLS"]; }); diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts index b48eade966..ee82caf373 100644 --- a/test/mcp-standalone.test.ts +++ b/test/mcp-standalone.test.ts @@ -53,27 +53,34 @@ const fetchTrap = vi.fn(async (url: unknown) => { 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 14 items", () => { - expect(CORE_TOOLS.length).toBe(14); + it("CORE_TOOLS has 10 items", () => { + expect(CORE_TOOLS.length).toBe(10); }); - 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", () => { @@ -89,6 +96,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", () => { @@ -169,11 +189,11 @@ describe("handleToolCall", () => { expect(fetchTrap).not.toHaveBeenCalled(); }); - 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); @@ -185,35 +205,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, ); @@ -222,11 +241,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"], @@ -242,11 +262,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", @@ -262,20 +283,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, ); @@ -284,38 +305,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, ) @@ -324,11 +345,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, ) @@ -357,96 +377,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"); }); }); 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"]); + }); +}); diff --git a/tsdown.config.ts b/tsdown.config.ts index 4475609a42..fe932a4d65 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", diff --git a/website/lib/generated-meta.json b/website/lib/generated-meta.json index 14ed7113ee..b07a45ed28 100644 --- a/website/lib/generated-meta.json +++ b/website/lib/generated-meta.json @@ -1,6 +1,6 @@ { "version": "0.9.20", - "mcpTools": 53, + "mcpTools": 15, "hooks": 12, "restEndpoints": 124, "testsPassing": 1055,