@agentmemory/agentmemory 0.9.28 → 0.9.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/.env.example +15 -6
  2. package/AGENTS.md +6 -6
  3. package/README.md +220 -152
  4. package/dist/.env.example +15 -6
  5. package/dist/cli.d.mts.map +1 -1
  6. package/dist/cli.mjs +233 -35
  7. package/dist/cli.mjs.map +1 -1
  8. package/dist/{connect-JnsJXc68.mjs → connect-Qaeq15TQ.mjs} +599 -41
  9. package/dist/connect-Qaeq15TQ.mjs.map +1 -0
  10. package/dist/docker-compose.yml +2 -2
  11. package/dist/hooks/antigravity-bridge.d.mts +8 -0
  12. package/dist/hooks/antigravity-bridge.d.mts.map +1 -0
  13. package/dist/hooks/antigravity-bridge.mjs +114 -0
  14. package/dist/hooks/antigravity-bridge.mjs.map +1 -0
  15. package/dist/hooks/notification.mjs +19 -4
  16. package/dist/hooks/notification.mjs.map +1 -1
  17. package/dist/hooks/post-commit.mjs +13 -1
  18. package/dist/hooks/post-commit.mjs.map +1 -1
  19. package/dist/hooks/post-tool-failure.mjs +14 -3
  20. package/dist/hooks/post-tool-failure.mjs.map +1 -1
  21. package/dist/hooks/post-tool-use.mjs +14 -3
  22. package/dist/hooks/post-tool-use.mjs.map +1 -1
  23. package/dist/hooks/pre-compact.mjs +12 -2
  24. package/dist/hooks/pre-compact.mjs.map +1 -1
  25. package/dist/hooks/pre-tool-use.mjs +1 -1
  26. package/dist/hooks/pre-tool-use.mjs.map +1 -1
  27. package/dist/hooks/prompt-submit.mjs +14 -3
  28. package/dist/hooks/prompt-submit.mjs.map +1 -1
  29. package/dist/hooks/session-end.mjs +82 -18
  30. package/dist/hooks/session-end.mjs.map +1 -1
  31. package/dist/hooks/session-start.mjs +22 -4
  32. package/dist/hooks/session-start.mjs.map +1 -1
  33. package/dist/hooks/stop.mjs +1 -7
  34. package/dist/hooks/stop.mjs.map +1 -1
  35. package/dist/hooks/subagent-start.mjs +14 -3
  36. package/dist/hooks/subagent-start.mjs.map +1 -1
  37. package/dist/hooks/subagent-stop.mjs +14 -3
  38. package/dist/hooks/subagent-stop.mjs.map +1 -1
  39. package/dist/hooks/task-completed.mjs +14 -3
  40. package/dist/hooks/task-completed.mjs.map +1 -1
  41. package/dist/{image-refs-C2YU7BIm.mjs → image-refs-CJgZmb9X.mjs} +2 -2
  42. package/dist/{image-refs-C2YU7BIm.mjs.map → image-refs-CJgZmb9X.mjs.map} +1 -1
  43. package/dist/index.mjs +1557 -755
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/schema-BFZhNTF7.mjs +197 -0
  46. package/dist/schema-BFZhNTF7.mjs.map +1 -0
  47. package/dist/{src-CzgoepGU.mjs → src-G7yt8gGm.mjs} +1531 -883
  48. package/dist/src-G7yt8gGm.mjs.map +1 -0
  49. package/dist/{standalone-YsZFFQBM.mjs → standalone-BqNJDJ04.mjs} +26 -15
  50. package/dist/standalone-BqNJDJ04.mjs.map +1 -0
  51. package/dist/standalone.d.mts.map +1 -1
  52. package/dist/standalone.mjs +50 -14
  53. package/dist/standalone.mjs.map +1 -1
  54. package/dist/{tools-registry-D3NEoe5m.mjs → tools-registry-BV_2bu7z.mjs} +293 -3
  55. package/dist/tools-registry-BV_2bu7z.mjs.map +1 -0
  56. package/dist/viewer/favicon.svg +35 -1
  57. package/dist/viewer/index.html +473 -83
  58. package/docker-compose.yml +2 -2
  59. package/integrations/pi/README.md +77 -0
  60. package/integrations/pi/index.ts +403 -0
  61. package/integrations/pi/package.json +32 -0
  62. package/integrations/pi/security.ts +35 -0
  63. package/package.json +3 -4
  64. package/plugin/.claude-plugin/plugin.json +2 -2
  65. package/plugin/.codex-plugin/plugin.json +2 -2
  66. package/plugin/.devin-plugin/plugin.json +32 -0
  67. package/plugin/cursor/hooks.json +41 -0
  68. package/plugin/cursor/mcp.json +12 -0
  69. package/plugin/hooks/hooks.antigravity.json +43 -0
  70. package/plugin/hooks/hooks.devin.json +67 -0
  71. package/plugin/hooks/hooks.droid.json +55 -0
  72. package/plugin/opencode/README.md +1 -1
  73. package/plugin/opencode/agentmemory-capture.ts +73 -13
  74. package/plugin/opencode/plugin.json +1 -1
  75. package/plugin/plugin.json +2 -2
  76. package/plugin/scripts/antigravity-bridge.d.mts +8 -0
  77. package/plugin/scripts/antigravity-bridge.d.mts.map +1 -0
  78. package/plugin/scripts/antigravity-bridge.mjs +114 -0
  79. package/plugin/scripts/antigravity-bridge.mjs.map +1 -0
  80. package/plugin/scripts/notification.mjs +19 -4
  81. package/plugin/scripts/notification.mjs.map +1 -1
  82. package/plugin/scripts/post-commit.mjs +13 -1
  83. package/plugin/scripts/post-commit.mjs.map +1 -1
  84. package/plugin/scripts/post-tool-failure.mjs +14 -3
  85. package/plugin/scripts/post-tool-failure.mjs.map +1 -1
  86. package/plugin/scripts/post-tool-use.mjs +14 -3
  87. package/plugin/scripts/post-tool-use.mjs.map +1 -1
  88. package/plugin/scripts/pre-compact.mjs +12 -2
  89. package/plugin/scripts/pre-compact.mjs.map +1 -1
  90. package/plugin/scripts/pre-tool-use.mjs +1 -1
  91. package/plugin/scripts/pre-tool-use.mjs.map +1 -1
  92. package/plugin/scripts/prompt-submit.mjs +14 -3
  93. package/plugin/scripts/prompt-submit.mjs.map +1 -1
  94. package/plugin/scripts/session-end.mjs +82 -18
  95. package/plugin/scripts/session-end.mjs.map +1 -1
  96. package/plugin/scripts/session-start.mjs +22 -4
  97. package/plugin/scripts/session-start.mjs.map +1 -1
  98. package/plugin/scripts/stop.mjs +1 -7
  99. package/plugin/scripts/stop.mjs.map +1 -1
  100. package/plugin/scripts/subagent-start.mjs +14 -3
  101. package/plugin/scripts/subagent-start.mjs.map +1 -1
  102. package/plugin/scripts/subagent-stop.mjs +14 -3
  103. package/plugin/scripts/subagent-stop.mjs.map +1 -1
  104. package/plugin/scripts/task-completed.mjs +14 -3
  105. package/plugin/scripts/task-completed.mjs.map +1 -1
  106. package/plugin/skills/agentmemory-agents/REFERENCE.md +6 -3
  107. package/plugin/skills/agentmemory-config/REFERENCE.md +4 -1
  108. package/plugin/skills/agentmemory-mcp-tools/REFERENCE.md +3 -2
  109. package/plugin/skills/agentmemory-rest-api/REFERENCE.md +14 -1
  110. package/plugin/skills/forget/SKILL.md +4 -1
  111. package/plugin/skills/lesson/SKILL.md +64 -0
  112. package/plugin/skills/memory-discipline/SKILL.md +57 -0
  113. package/plugin/skills/recall/SKILL.md +4 -1
  114. package/plugin/skills/remember/SKILL.md +6 -1
  115. package/dist/config-ChC9EtgV.mjs +0 -259
  116. package/dist/config-ChC9EtgV.mjs.map +0 -1
  117. package/dist/connect-JnsJXc68.mjs.map +0 -1
  118. package/dist/schema-CNiCWzV9.mjs +0 -78
  119. package/dist/schema-CNiCWzV9.mjs.map +0 -1
  120. package/dist/src-CzgoepGU.mjs.map +0 -1
  121. package/dist/standalone-YsZFFQBM.mjs.map +0 -1
  122. package/dist/tools-registry-D3NEoe5m.mjs.map +0 -1
  123. package/plugin/scripts/diagnostics.d.mts +0 -17
  124. package/plugin/scripts/diagnostics.d.mts.map +0 -1
  125. package/plugin/scripts/diagnostics.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"standalone-YsZFFQBM.mjs","names":[],"sources":["../src/mcp/in-memory-kv.ts","../src/mcp/transport.ts","../src/mcp/rest-proxy.ts","../src/mcp/standalone.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport class InMemoryKV {\n private store = new Map<string, Map<string, unknown>>();\n\n constructor(private persistPath?: string) {\n if (persistPath && existsSync(persistPath)) {\n try {\n const data = JSON.parse(readFileSync(persistPath, \"utf-8\"));\n for (const [scope, entries] of Object.entries(data)) {\n const map = new Map<string, unknown>();\n for (const [key, value] of Object.entries(\n entries as Record<string, unknown>,\n )) {\n map.set(key, value);\n }\n this.store.set(scope, map);\n }\n } catch {\n // start fresh\n }\n }\n }\n\n async get<T = unknown>(scope: string, key: string): Promise<T | null> {\n return (this.store.get(scope)?.get(key) as T) ?? null;\n }\n\n async set<T = unknown>(scope: string, key: string, data: T): Promise<T> {\n if (!this.store.has(scope)) this.store.set(scope, new Map());\n this.store.get(scope)!.set(key, data);\n return data;\n }\n\n async delete(scope: string, key: string): Promise<void> {\n this.store.get(scope)?.delete(key);\n }\n\n async list<T = unknown>(scope: string): Promise<T[]> {\n const entries = this.store.get(scope);\n return entries ? (Array.from(entries.values()) as T[]) : [];\n }\n\n persist(): void {\n if (!this.persistPath) return;\n try {\n const dir = dirname(this.persistPath);\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n const data: Record<string, Record<string, unknown>> = {};\n for (const [scope, entries] of this.store) {\n data[scope] = Object.fromEntries(entries);\n }\n writeFileSync(this.persistPath, JSON.stringify(data), \"utf-8\");\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] Persist failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n}\n","export interface JsonRpcRequest {\n jsonrpc: \"2.0\";\n id?: string | number;\n method: string;\n params?: Record<string, unknown>;\n}\n\nexport interface JsonRpcResponse {\n jsonrpc: \"2.0\";\n id: string | number | null;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\nexport type RequestHandler = (\n method: string,\n params: Record<string, unknown>,\n) => Promise<unknown>;\n\nexport interface StdioMessageParser {\n push: (chunk: Buffer | string) => void;\n isFramed: () => boolean;\n}\n\n// JSON-RPC 2.0 notifications are messages without an `id` field. The spec\n// (and the MCP transport contract) requires the server to NOT send a\n// response for notifications. Some clients tolerate spurious responses;\n// stricter clients (e.g. Codex CLI) treat them as protocol violations and\n// close the transport. See agentmemory#129.\nfunction isNotification(req: JsonRpcRequest): boolean {\n return req.id === undefined || req.id === null;\n}\n\n// Per JSON-RPC 2.0 §4, a valid request id must be a String, Number, or Null\n// (Null is technically only allowed in responses; in requests, omitting id\n// is the convention for notifications, which we treat the same as null).\n// Any other runtime type (object, array, boolean) is an Invalid Request.\nfunction isValidId(id: unknown): id is string | number | null | undefined {\n return (\n id === undefined ||\n id === null ||\n typeof id === \"string\" ||\n typeof id === \"number\"\n );\n}\n\n// Exported for unit tests so the line-handling logic is exercised\n// independently of process.stdin / process.stdout.\nexport async function processLine(\n line: string,\n handler: RequestHandler,\n writeOut: (response: JsonRpcResponse) => void,\n writeErr: (msg: string) => void = (msg) => process.stderr.write(msg),\n): Promise<void> {\n const trimmed = line.trim();\n if (!trimmed) return;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n writeOut({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32700, message: \"Parse error\" },\n });\n return;\n }\n\n const request = parsed as JsonRpcRequest;\n const rawId = (request as { id?: unknown } | null)?.id;\n\n // Invalid request shape (missing/wrong jsonrpc, non-string method).\n if (\n !request ||\n typeof request !== \"object\" ||\n request.jsonrpc !== \"2.0\" ||\n typeof request.method !== \"string\"\n ) {\n // Echo the id back only if it's a valid string/number. Notifications\n // (missing/null id) and malformed ids both drop silently — we don't\n // want to respond to something that could be a notification, and we\n // can't invent an id for a malformed one.\n if (typeof rawId === \"string\" || typeof rawId === \"number\") {\n writeOut({\n jsonrpc: \"2.0\",\n id: rawId,\n error: { code: -32600, message: \"Invalid Request\" },\n });\n }\n return;\n }\n\n // Request shape is valid but id may still be of the wrong type\n // (object, array, boolean). Per the spec, that's an Invalid Request.\n // Respond with id: null because we can't safely echo a non-JSON-RPC id.\n if (!isValidId(rawId)) {\n writeOut({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32600, message: \"Invalid Request: id must be string, number, or null\" },\n });\n return;\n }\n\n const notification = isNotification(request);\n\n try {\n const result = await handler(request.method, request.params || {});\n if (notification) return;\n writeOut({\n jsonrpc: \"2.0\",\n id: request.id as string | number,\n result,\n });\n } catch (err) {\n if (notification) {\n writeErr(\n `[mcp-transport] notification handler error for ${request.method}: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n return;\n }\n writeOut({\n jsonrpc: \"2.0\",\n id: request.id as string | number,\n error: {\n code: -32603,\n message: err instanceof Error ? err.message : String(err),\n },\n });\n }\n}\n\nfunction findHeaderEnd(buffer: Buffer): { headerEnd: number; bodyStart: number } | null {\n const crlf = buffer.indexOf(\"\\r\\n\\r\\n\");\n const lf = buffer.indexOf(\"\\n\\n\");\n if (crlf === -1 && lf === -1) return null;\n if (crlf !== -1 && (lf === -1 || crlf <= lf)) {\n return { headerEnd: crlf, bodyStart: crlf + 4 };\n }\n return { headerEnd: lf, bodyStart: lf + 2 };\n}\n\nfunction parseContentLength(header: string): number | null {\n for (const line of header.split(/\\r?\\n/)) {\n const match = line.match(/^content-length:\\s*(\\d+)\\s*$/i);\n if (match) return Number(match[1]);\n }\n return null;\n}\n\nexport function formatResponse(\n response: JsonRpcResponse,\n framed: boolean,\n): string | Buffer[] {\n const body = JSON.stringify(response);\n if (!framed) return `${body}\\n`;\n const bytes = Buffer.from(body, \"utf8\");\n return [Buffer.from(`Content-Length: ${bytes.length}\\r\\n\\r\\n`, \"ascii\"), bytes];\n}\n\nexport function createMessageParser(\n onMessage: (message: string) => void,\n writeErr: (msg: string) => void = (msg) => process.stderr.write(msg),\n): StdioMessageParser {\n let buffer = Buffer.alloc(0);\n let framed = false;\n\n function processBuffer(): void {\n while (buffer.length > 0) {\n if (buffer[0] === 10 || buffer[0] === 13) {\n buffer = buffer.subarray(1);\n continue;\n }\n\n const preview = buffer.toString(\"ascii\", 0, Math.min(buffer.length, 32));\n if (/^content-length:/i.test(preview)) {\n const header = findHeaderEnd(buffer);\n if (!header) return;\n\n const headerText = buffer.subarray(0, header.headerEnd).toString(\"ascii\");\n const contentLength = parseContentLength(headerText);\n if (contentLength === null) {\n writeErr(\"[mcp-transport] missing Content-Length header\\n\");\n buffer = buffer.subarray(header.bodyStart);\n continue;\n }\n\n const messageEnd = header.bodyStart + contentLength;\n if (buffer.length < messageEnd) return;\n\n framed = true;\n const message = buffer.subarray(header.bodyStart, messageEnd).toString(\"utf8\");\n buffer = buffer.subarray(messageEnd);\n onMessage(message);\n continue;\n }\n\n const newline = buffer.indexOf(10);\n if (newline === -1) return;\n const line = buffer\n .subarray(0, newline)\n .toString(\"utf8\")\n .replace(/\\r$/, \"\");\n buffer = buffer.subarray(newline + 1);\n onMessage(line);\n }\n }\n\n return {\n push(chunk) {\n const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, \"utf8\");\n buffer = Buffer.concat([buffer, bytes]);\n processBuffer();\n },\n isFramed() {\n return framed;\n },\n };\n}\n\nexport function createStdioTransport(handler: RequestHandler): {\n start: () => void;\n stop: () => void;\n} {\n let parser: StdioMessageParser | null = null;\n let queue = Promise.resolve();\n\n const writeResponse = (response: JsonRpcResponse) => {\n const formatted = formatResponse(response, parser?.isFramed() ?? false);\n if (typeof formatted === \"string\") {\n process.stdout.write(formatted);\n return;\n }\n for (const chunk of formatted) {\n process.stdout.write(chunk);\n }\n };\n\n const onData = (chunk: Buffer) => parser?.push(chunk);\n\n return {\n start() {\n parser = createMessageParser((message) => {\n queue = queue.then(() => processLine(message, handler, writeResponse));\n void queue.catch((err) => {\n process.stderr.write(\n `[mcp-transport] request processing failed: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n });\n });\n process.stdin.on(\"data\", onData);\n },\n stop() {\n process.stdin.off(\"data\", onData);\n parser = null;\n },\n };\n}\n","const DEFAULT_URL = \"http://localhost:3111\";\nconst DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2_000;\nconst CALL_TIMEOUT_MS = 15_000;\nconst LOCAL_MODE_TTL_MS = 30_000;\n\nfunction probeTimeoutMs(): number {\n const raw = process.env[\"AGENTMEMORY_PROBE_TIMEOUT_MS\"];\n if (!raw) return DEFAULT_HEALTH_PROBE_TIMEOUT_MS;\n const n = Number(raw);\n return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_HEALTH_PROBE_TIMEOUT_MS;\n}\n\nfunction forceProxy(): boolean {\n const raw = process.env[\"AGENTMEMORY_FORCE_PROXY\"];\n return raw === \"1\" || raw === \"true\";\n}\n\nexport interface ProxyHandle {\n mode: \"proxy\";\n baseUrl: string;\n call: (path: string, init?: RequestInit) => Promise<unknown>;\n}\n\nexport interface LocalHandle {\n mode: \"local\";\n}\n\nexport type Handle = ProxyHandle | LocalHandle;\n\nlet cached: Handle | null = null;\nlet cachedAt = 0;\nlet probeInFlight: Promise<Handle> | null = null;\n\n// `${VAR}`-style placeholders ship in plugin/.mcp.json so MCP hosts that\n// expand them (Claude Code, Cursor) substitute the user's shell value.\n// Hosts that DON'T expand pass the literal string `\"${AGENTMEMORY_URL}\"`\n// through to our subprocess — that string is truthy, defeats the `||`\n// fallback, and would have us POST to `${AGENTMEMORY_URL}/agentmemory/...`\n// (DNS failure). Strip any literal placeholder we see so the fallback\n// engages instead.\nexport function resolveEnvOrEmpty(name: string): string {\n const raw = process.env[name];\n if (!raw) return \"\";\n if (raw.startsWith(\"${\") && raw.endsWith(\"}\")) return \"\";\n return raw;\n}\n\nfunction baseUrl(): string {\n return (resolveEnvOrEmpty(\"AGENTMEMORY_URL\") || DEFAULT_URL).replace(/\\/+$/, \"\");\n}\n\nfunction authHeader(): Record<string, string> {\n const secret = resolveEnvOrEmpty(\"AGENTMEMORY_SECRET\");\n return secret ? { authorization: `Bearer ${secret}` } : {};\n}\n\n/**\n * Probes the agentmemory server's livez endpoint. Returns a Response-shaped\n * object whose `ok` flag drives the proxy/local-fallback decision.\n *\n * Tests can swap this via {@link setLivezProbe} to avoid the real 2s\n * AbortController race that destabilises mcp-standalone test runs (#449).\n * Production callers should leave it on the default.\n */\nexport type LivezProbe = (\n url: string,\n timeoutMs: number,\n headers: Record<string, string>,\n) => Promise<{ ok: boolean; status?: number; statusText?: string }>;\n\nconst defaultLivezProbe: LivezProbe = async (url, timeoutMs, headers) => {\n const res = await fetch(`${url}/agentmemory/livez`, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n });\n return { ok: res.ok, status: res.status, statusText: res.statusText };\n};\n\nlet livezProbe: LivezProbe = defaultLivezProbe;\n\n/**\n * Override the livez probe. Intended for tests — production code should rely\n * on the default fetch-based probe. Calling without an argument restores the\n * default. Pair with {@link resetHandleForTests} so the cached handle is\n * dropped before the next call.\n */\nexport function setLivezProbe(fn?: LivezProbe): void {\n livezProbe = fn ?? defaultLivezProbe;\n}\n\nasync function probe(url: string): Promise<boolean> {\n const timeout = probeTimeoutMs();\n try {\n const res = await livezProbe(url, timeout, authHeader());\n if (!res.ok) {\n process.stderr.write(\n `[@agentmemory/mcp] livez probe ${url}/agentmemory/livez -> ${res.status ?? \"?\"} ${res.statusText ?? \"\"}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe)\\n`,\n );\n }\n return res.ok;\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] livez probe ${url}/agentmemory/livez failed in ${timeout}ms: ${err instanceof Error ? err.message : String(err)}; falling back to local InMemoryKV (set AGENTMEMORY_FORCE_PROXY=1 to skip the probe, or raise AGENTMEMORY_PROBE_TIMEOUT_MS)\\n`,\n );\n return false;\n }\n}\n\nexport function invalidateHandle(): void {\n cached = null;\n cachedAt = 0;\n}\n\nexport async function resolveHandle(): Promise<Handle> {\n const now = Date.now();\n if (cached) {\n if (cached.mode === \"local\" && now - cachedAt >= LOCAL_MODE_TTL_MS) {\n cached = null;\n cachedAt = 0;\n } else {\n return cached;\n }\n }\n if (probeInFlight) return probeInFlight;\n const url = baseUrl();\n const skipProbe = forceProxy();\n probeInFlight = (async () => {\n const up = skipProbe ? true : await probe(url);\n if (skipProbe) {\n process.stderr.write(\n `[@agentmemory/mcp] AGENTMEMORY_FORCE_PROXY set; skipping livez probe and trusting ${url}\\n`,\n );\n }\n if (up) {\n const handle: ProxyHandle = {\n mode: \"proxy\",\n baseUrl: url,\n call: async (path, init) => {\n const res = await fetch(`${url}${path}`, {\n ...init,\n headers: {\n \"content-type\": \"application/json\",\n ...authHeader(),\n ...(init?.headers as Record<string, string> | undefined),\n },\n signal: AbortSignal.timeout(CALL_TIMEOUT_MS),\n });\n if (!res.ok) {\n throw new Error(\n `${init?.method || \"GET\"} ${path} -> ${res.status} ${res.statusText}`,\n );\n }\n const text = await res.text();\n return text ? JSON.parse(text) : null;\n },\n };\n cached = handle;\n cachedAt = Date.now();\n return handle;\n }\n const local: LocalHandle = { mode: \"local\" };\n cached = local;\n cachedAt = Date.now();\n return local;\n })();\n try {\n return await probeInFlight;\n } finally {\n probeInFlight = null;\n }\n}\n\nexport function resetHandleForTests(): void {\n cached = null;\n cachedAt = 0;\n probeInFlight = null;\n livezProbe = defaultLivezProbe;\n}\n","#!/usr/bin/env node\n\nimport { InMemoryKV } from \"./in-memory-kv.js\";\nimport { createStdioTransport } from \"./transport.js\";\nimport { getAllTools } from \"./tools-registry.js\";\nimport { getStandalonePersistPath } from \"../config.js\";\nimport { VERSION } from \"../version.js\";\nimport { generateId } from \"../state/schema.js\";\nimport {\n resolveHandle,\n invalidateHandle,\n type Handle,\n type ProxyHandle,\n} from \"./rest-proxy.js\";\n\nconst IMPLEMENTED_TOOLS = new Set([\n \"memory_save\",\n \"memory_recall\",\n \"memory_smart_search\",\n \"memory_sessions\",\n \"memory_export\",\n \"memory_audit\",\n \"memory_governance_delete\",\n]);\n\nconst SERVER_INFO = {\n name: \"agentmemory\",\n version: VERSION,\n protocolVersion: \"2024-11-05\",\n};\n\nconst kv = new InMemoryKV(getStandalonePersistPath());\nlet modeAnnounced = false;\n\nfunction displayAgentmemoryUrl(): string {\n // Match the literal-placeholder guard in rest-proxy.ts so log lines\n // don't show `${AGENTMEMORY_URL}` when an MCP host passed the\n // placeholder through unexpanded.\n const raw = process.env[\"AGENTMEMORY_URL\"];\n if (!raw || (raw.startsWith(\"${\") && raw.endsWith(\"}\"))) {\n return \"http://localhost:3111\";\n }\n return raw;\n}\n\nfunction announceMode(handle: Handle): void {\n if (modeAnnounced) return;\n modeAnnounced = true;\n if (handle.mode === \"proxy\") {\n process.stderr.write(\n `[@agentmemory/mcp] proxying to agentmemory server at ${handle.baseUrl}\\n`,\n );\n } else {\n const fullToolCount = getAllTools().length;\n process.stderr.write(\n `[@agentmemory/mcp] no server reachable at ${displayAgentmemoryUrl()}; running reduced LOCAL FALLBACK with ${IMPLEMENTED_TOOLS.size} of ${fullToolCount} tools. Start 'npx @agentmemory/agentmemory' (and point AGENTMEMORY_URL at it) to unlock all ${fullToolCount} tools.\\n`,\n );\n }\n}\n\nfunction normalizeList(value: unknown): string[] {\n if (!value) return [];\n if (Array.isArray(value)) {\n return value\n .map((v) => (typeof v === \"string\" ? v.trim() : \"\"))\n .filter((v) => v.length > 0);\n }\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n return [];\n}\n\nconst DEFAULT_LIMIT = 10;\nconst MAX_LIMIT = 100;\nfunction parseLimit(raw: unknown, fallback = DEFAULT_LIMIT): number {\n if (typeof raw !== \"number\" && typeof raw !== \"string\") return fallback;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0) return fallback;\n return Math.min(Math.floor(n), MAX_LIMIT);\n}\n\nfunction textResponse(payload: unknown, pretty = false): {\n content: Array<{ type: string; text: string }>;\n} {\n return {\n content: [\n { type: \"text\", text: JSON.stringify(payload, null, pretty ? 2 : 0) },\n ],\n };\n}\n\ninterface Validated {\n tool: string;\n content?: string;\n type?: string;\n concepts?: string[];\n files?: string[];\n query?: string;\n limit?: number;\n format?: string;\n tokenBudget?: number;\n memoryIds?: string[];\n reason?: string;\n}\n\nfunction validate(toolName: string, args: Record<string, unknown>): Validated {\n if (!IMPLEMENTED_TOOLS.has(toolName)) {\n throw new Error(`Unknown tool: ${toolName}`);\n }\n const v: Validated = { tool: toolName };\n switch (toolName) {\n case \"memory_save\": {\n const content = args[\"content\"];\n if (typeof content !== \"string\" || !content.trim()) {\n throw new Error(\"content is required\");\n }\n v.content = content;\n v.type = (args[\"type\"] as string) || \"fact\";\n v.concepts = normalizeList(args[\"concepts\"]);\n v.files = normalizeList(args[\"files\"]);\n return v;\n }\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const query = args[\"query\"];\n if (typeof query !== \"string\" || !query.trim()) {\n throw new Error(\"query is required\");\n }\n v.query = query.trim();\n v.limit = parseLimit(args[\"limit\"]);\n const fmt = args[\"format\"];\n if (typeof fmt === \"string\" && fmt.trim()) {\n v.format = fmt.trim().toLowerCase();\n }\n const budget = args[\"token_budget\"];\n if (typeof budget === \"number\" && Number.isFinite(budget) && budget > 0) {\n v.tokenBudget = Math.floor(budget);\n } else if (typeof budget === \"string\" && budget.trim()) {\n const n = Number(budget);\n if (Number.isFinite(n) && n > 0) v.tokenBudget = Math.floor(n);\n }\n return v;\n }\n case \"memory_sessions\": {\n v.limit = parseLimit(args[\"limit\"], 20);\n return v;\n }\n case \"memory_governance_delete\": {\n const ids = normalizeList(args[\"memoryIds\"]);\n if (ids.length === 0) throw new Error(\"memoryIds is required\");\n v.memoryIds = ids;\n v.reason = (args[\"reason\"] as string) || \"plugin skill request\";\n return v;\n }\n case \"memory_export\":\n return v;\n case \"memory_audit\": {\n v.limit = parseLimit(args[\"limit\"], 50);\n return v;\n }\n default:\n throw new Error(`Unknown tool: ${toolName}`);\n }\n}\n\nasync function handleProxy(\n v: Validated,\n handle: ProxyHandle,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n switch (v.tool) {\n case \"memory_save\": {\n const result = await handle.call(\"/agentmemory/remember\", {\n method: \"POST\",\n body: JSON.stringify({\n content: v.content,\n type: v.type,\n concepts: v.concepts,\n files: v.files,\n }),\n });\n return textResponse(result);\n }\n case \"memory_recall\": {\n const body: Record<string, unknown> = {\n query: v.query,\n limit: v.limit,\n format: v.format ?? \"full\",\n };\n if (v.tokenBudget != null) body[\"token_budget\"] = v.tokenBudget;\n const result = await handle.call(\"/agentmemory/search\", {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n return textResponse(result, true);\n }\n case \"memory_smart_search\": {\n const body: Record<string, unknown> = { query: v.query, limit: v.limit };\n if (v.format != null) body[\"format\"] = v.format;\n if (v.tokenBudget != null) body[\"token_budget\"] = v.tokenBudget;\n const result = await handle.call(\"/agentmemory/smart-search\", {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n return textResponse(result, true);\n }\n case \"memory_sessions\": {\n const result = await handle.call(\n `/agentmemory/sessions?limit=${v.limit}`,\n { method: \"GET\" },\n );\n return textResponse(result, true);\n }\n case \"memory_governance_delete\": {\n const result = await handle.call(\"/agentmemory/governance/memories\", {\n method: \"DELETE\",\n body: JSON.stringify({ memoryIds: v.memoryIds, reason: v.reason }),\n });\n return textResponse(result);\n }\n case \"memory_export\": {\n const result = await handle.call(\"/agentmemory/export\", { method: \"GET\" });\n return textResponse(result, true);\n }\n case \"memory_audit\": {\n const result = await handle.call(\n `/agentmemory/audit?limit=${v.limit}`,\n { method: \"GET\" },\n );\n return textResponse(result, true);\n }\n default:\n throw new Error(`Unknown tool: ${v.tool}`);\n }\n}\n\nasync function handleLocal(\n v: Validated,\n kvInstance: InMemoryKV,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n switch (v.tool) {\n case \"memory_save\": {\n const id = generateId(\"mem\");\n const isoNow = new Date().toISOString();\n await kvInstance.set(\"mem:memories\", id, {\n id,\n type: v.type,\n title: (v.content || \"\").slice(0, 80),\n content: v.content,\n concepts: v.concepts,\n files: v.files,\n createdAt: isoNow,\n updatedAt: isoNow,\n strength: 7,\n version: 1,\n isLatest: true,\n sessionIds: [],\n });\n kvInstance.persist();\n return textResponse({ saved: id });\n }\n\n case \"memory_recall\":\n case \"memory_smart_search\": {\n const query = (v.query || \"\").toLowerCase();\n const limit = v.limit ?? DEFAULT_LIMIT;\n const all =\n await kvInstance.list<Record<string, unknown>>(\"mem:memories\");\n const results = all\n .filter((m) => {\n const text = [\n typeof m[\"title\"] === \"string\" ? m[\"title\"] : \"\",\n typeof m[\"content\"] === \"string\" ? m[\"content\"] : \"\",\n Array.isArray(m[\"files\"]) ? m[\"files\"].join(\" \") : \"\",\n Array.isArray(m[\"concepts\"]) ? m[\"concepts\"].join(\" \") : \"\",\n Array.isArray(m[\"sessionIds\"]) ? m[\"sessionIds\"].join(\" \") : \"\",\n typeof m[\"id\"] === \"string\" ? m[\"id\"] : \"\",\n ]\n .join(\" \")\n .toLowerCase();\n return query.split(/\\s+/).every((word) => text.includes(word));\n })\n .slice(0, limit);\n return textResponse({ mode: \"compact\", results }, true);\n }\n\n case \"memory_sessions\": {\n const sessions =\n await kvInstance.list<Record<string, unknown>>(\"mem:sessions\");\n const limit = v.limit ?? 20;\n return textResponse({ sessions: sessions.slice(0, limit) }, true);\n }\n\n case \"memory_governance_delete\": {\n let deleted = 0;\n for (const id of v.memoryIds || []) {\n const existing = await kvInstance.get(\"mem:memories\", id);\n if (existing) {\n await kvInstance.delete(\"mem:memories\", id);\n deleted++;\n }\n }\n kvInstance.persist();\n return textResponse({\n deleted,\n requested: (v.memoryIds || []).length,\n reason: v.reason,\n });\n }\n\n case \"memory_export\": {\n const memories = await kvInstance.list(\"mem:memories\");\n const sessions = await kvInstance.list(\"mem:sessions\");\n return textResponse({ version: VERSION, memories, sessions }, true);\n }\n\n case \"memory_audit\": {\n const entries = await kvInstance.list(\"mem:audit\");\n const limit = v.limit ?? 50;\n return textResponse(\n {\n entries: (entries as Array<Record<string, unknown>>).slice(0, limit),\n },\n true,\n );\n }\n\n default:\n throw new Error(`Unknown tool: ${v.tool}`);\n }\n}\n\nasync function handleProxyGeneric(\n toolName: string,\n args: Record<string, unknown>,\n handle: ProxyHandle,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n // Forward to the server's full MCP surface so non-Claude clients can\n // reach all 53 tools (lessons, sentinels, slots, signals, graph, …)\n // instead of being capped at the 7 IMPLEMENTED_TOOLS set baked into\n // this shim. The server validates arguments per tool.\n const result = (await handle.call(\"/agentmemory/mcp/call\", {\n method: \"POST\",\n body: JSON.stringify({ name: toolName, arguments: args }),\n })) as { content?: Array<{ type: string; text: string }> } | null;\n if (result && Array.isArray(result.content)) {\n return { content: result.content };\n }\n return textResponse(result, true);\n}\n\nexport async function handleToolCall(\n toolName: string,\n args: Record<string, unknown>,\n kvInstance: InMemoryKV = kv,\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n const handle = await resolveHandle();\n announceMode(handle);\n\n // Tools the local InMemoryKV fallback doesn't implement: forward straight\n // to the server. Local validation would otherwise raise \"Unknown tool\"\n // (issue #234).\n if (!IMPLEMENTED_TOOLS.has(toolName)) {\n if (handle.mode === \"proxy\") {\n try {\n return await handleProxyGeneric(toolName, args, handle);\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n invalidateHandle();\n throw err;\n }\n }\n throw new Error(\n `Unknown tool: ${toolName} (local fallback supports only ${[...IMPLEMENTED_TOOLS].join(\", \")}; start an agentmemory server and set AGENTMEMORY_URL to use the full tool set)`,\n );\n }\n\n const validated = validate(toolName, args);\n if (handle.mode === \"proxy\") {\n try {\n return await handleProxy(validated, handle);\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] proxy call failed for ${toolName}: ${err instanceof Error ? err.message : String(err)}; invalidating handle and falling back to local KV\\n`,\n );\n invalidateHandle();\n }\n }\n return handleLocal(validated, kvInstance);\n}\n\nexport async function handleToolsList(): Promise<{ tools: unknown[] }> {\n const debug = process.env[\"AGENTMEMORY_DEBUG\"] === \"1\" || process.env[\"AGENTMEMORY_DEBUG\"] === \"true\";\n const handle = await resolveHandle();\n announceMode(handle);\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: handle.mode=${handle.mode}${handle.mode === \"proxy\" ? ` baseUrl=${handle.baseUrl}` : \"\"}\\n`,\n );\n }\n if (handle.mode === \"proxy\") {\n try {\n const remote = (await handle.call(\"/agentmemory/mcp/tools\", {\n method: \"GET\",\n })) as { tools?: unknown } | null;\n if (debug) {\n const shape = remote === null\n ? \"null\"\n : typeof remote !== \"object\"\n ? typeof remote\n : `keys=${Object.keys(remote as object).join(\",\")} toolsType=${Array.isArray((remote as { tools?: unknown }).tools) ? `array(len=${((remote as { tools: unknown[] }).tools).length})` : typeof (remote as { tools?: unknown }).tools}`;\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: remote response shape: ${shape}\\n`,\n );\n }\n if (remote && Array.isArray(remote.tools)) {\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: returning ${remote.tools.length} tools from server\\n`,\n );\n }\n return { tools: remote.tools };\n }\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: server returned unexpected shape (no .tools array); falling back to local IMPLEMENTED_TOOLS list. Set AGENTMEMORY_DEBUG=1 to inspect response.\\n`,\n );\n } catch (err) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list proxy failed: ${err instanceof Error ? err.message : String(err)}; falling back to local list\\n`,\n );\n invalidateHandle();\n }\n }\n const fallback = getAllTools().filter((t) => IMPLEMENTED_TOOLS.has(t.name));\n if (debug) {\n process.stderr.write(\n `[@agentmemory/mcp] tools/list: returning ${fallback.length} local fallback tools (${fallback.map((t) => t.name).join(\",\")})\\n`,\n );\n }\n return { tools: fallback };\n}\n\nconst transport = createStdioTransport(async (method, params) => {\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: SERVER_INFO.protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: {\n name: SERVER_INFO.name,\n version: SERVER_INFO.version,\n },\n };\n\n case \"notifications/initialized\":\n return {};\n\n case \"tools/list\":\n return handleToolsList();\n\n case \"tools/call\": {\n const toolName = params.name as string;\n const toolArgs = (params.arguments as Record<string, unknown>) || {};\n try {\n return await handleToolCall(toolName, toolArgs);\n } catch (err) {\n return {\n content: [\n {\n type: \"text\",\n text: `Error: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n default:\n throw new Error(`Unknown method: ${method}`);\n }\n});\n\nprocess.stderr.write(\n `[@agentmemory/mcp] Standalone MCP server v${SERVER_INFO.version} starting...\\n`,\n);\ntransport.start();\n\nprocess.on(\"SIGINT\", () => {\n kv.persist();\n process.exit(0);\n});\nprocess.on(\"SIGTERM\", () => {\n kv.persist();\n process.exit(0);\n});\n"],"mappings":";;;;;;AAGA,IAAa,aAAb,MAAwB;CACtB,wBAAgB,IAAI,KAAmC;CAEvD,YAAY,aAA8B;AAAtB,OAAA,cAAA;AAClB,MAAI,eAAe,WAAW,YAAY,CACxC,KAAI;GACF,MAAM,OAAO,KAAK,MAAM,aAAa,aAAa,QAAQ,CAAC;AAC3D,QAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE;IACnD,MAAM,sBAAM,IAAI,KAAsB;AACtC,SAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAChC,QACD,CACC,KAAI,IAAI,KAAK,MAAM;AAErB,SAAK,MAAM,IAAI,OAAO,IAAI;;UAEtB;;CAMZ,MAAM,IAAiB,OAAe,KAAgC;AACpE,SAAQ,KAAK,MAAM,IAAI,MAAM,EAAE,IAAI,IAAI,IAAU;;CAGnD,MAAM,IAAiB,OAAe,KAAa,MAAqB;AACtE,MAAI,CAAC,KAAK,MAAM,IAAI,MAAM,CAAE,MAAK,MAAM,IAAI,uBAAO,IAAI,KAAK,CAAC;AAC5D,OAAK,MAAM,IAAI,MAAM,CAAE,IAAI,KAAK,KAAK;AACrC,SAAO;;CAGT,MAAM,OAAO,OAAe,KAA4B;AACtD,OAAK,MAAM,IAAI,MAAM,EAAE,OAAO,IAAI;;CAGpC,MAAM,KAAkB,OAA6B;EACnD,MAAM,UAAU,KAAK,MAAM,IAAI,MAAM;AACrC,SAAO,UAAW,MAAM,KAAK,QAAQ,QAAQ,CAAC,GAAW,EAAE;;CAG7D,UAAgB;AACd,MAAI,CAAC,KAAK,YAAa;AACvB,MAAI;GACF,MAAM,MAAM,QAAQ,KAAK,YAAY;AACrC,OAAI,CAAC,WAAW,IAAI,CAAE,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AAO,MACb,4CAA4C,SAAS,OAAO,yBAAyB,SAAS,KAAK,MAAM,EAAE,KAAK,CAAC,KAAK,IAAI,CAAC,KAC5H;AAEH,QAAO,EAAE,OAAO,UAAU;;AAG5B,MAAM,YAAY,qBAAqB,OAAO,QAAQ,WAAW;AAC/D,SAAQ,QAAR;EACE,KAAK,aACH,QAAO;GACL,iBAAiB,YAAY;GAC7B,cAAc,EAAE,OAAO,EAAE,aAAa,OAAO,EAAE;GAC/C,YAAY;IACV,MAAM,YAAY;IAClB,SAAS,YAAY;IACtB;GACF;EAEH,KAAK,4BACH,QAAO,EAAE;EAEX,KAAK,aACH,QAAO,iBAAiB;EAE1B,KAAK,cAAc;GACjB,MAAM,WAAW,OAAO;GACxB,MAAM,WAAY,OAAO,aAAyC,EAAE;AACpE,OAAI;AACF,WAAO,MAAM,eAAe,UAAU,SAAS;YACxC,KAAK;AACZ,WAAO;KACL,SAAS,CACP;MACE,MAAM;MACN,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;MACjE,CACF;KACD,SAAS;KACV;;;EAIL,QACE,OAAM,IAAI,MAAM,mBAAmB,SAAS;;EAEhD;AAEF,QAAQ,OAAO,MACb,6CAA6C,YAAY,QAAQ,gBAClE;AACD,UAAU,OAAO;AAEjB,QAAQ,GAAG,gBAAgB;AACzB,IAAG,SAAS;AACZ,SAAQ,KAAK,EAAE;EACf;AACF,QAAQ,GAAG,iBAAiB;AAC1B,IAAG,SAAS;AACZ,SAAQ,KAAK,EAAE;EACf"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tools-registry-D3NEoe5m.mjs","names":[],"sources":["../src/version.ts","../src/mcp/tools-registry.ts"],"sourcesContent":["export const VERSION = \"0.9.28\";\n","export type McpToolDef = {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties: Record<string, { type: string; description: string }>;\n required?: string[];\n };\n};\n\nexport const CORE_TOOLS: McpToolDef[] = [\n {\n name: \"memory_recall\",\n description:\n \"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.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"Search query (keywords, file names, concepts)\",\n },\n limit: {\n type: \"number\",\n description: \"Max results to return (default 10)\",\n },\n format: {\n type: \"string\",\n description: \"Result format: full, compact, or narrative (default full)\",\n },\n token_budget: {\n type: \"number\",\n description: \"Optional token budget to trim returned results\",\n },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_compress_file\",\n description:\n \"Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"Path to the markdown file to compress\",\n },\n },\n required: [\"filePath\"],\n },\n },\n {\n name: \"memory_save\",\n description:\n \"Explicitly save an important insight, decision, or pattern to long-term memory.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The insight or decision to remember\",\n },\n type: {\n type: \"string\",\n description:\n \"Memory type: pattern, preference, architecture, bug, workflow, or fact\",\n },\n concepts: {\n type: \"string\",\n description: \"Comma-separated key concepts\",\n },\n files: {\n type: \"string\",\n description: \"Comma-separated relevant file paths\",\n },\n project: {\n type: \"string\",\n description:\n \"Stable canonical project identifier this memory belongs to (e.g. a slug, \" +\n \"UUID, or registry key). Must match the value used when the session was \" +\n \"started. Do not use filesystem paths or ad-hoc display names — those \" +\n \"change across machines and will silently break project scoping.\",\n },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_file_history\",\n description: \"Get past observations about specific files.\",\n inputSchema: {\n type: \"object\",\n properties: {\n files: { type: \"string\", description: \"Comma-separated file paths\" },\n sessionId: {\n type: \"string\",\n description: \"Current session ID to exclude\",\n },\n },\n required: [\"files\"],\n },\n },\n {\n name: \"memory_patterns\",\n description: \"Detect recurring patterns across sessions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path to analyze\" },\n },\n },\n },\n {\n name: \"memory_sessions\",\n description:\n \"List recent sessions with their status and observation counts.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_smart_search\",\n description: \"Hybrid semantic+keyword search with progressive disclosure.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n expandIds: {\n type: \"string\",\n description: \"Comma-separated observation IDs to expand\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_vision_search\",\n description:\n \"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.\",\n inputSchema: {\n type: \"object\",\n properties: {\n queryText: { type: \"string\", description: \"Text query (e.g. 'login form with error banner')\" },\n queryImageRef: { type: \"string\", description: \"Absolute path to a stored image to match against\" },\n queryImageBase64: { type: \"string\", description: \"Raw base64 image bytes or data URL\" },\n topK: { type: \"number\", description: \"Max results (default 10, max 50)\" },\n sessionId: { type: \"string\", description: \"Filter to a single session\" },\n },\n },\n },\n {\n name: \"memory_timeline\",\n description: \"Chronological observations around an anchor point.\",\n inputSchema: {\n type: \"object\",\n properties: {\n anchor: {\n type: \"string\",\n description: \"Anchor point: ISO date or keyword\",\n },\n project: { type: \"string\", description: \"Filter by project path\" },\n before: {\n type: \"number\",\n description: \"Observations before anchor (default 5)\",\n },\n after: {\n type: \"number\",\n description: \"Observations after anchor (default 5)\",\n },\n },\n required: [\"anchor\"],\n },\n },\n {\n name: \"memory_profile\",\n description: \"User/project profile with top concepts and file patterns.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Project path\" },\n refresh: {\n type: \"string\",\n description: \"Set to 'true' to force rebuild\",\n },\n },\n required: [\"project\"],\n },\n },\n {\n name: \"memory_export\",\n description: \"Export all memory data as JSON.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_relations\",\n description: \"Query the memory relationship graph.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryId: {\n type: \"string\",\n description: \"Memory ID to find relations for\",\n },\n maxHops: {\n type: \"number\",\n description: \"Max traversal depth (default 2)\",\n },\n minConfidence: {\n type: \"number\",\n description: \"Min confidence (0-1, default 0)\",\n },\n },\n required: [\"memoryId\"],\n },\n },\n {\n name: \"memory_commit_lookup\",\n description:\n \"Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sha: { type: \"string\", description: \"Full git commit SHA\" },\n },\n required: [\"sha\"],\n },\n },\n {\n name: \"memory_commits\",\n description:\n \"List recent commits linked to agent sessions, optionally filtered by branch or repo.\",\n inputSchema: {\n type: \"object\",\n properties: {\n branch: { type: \"string\", description: \"Filter by branch name\" },\n repo: { type: \"string\", description: \"Filter by remote URL\" },\n limit: { type: \"number\", description: \"Max results (default 100, max 500)\" },\n },\n },\n },\n];\n\nexport const V040_TOOLS: McpToolDef[] = [\n {\n name: \"memory_claude_bridge_sync\",\n description:\n \"Sync memory state to/from Claude Code's native MEMORY.md file.\",\n inputSchema: {\n type: \"object\",\n properties: {\n direction: {\n type: \"string\",\n description:\n \"'read' to import from MEMORY.md, 'write' to export to MEMORY.md\",\n },\n },\n required: [\"direction\"],\n },\n },\n {\n name: \"memory_graph_query\",\n description: \"Query the knowledge graph for entities and relationships.\",\n inputSchema: {\n type: \"object\",\n properties: {\n startNodeId: {\n type: \"string\",\n description: \"Starting node ID for traversal\",\n },\n nodeType: { type: \"string\", description: \"Filter by node type\" },\n maxDepth: {\n type: \"number\",\n description: \"Max BFS depth (default 3, max 5)\",\n },\n query: { type: \"string\", description: \"Search nodes by name\" },\n },\n },\n },\n {\n name: \"memory_consolidate\",\n description:\n \"Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural).\",\n inputSchema: {\n type: \"object\",\n properties: {\n tier: {\n type: \"string\",\n description: \"Target tier: episodic, semantic, or procedural\",\n },\n },\n },\n },\n {\n name: \"memory_team_share\",\n description: \"Share a memory or observation with team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n itemId: {\n type: \"string\",\n description: \"ID of memory or observation to share\",\n },\n itemType: {\n type: \"string\",\n description: \"Type: observation, memory, or pattern\",\n },\n },\n required: [\"itemId\", \"itemType\"],\n },\n },\n {\n name: \"memory_team_feed\",\n description: \"Get recent shared items from all team members.\",\n inputSchema: {\n type: \"object\",\n properties: {\n limit: { type: \"number\", description: \"Max items (default 20)\" },\n },\n },\n },\n {\n name: \"memory_audit\",\n description: \"View the audit trail of memory operations.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: { type: \"string\", description: \"Filter by operation type\" },\n limit: { type: \"number\", description: \"Max entries (default 50)\" },\n },\n },\n },\n {\n name: \"memory_governance_delete\",\n description: \"Delete specific memories with audit trail.\",\n inputSchema: {\n type: \"object\",\n properties: {\n memoryIds: {\n type: \"string\",\n description: \"Comma-separated memory IDs to delete\",\n },\n reason: { type: \"string\", description: \"Reason for deletion\" },\n },\n required: [\"memoryIds\"],\n },\n },\n {\n name: \"memory_snapshot_create\",\n description: \"Create a git-versioned snapshot of current memory state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n message: { type: \"string\", description: \"Snapshot description\" },\n },\n },\n },\n];\n\nexport const V050_TOOLS: McpToolDef[] = [\n {\n name: \"memory_action_create\",\n description:\n \"Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Action title\" },\n description: {\n type: \"string\",\n description: \"Detailed description of the work\",\n },\n priority: {\n type: \"number\",\n description: \"Priority 1-10 (10 highest)\",\n },\n project: { type: \"string\", description: \"Project path\" },\n tags: {\n type: \"string\",\n description: \"Comma-separated tags\",\n },\n parentId: {\n type: \"string\",\n description: \"Parent action ID for hierarchical actions\",\n },\n requires: {\n type: \"string\",\n description:\n \"Comma-separated action IDs that must complete before this\",\n },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_action_update\",\n description:\n \"Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID to update\" },\n status: {\n type: \"string\",\n description: \"New status: pending, active, done, blocked, cancelled\",\n },\n result: {\n type: \"string\",\n description: \"Outcome description (when completing)\",\n },\n priority: { type: \"number\", description: \"New priority 1-10\" },\n },\n required: [\"actionId\"],\n },\n },\n {\n name: \"memory_frontier\",\n description:\n \"Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: {\n type: \"string\",\n description: \"Agent ID to check lease conflicts\",\n },\n limit: { type: \"number\", description: \"Max results (default 20)\" },\n },\n },\n },\n {\n name: \"memory_next\",\n description:\n \"Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n agentId: { type: \"string\", description: \"Current agent ID\" },\n },\n },\n },\n {\n name: \"memory_lease\",\n description:\n \"Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionId: { type: \"string\", description: \"Action ID\" },\n agentId: { type: \"string\", description: \"Agent claiming the action\" },\n operation: {\n type: \"string\",\n description: \"acquire, release, or renew\",\n },\n result: {\n type: \"string\",\n description: \"Result when releasing (marks action done)\",\n },\n ttlMs: {\n type: \"number\",\n description: \"Lease duration in ms (default 10min, max 1hr)\",\n },\n },\n required: [\"actionId\", \"agentId\", \"operation\"],\n },\n },\n {\n name: \"memory_routine_run\",\n description:\n \"Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.\",\n inputSchema: {\n type: \"object\",\n properties: {\n routineId: { type: \"string\", description: \"Routine template ID\" },\n project: { type: \"string\", description: \"Project context\" },\n initiatedBy: { type: \"string\", description: \"Agent starting the run\" },\n },\n required: [\"routineId\"],\n },\n },\n {\n name: \"memory_signal_send\",\n description:\n \"Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n from: { type: \"string\", description: \"Sender agent ID\" },\n to: {\n type: \"string\",\n description: \"Recipient agent ID (omit for broadcast)\",\n },\n content: { type: \"string\", description: \"Message content\" },\n type: {\n type: \"string\",\n description: \"Message type: info, request, response, alert, handoff\",\n },\n replyTo: {\n type: \"string\",\n description: \"Signal ID to reply to (auto-threads)\",\n },\n },\n required: [\"from\", \"content\"],\n },\n },\n {\n name: \"memory_signal_read\",\n description:\n \"Read messages for an agent. Marks delivered messages as read.\",\n inputSchema: {\n type: \"object\",\n properties: {\n agentId: { type: \"string\", description: \"Agent to read messages for\" },\n unreadOnly: {\n type: \"string\",\n description: \"Set to 'true' for unread only\",\n },\n threadId: {\n type: \"string\",\n description: \"Filter by conversation thread\",\n },\n limit: { type: \"number\", description: \"Max messages (default 50)\" },\n },\n required: [\"agentId\"],\n },\n },\n {\n name: \"memory_checkpoint\",\n description:\n \"Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.\",\n inputSchema: {\n type: \"object\",\n properties: {\n operation: {\n type: \"string\",\n description: \"create, resolve, or list\",\n },\n name: { type: \"string\", description: \"Checkpoint name (for create)\" },\n checkpointId: {\n type: \"string\",\n description: \"Checkpoint ID (for resolve)\",\n },\n status: {\n type: \"string\",\n description: \"passed or failed (for resolve)\",\n },\n type: {\n type: \"string\",\n description: \"Checkpoint type: ci, approval, deploy, external, timer\",\n },\n linkedActionIds: {\n type: \"string\",\n description:\n \"Comma-separated action IDs this checkpoint gates (for create)\",\n },\n },\n required: [\"operation\"],\n },\n },\n {\n name: \"memory_mesh_sync\",\n description:\n \"Sync memories and actions with peer agentmemory instances for multi-agent collaboration.\",\n inputSchema: {\n type: \"object\",\n properties: {\n peerId: {\n type: \"string\",\n description: \"Specific peer ID (omit for all)\",\n },\n direction: {\n type: \"string\",\n description: \"push, pull, or both (default both)\",\n },\n },\n },\n },\n];\n\nexport const V051_TOOLS: McpToolDef[] = [\n {\n name: \"memory_sentinel_create\",\n description:\n \"Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Sentinel name\" },\n type: {\n type: \"string\",\n description: \"Type: webhook, timer, threshold, pattern, approval, custom\",\n },\n config: {\n type: \"string\",\n description: \"JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})\",\n },\n linkedActionIds: {\n type: \"string\",\n description: \"Comma-separated action IDs to gate\",\n },\n expiresInMs: { type: \"number\", description: \"Auto-expire after ms\" },\n },\n required: [\"name\", \"type\"],\n },\n },\n {\n name: \"memory_sentinel_trigger\",\n description:\n \"Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sentinelId: { type: \"string\", description: \"Sentinel ID to trigger\" },\n result: { type: \"string\", description: \"JSON result payload\" },\n },\n required: [\"sentinelId\"],\n },\n },\n {\n name: \"memory_sketch_create\",\n description:\n \"Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.\",\n inputSchema: {\n type: \"object\",\n properties: {\n title: { type: \"string\", description: \"Sketch title\" },\n description: { type: \"string\", description: \"What this sketch explores\" },\n expiresInMs: { type: \"number\", description: \"TTL in ms (default 1 hour)\" },\n project: { type: \"string\", description: \"Project context\" },\n },\n required: [\"title\"],\n },\n },\n {\n name: \"memory_sketch_promote\",\n description:\n \"Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.\",\n inputSchema: {\n type: \"object\",\n properties: {\n sketchId: { type: \"string\", description: \"Sketch ID to promote\" },\n project: { type: \"string\", description: \"Override project for promoted actions\" },\n },\n required: [\"sketchId\"],\n },\n },\n {\n name: \"memory_crystallize\",\n description:\n \"Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.\",\n inputSchema: {\n type: \"object\",\n properties: {\n actionIds: {\n type: \"string\",\n description: \"Comma-separated completed action IDs to crystallize\",\n },\n project: { type: \"string\", description: \"Project context\" },\n sessionId: { type: \"string\", description: \"Session context\" },\n },\n required: [\"actionIds\"],\n },\n },\n {\n name: \"memory_diagnose\",\n description:\n \"Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to check (default all)\",\n },\n },\n },\n },\n {\n name: \"memory_heal\",\n description:\n \"Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.\",\n inputSchema: {\n type: \"object\",\n properties: {\n categories: {\n type: \"string\",\n description: \"Comma-separated categories to heal (default all)\",\n },\n dryRun: {\n type: \"string\",\n description: \"Set to 'true' for dry run (report but don't fix)\",\n },\n },\n },\n },\n {\n name: \"memory_facet_tag\",\n description:\n \"Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.\",\n inputSchema: {\n type: \"object\",\n properties: {\n targetId: { type: \"string\", description: \"ID of the target to tag\" },\n targetType: {\n type: \"string\",\n description: \"Type: action, memory, or observation\",\n },\n dimension: { type: \"string\", description: \"Tag dimension (e.g., priority, team, status)\" },\n value: { type: \"string\", description: \"Tag value (e.g., urgent, backend, reviewed)\" },\n },\n required: [\"targetId\", \"targetType\", \"dimension\", \"value\"],\n },\n },\n {\n name: \"memory_facet_query\",\n description:\n \"Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.\",\n inputSchema: {\n type: \"object\",\n properties: {\n matchAll: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (AND logic)\",\n },\n matchAny: {\n type: \"string\",\n description: \"Comma-separated dimension:value pairs (OR logic)\",\n },\n targetType: {\n type: \"string\",\n description: \"Filter by type: action, memory, or observation\",\n },\n },\n },\n },\n];\n\nexport const V061_TOOLS: McpToolDef[] = [\n {\n name: \"memory_verify\",\n description:\n \"Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"Memory ID or observation ID to verify\",\n },\n },\n required: [\"id\"],\n },\n },\n];\n\nexport const V070_TOOLS: McpToolDef[] = [\n {\n name: \"memory_lesson_save\",\n description:\n \"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.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: {\n type: \"string\",\n description: \"The lesson learned (what worked, what to avoid, when to use X approach)\",\n },\n context: {\n type: \"string\",\n description: \"When/where this lesson applies\",\n },\n confidence: {\n type: \"number\",\n description: \"Initial confidence 0.0-1.0 (default 0.5)\",\n },\n project: { type: \"string\", description: \"Project this lesson is about\" },\n tags: { type: \"string\", description: \"Comma-separated tags\" },\n },\n required: [\"content\"],\n },\n },\n {\n name: \"memory_lesson_recall\",\n description:\n \"Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Search query\" },\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0.1)\",\n },\n limit: { type: \"number\", description: \"Max results (default 10)\" },\n },\n required: [\"query\"],\n },\n },\n {\n name: \"memory_obsidian_export\",\n description:\n \"Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n vaultDir: {\n type: \"string\",\n description: \"Output directory (default ~/.agentmemory/vault/)\",\n },\n types: {\n type: \"string\",\n description: \"Comma-separated types to export: memories,lessons,crystals,sessions (default all)\",\n },\n },\n },\n },\n];\n\nexport const V073_TOOLS: McpToolDef[] = [\n {\n name: \"memory_reflect\",\n description:\n \"Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n maxClusters: {\n type: \"number\",\n description: \"Max concept clusters to process (default 10, max 20)\",\n },\n },\n },\n },\n {\n name: \"memory_insight_list\",\n description:\n \"List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.\",\n inputSchema: {\n type: \"object\",\n properties: {\n project: { type: \"string\", description: \"Filter by project\" },\n minConfidence: {\n type: \"number\",\n description: \"Minimum confidence threshold (default 0)\",\n },\n limit: { type: \"number\", description: \"Max results (default 50)\" },\n },\n },\n },\n];\n\nexport const V010_SLOTS_TOOLS: McpToolDef[] = [\n {\n name: \"memory_slot_list\",\n description:\n \"List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions.\",\n inputSchema: { type: \"object\", properties: {} },\n },\n {\n name: \"memory_slot_get\",\n description: \"Read a single slot by label.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label (e.g. 'persona', 'pending_items')\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_create\",\n description: \"Create a new slot. Reject if a slot with the same label already exists.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label — lowercase, starts with letter, [a-z0-9_]\" },\n content: { type: \"string\", description: \"Initial content (default empty)\" },\n sizeLimit: { type: \"number\", description: \"Max chars (default 2000, hard cap 20000)\" },\n description: { type: \"string\", description: \"What this slot is for\" },\n pinned: { type: \"string\", description: \"'false' to exclude from context injection; default true\" },\n scope: { type: \"string\", description: \"'project' (default) or 'global' (shared across projects)\" },\n },\n required: [\"label\"],\n },\n },\n {\n name: \"memory_slot_append\",\n description:\n \"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.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n text: { type: \"string\", description: \"Text to append\" },\n },\n required: [\"label\", \"text\"],\n },\n },\n {\n name: \"memory_slot_replace\",\n description: \"Replace slot content in place. Fails if content exceeds sizeLimit.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n content: { type: \"string\", description: \"New full content\" },\n },\n required: [\"label\", \"content\"],\n },\n },\n {\n name: \"memory_slot_delete\",\n description: \"Delete a slot. Seeded default slots can be deleted unless marked readOnly.\",\n inputSchema: {\n type: \"object\",\n properties: {\n label: { type: \"string\", description: \"Slot label\" },\n },\n required: [\"label\"],\n },\n },\n];\n\nexport const ESSENTIAL_TOOLS = new Set([\n \"memory_save\",\n \"memory_recall\",\n \"memory_consolidate\",\n \"memory_smart_search\",\n \"memory_sessions\",\n \"memory_diagnose\",\n \"memory_lesson_save\",\n \"memory_reflect\",\n]);\n\nexport function getAllTools(): McpToolDef[] {\n return [\n ...CORE_TOOLS,\n ...V040_TOOLS,\n ...V050_TOOLS,\n ...V051_TOOLS,\n ...V061_TOOLS,\n ...V070_TOOLS,\n ...V073_TOOLS,\n ...V010_SLOTS_TOOLS,\n ];\n}\n\n// default switched from \"core\" (8 essential tools) to \"all\"\n// (full 53-tool surface). README and plugin manifests have always\n// advertised 53 tools \"in proxy mode\"; the old default left OpenCode /\n// Claude Code users seeing 8 with no indication the other tools existed.\n// Users who want the lean essentials can still set AGENTMEMORY_TOOLS=core.\nexport function getVisibleTools(): McpToolDef[] {\n const mode = process.env[\"AGENTMEMORY_TOOLS\"] || \"all\";\n if (mode === \"core\") return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));\n return getAllTools();\n}\n"],"mappings":";AAAA,MAAa,UAAU;;;ACUvB,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACD,QAAQ;KACN,MAAM;KACN,aAAa;KACd;IACD,cAAc;KACZ,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,UAAU;IACR,MAAM;IACN,aAAa;IACd,EACF;GACD,UAAU,CAAC,WAAW;GACvB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,MAAM;KACJ,MAAM;KACN,aACE;KACH;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,OAAO;KACL,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;KACN,aACE;KAIH;IACF;GACD,UAAU,CAAC,UAAU;GACtB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAA8B;IACpE,WAAW;KACT,MAAM;KACN,aAAa;KACd;IACF;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY,EACV,SAAS;IAAE,MAAM;IAAU,aAAa;IAA2B,EACpE;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GAAE,MAAM;GAAU,YAAY,EAAE;GAAE;EAChD;CACD;EACE,MAAM;EACN,aAAa;EACb,aAAa;GACX,MAAM;GACN,YAAY;IACV,OAAO;KAAE,MAAM;KAAU,aAAa;KAAgB;IACtD,WAAW;KACT,MAAM;KACN,aAAa;KACd;IACD,OAAO;KAAE,MAAM;KAAU,aAAa;KAA4B;IACnE;GACD,UAAU,CAAC,QAAQ;GACpB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;G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EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,WAAW;KACT,MAAM;KACN,aAAa;KACd;IACD,SAAS;KAAE,MAAM;KAAU,aAAa;KAAmB;IAC3D,WAAW;KAAE,MAAM;KAAU,aAAa;KAAmB;IAC9D;GACD,UAAU,CAAC,YAAY;GACxB;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY,EACV,YAAY;IACV,MAAM;IACN,aAAa;IACd,EACF;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACD,QAAQ;KACN,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KAAE,MAAM;KAAU,aAAa;KAA2B;IACpE,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACD,WAAW;KAAE,MAAM;KAAU,aAAa;KAAgD;IAC1F,OAAO;KAAE,MAAM;KAAU,aAAa;KAA+C;IACtF;GACD,UAAU;IAAC;IAAY;IAAc;IAAa;IAAQ;GAC3D;EACF;CACD;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,UAAU;KACR,MAAM;KACN,aAAa;KACd;IACD,YAAY;KACV,MAAM;KACN,aAAa;KACd;IACF;GACF;EACF;CACF;AAED,MAAa,aAA2B,CACtC;CACE,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY,EACV,IAAI;GACF,MAAM;GACN,aAAa;GACd,EACF;EACD,UAAU,CAAC,KAAK;EACjB;CACF,CACF;AAED,MAAa,aAA2B;CACtC;EACE,MAAM;EACN,aACE;EACF,aAAa;GACX,MAAM;GACN,YAAY;IACV,SAAS;KACP,MAAM;KACN,aAAa;KACd;IACD,SAAS;KACP,MAAM;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@@ -1,17 +0,0 @@
1
- import { ISdk } from "iii-sdk";
2
-
3
- //#region src/state/kv.d.ts
4
- declare class StateKV {
5
- private sdk;
6
- constructor(sdk: ISdk);
7
- get<T = unknown>(scope: string, key: string): Promise<T | null>;
8
- set<T = unknown>(scope: string, key: string, data: T): Promise<T>;
9
- delete(scope: string, key: string): Promise<void>;
10
- list<T = unknown>(scope: string): Promise<T[]>;
11
- }
12
- //#endregion
13
- //#region src/functions/diagnostics.d.ts
14
- declare function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void;
15
- //#endregion
16
- export { registerDiagnosticsFunction };
17
- //# sourceMappingURL=diagnostics.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"diagnostics.d.mts","names":[],"sources":["../../src/state/kv.ts","../../src/functions/diagnostics.ts"],"mappings":";;;cAEa,OAAA;EAAA,QACS,GAAA;cAAA,GAAA,EAAK,IAAA;EAEnB,GAAA,aAAA,CAAiB,KAAA,UAAe,GAAA,WAAc,OAAA,CAAQ,CAAA;EAOtD,GAAA,aAAA,CAAiB,KAAA,UAAe,GAAA,UAAa,IAAA,EAAM,CAAA,GAAI,OAAA,CAAQ,CAAA;EAO/D,MAAA,CAAO,KAAA,UAAe,GAAA,WAAc,OAAA;EAOpC,IAAA,aAAA,CAAkB,KAAA,WAAgB,OAAA,CAAQ,CAAA;AAAA;;;iBC0BlC,2BAAA,CAA4B,GAAA,EAAK,IAAA,EAAM,EAAA,EAAI,OAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"diagnostics.mjs","names":[],"sources":["../../src/state/schema.ts","../../src/state/keyed-mutex.ts","../../src/functions/diagnostics.ts"],"sourcesContent":["export const KV = {\n sessions: \"mem:sessions\",\n observations: (sessionId: string) => `mem:obs:${sessionId}`,\n memories: \"mem:memories\",\n summaries: \"mem:summaries\",\n config: \"mem:config\",\n metrics: \"mem:metrics\",\n health: \"mem:health\",\n embeddings: (obsId: string) => `mem:emb:${obsId}`,\n bm25Index: \"mem:index:bm25\",\n relations: \"mem:relations\",\n profiles: \"mem:profiles\",\n claudeBridge: \"mem:claude-bridge\",\n graphNodes: \"mem:graph:nodes\",\n graphEdges: \"mem:graph:edges\",\n semantic: \"mem:semantic\",\n procedural: \"mem:procedural\",\n teamShared: (teamId: string) => `mem:team:${teamId}:shared`,\n teamUsers: (teamId: string, userId: string) =>\n `mem:team:${teamId}:users:${userId}`,\n teamProfile: (teamId: string) => `mem:team:${teamId}:profile`,\n audit: \"mem:audit\",\n actions: \"mem:actions\",\n actionEdges: \"mem:action-edges\",\n leases: \"mem:leases\",\n routines: \"mem:routines\",\n routineRuns: \"mem:routine-runs\",\n signals: \"mem:signals\",\n checkpoints: \"mem:checkpoints\",\n mesh: \"mem:mesh\",\n sketches: \"mem:sketches\",\n facets: \"mem:facets\",\n sentinels: \"mem:sentinels\",\n crystals: \"mem:crystals\",\n} as const;\n\nexport const STREAM = {\n name: \"mem-live\",\n group: (sessionId: string) => sessionId,\n viewerGroup: \"viewer\",\n} as const;\n\nexport function generateId(prefix: string): string {\n const ts = Date.now().toString(36);\n const rand = crypto.randomUUID().replace(/-/g, \"\").slice(0, 12);\n return `${prefix}_${ts}_${rand}`;\n}\n\nexport function fingerprintId(prefix: string, content: string): string {\n const crypto = require(\"node:crypto\") as typeof import(\"node:crypto\");\n const hash = crypto.createHash(\"sha256\").update(content).digest(\"hex\");\n return `${prefix}_${hash.slice(0, 16)}`;\n}\n\nexport function jaccardSimilarity(a: string, b: string): number {\n const setA = new Set(a.split(/\\s+/).filter((t) => t.length > 2));\n const setB = new Set(b.split(/\\s+/).filter((t) => t.length > 2));\n if (setA.size === 0 && setB.size === 0) return 1;\n if (setA.size === 0 || setB.size === 0) return 0;\n let intersection = 0;\n for (const word of setA) {\n if (setB.has(word)) intersection++;\n }\n return intersection / (setA.size + setB.size - intersection);\n}\n","const locks = new Map<string, Promise<void>>();\n\nexport function withKeyedLock<T>(\n key: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const prev = locks.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n const cleanup = next.then(\n () => {},\n () => {},\n );\n locks.set(key, cleanup);\n cleanup.then(() => {\n if (locks.get(key) === cleanup) locks.delete(key);\n });\n return next;\n}\n","import type { ISdk } from \"iii-sdk\";\nimport type { StateKV } from \"../state/kv.js\";\nimport { KV } from \"../state/schema.js\";\nimport { withKeyedLock } from \"../state/keyed-mutex.js\";\nimport type {\n Action,\n ActionEdge,\n Lease,\n Checkpoint,\n Signal,\n Sketch,\n MeshPeer,\n Session,\n Memory,\n} from \"../types.js\";\n\ninterface Sentinel {\n id: string;\n name: string;\n type: \"webhook\" | \"timer\" | \"threshold\" | \"pattern\" | \"approval\" | \"custom\";\n status: \"watching\" | \"triggered\" | \"cancelled\" | \"expired\";\n config: Record<string, unknown>;\n result?: unknown;\n createdAt: string;\n triggeredAt?: string;\n expiresAt?: string;\n linkedActionIds: string[];\n escalatedAt?: string;\n}\n\ninterface DiagnosticCheck {\n name: string;\n category: string;\n status: \"pass\" | \"warn\" | \"fail\";\n message: string;\n fixable: boolean;\n}\n\nconst ALL_CATEGORIES = [\n \"actions\",\n \"leases\",\n \"sentinels\",\n \"sketches\",\n \"signals\",\n \"sessions\",\n \"memories\",\n \"mesh\",\n];\n\nconst TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;\nconst ONE_HOUR_MS = 60 * 60 * 1000;\n\nexport function registerDiagnosticsFunction(sdk: ISdk, kv: StateKV): void {\n sdk.registerFunction(\n { id: \"mem::diagnose\" },\n async (data: { categories?: string[] }) => {\n const categories = data.categories && data.categories.length > 0\n ? data.categories.filter((c) => ALL_CATEGORIES.includes(c))\n : ALL_CATEGORIES;\n\n const checks: DiagnosticCheck[] = [];\n const now = Date.now();\n\n if (categories.includes(\"actions\")) {\n const actions = await kv.list<Action>(KV.actions);\n const allEdges = await kv.list<ActionEdge>(KV.actionEdges);\n const leases = await kv.list<Lease>(KV.leases);\n const actionMap = new Map(actions.map((a) => [a.id, a]));\n\n for (const action of actions) {\n if (action.status === \"active\") {\n const hasActiveLease = leases.some(\n (l) =>\n l.actionId === action.id &&\n l.status === \"active\" &&\n new Date(l.expiresAt).getTime() > now,\n );\n if (!hasActiveLease) {\n checks.push({\n name: `active-no-lease:${action.id}`,\n category: \"actions\",\n status: \"warn\",\n message: `Action \"${action.title}\" is active but has no active lease`,\n fixable: false,\n });\n }\n }\n\n if (action.status === \"blocked\") {\n const deps = allEdges.filter(\n (e) => e.sourceActionId === action.id && e.type === \"requires\",\n );\n if (deps.length > 0) {\n const allDone = deps.every((d) => {\n const target = actionMap.get(d.targetActionId);\n return target && target.status === \"done\";\n });\n if (allDone) {\n checks.push({\n name: `blocked-deps-done:${action.id}`,\n category: \"actions\",\n status: \"fail\",\n message: `Action \"${action.title}\" is blocked but all dependencies are done`,\n fixable: true,\n });\n }\n }\n }\n\n if (action.status === \"pending\") {\n const deps = allEdges.filter(\n (e) => e.sourceActionId === action.id && e.type === \"requires\",\n );\n if (deps.length > 0) {\n const hasUnsatisfied = deps.some((d) => {\n const target = actionMap.get(d.targetActionId);\n return !target || target.status !== \"done\";\n });\n if (hasUnsatisfied) {\n checks.push({\n name: `pending-unsatisfied-deps:${action.id}`,\n category: \"actions\",\n status: \"fail\",\n message: `Action \"${action.title}\" is pending but has unsatisfied dependencies`,\n fixable: true,\n });\n }\n }\n }\n }\n\n if (\n !checks.some((c) => c.category === \"actions\" && c.status !== \"pass\")\n ) {\n checks.push({\n name: \"actions-ok\",\n category: \"actions\",\n status: \"pass\",\n message: `All ${actions.length} actions are consistent`,\n fixable: false,\n });\n }\n }\n\n if (categories.includes(\"leases\")) {\n const leases = await kv.list<Lease>(KV.leases);\n const actions = await kv.list<Action>(KV.actions);\n const actionIds = new Set(actions.map((a) => a.id));\n let leaseIssues = 0;\n\n for (const lease of leases) {\n if (\n lease.status === \"active\" &&\n new Date(lease.expiresAt).getTime() <= now\n ) {\n checks.push({\n name: `expired-lease:${lease.id}`,\n category: \"leases\",\n status: \"fail\",\n message: `Lease ${lease.id} for action ${lease.actionId} expired at ${lease.expiresAt}`,\n fixable: true,\n });\n leaseIssues++;\n }\n\n if (!actionIds.has(lease.actionId)) {\n checks.push({\n name: `orphaned-lease:${lease.id}`,\n category: \"leases\",\n status: \"fail\",\n message: `Lease ${lease.id} references non-existent action ${lease.actionId}`,\n fixable: true,\n });\n leaseIssues++;\n }\n }\n\n if (leaseIssues === 0) {\n checks.push({\n name: \"leases-ok\",\n category: \"leases\",\n status: \"pass\",\n message: `All ${leases.length} leases are healthy`,\n fixable: false,\n });\n }\n }\n\n if (categories.includes(\"sentinels\")) {\n const sentinels = await kv.list<Sentinel>(KV.sentinels);\n const actions = await kv.list<Action>(KV.actions);\n const actionIds = new Set(actions.map((a) => a.id));\n let sentinelIssues = 0;\n\n for (const sentinel of sentinels) {\n if (\n sentinel.status === \"watching\" &&\n sentinel.expiresAt &&\n new Date(sentinel.expiresAt).getTime() <= now\n ) {\n checks.push({\n name: `expired-sentinel:${sentinel.id}`,\n category: \"sentinels\",\n status: \"fail\",\n message: `Sentinel \"${sentinel.name}\" expired at ${sentinel.expiresAt}`,\n fixable: true,\n });\n sentinelIssues++;\n }\n\n for (const actionId of sentinel.linkedActionIds) {\n if (!actionIds.has(actionId)) {\n checks.push({\n name: `sentinel-missing-action:${sentinel.id}:${actionId}`,\n category: \"sentinels\",\n status: \"warn\",\n message: `Sentinel \"${sentinel.name}\" references non-existent action ${actionId}`,\n fixable: false,\n });\n sentinelIssues++;\n }\n }\n }\n\n if (sentinelIssues === 0) {\n checks.push({\n name: \"sentinels-ok\",\n category: \"sentinels\",\n status: \"pass\",\n message: `All ${sentinels.length} sentinels are healthy`,\n fixable: false,\n });\n }\n }\n\n if (categories.includes(\"sketches\")) {\n const sketches = await kv.list<Sketch>(KV.sketches);\n let sketchIssues = 0;\n\n for (const sketch of sketches) {\n if (\n sketch.status === \"active\" &&\n new Date(sketch.expiresAt).getTime() <= now\n ) {\n checks.push({\n name: `expired-sketch:${sketch.id}`,\n category: \"sketches\",\n status: \"fail\",\n message: `Sketch \"${sketch.title}\" expired at ${sketch.expiresAt}`,\n fixable: true,\n });\n sketchIssues++;\n }\n }\n\n if (sketchIssues === 0) {\n checks.push({\n name: \"sketches-ok\",\n category: \"sketches\",\n status: \"pass\",\n message: `All ${sketches.length} sketches are healthy`,\n fixable: false,\n });\n }\n }\n\n if (categories.includes(\"signals\")) {\n const signals = await kv.list<Signal>(KV.signals);\n let signalIssues = 0;\n\n for (const signal of signals) {\n if (\n signal.expiresAt &&\n new Date(signal.expiresAt).getTime() <= now\n ) {\n checks.push({\n name: `expired-signal:${signal.id}`,\n category: \"signals\",\n status: \"fail\",\n message: `Signal from \"${signal.from}\" expired at ${signal.expiresAt}`,\n fixable: true,\n });\n signalIssues++;\n }\n }\n\n if (signalIssues === 0) {\n checks.push({\n name: \"signals-ok\",\n category: \"signals\",\n status: \"pass\",\n message: `All ${signals.length} signals are healthy`,\n fixable: false,\n });\n }\n }\n\n if (categories.includes(\"sessions\")) {\n const sessions = await kv.list<Session>(KV.sessions);\n let sessionIssues = 0;\n\n for (const session of sessions) {\n if (\n session.status === \"active\" &&\n now - new Date(session.startedAt).getTime() > TWENTY_FOUR_HOURS_MS\n ) {\n checks.push({\n name: `abandoned-session:${session.id}`,\n category: \"sessions\",\n status: \"warn\",\n message: `Session ${session.id} has been active for over 24 hours`,\n fixable: false,\n });\n sessionIssues++;\n }\n }\n\n if (sessionIssues === 0) {\n checks.push({\n name: \"sessions-ok\",\n category: \"sessions\",\n status: \"pass\",\n message: `All ${sessions.length} sessions are healthy`,\n fixable: false,\n });\n }\n }\n\n if (categories.includes(\"memories\")) {\n const memories = await kv.list<Memory>(KV.memories);\n const memoryIds = new Set(memories.map((m) => m.id));\n const supersededBy = new Map<string, string>();\n let memoryIssues = 0;\n\n for (const memory of memories) {\n if (memory.supersedes && memory.supersedes.length > 0) {\n for (const sid of memory.supersedes) {\n if (!memoryIds.has(sid)) {\n checks.push({\n name: `memory-missing-supersedes:${memory.id}:${sid}`,\n category: \"memories\",\n status: \"warn\",\n message: `Memory \"${memory.title}\" supersedes non-existent memory ${sid}`,\n fixable: false,\n });\n memoryIssues++;\n }\n supersededBy.set(sid, memory.id);\n }\n }\n }\n\n for (const memory of memories) {\n if (memory.isLatest && supersededBy.has(memory.id)) {\n checks.push({\n name: `memory-stale-latest:${memory.id}`,\n category: \"memories\",\n status: \"fail\",\n message: `Memory \"${memory.title}\" has isLatest=true but is superseded by ${supersededBy.get(memory.id)}`,\n fixable: true,\n });\n memoryIssues++;\n }\n }\n\n if (memoryIssues === 0) {\n checks.push({\n name: \"memories-ok\",\n category: \"memories\",\n status: \"pass\",\n message: `All ${memories.length} memories are consistent`,\n fixable: false,\n });\n }\n }\n\n if (categories.includes(\"mesh\")) {\n const peers = await kv.list<MeshPeer>(KV.mesh);\n let meshIssues = 0;\n\n for (const peer of peers) {\n if (\n peer.lastSyncAt &&\n now - new Date(peer.lastSyncAt).getTime() > ONE_HOUR_MS\n ) {\n checks.push({\n name: `stale-peer:${peer.id}`,\n category: \"mesh\",\n status: \"warn\",\n message: `Peer \"${peer.name}\" last synced over 1 hour ago`,\n fixable: false,\n });\n meshIssues++;\n }\n\n if (peer.status === \"error\") {\n checks.push({\n name: `error-peer:${peer.id}`,\n category: \"mesh\",\n status: \"warn\",\n message: `Peer \"${peer.name}\" is in error state`,\n fixable: false,\n });\n meshIssues++;\n }\n }\n\n if (meshIssues === 0) {\n checks.push({\n name: \"mesh-ok\",\n category: \"mesh\",\n status: \"pass\",\n message: `All ${peers.length} mesh peers are healthy`,\n fixable: false,\n });\n }\n }\n\n const summary = {\n pass: checks.filter((c) => c.status === \"pass\").length,\n warn: checks.filter((c) => c.status === \"warn\").length,\n fail: checks.filter((c) => c.status === \"fail\").length,\n fixable: checks.filter((c) => c.fixable).length,\n };\n\n return { success: true, checks, summary };\n },\n );\n\n sdk.registerFunction(\n { id: \"mem::heal\" },\n async (data: { categories?: string[]; dryRun?: boolean }) => {\n const dryRun = data.dryRun ?? false;\n const categories = data.categories && data.categories.length > 0\n ? data.categories.filter((c) => ALL_CATEGORIES.includes(c))\n : ALL_CATEGORIES;\n\n let fixed = 0;\n let skipped = 0;\n const details: string[] = [];\n const now = Date.now();\n\n if (categories.includes(\"actions\")) {\n const actions = await kv.list<Action>(KV.actions);\n const allEdges = await kv.list<ActionEdge>(KV.actionEdges);\n const actionMap = new Map(actions.map((a) => [a.id, a]));\n\n for (const action of actions) {\n if (action.status === \"blocked\") {\n const deps = allEdges.filter(\n (e) => e.sourceActionId === action.id && e.type === \"requires\",\n );\n if (deps.length > 0) {\n const allDone = deps.every((d) => {\n const target = actionMap.get(d.targetActionId);\n return target && target.status === \"done\";\n });\n if (allDone) {\n if (dryRun) {\n details.push(\n `[dry-run] Would unblock action \"${action.title}\" (${action.id})`,\n );\n fixed++;\n continue;\n }\n const didFix = await withKeyedLock(\n `mem:action:${action.id}`,\n async () => {\n const fresh = await kv.get<Action>(KV.actions, action.id);\n if (!fresh || fresh.status !== \"blocked\") return false;\n const freshEdges = await kv.list<ActionEdge>(KV.actionEdges);\n const freshDeps = freshEdges.filter(\n (e) =>\n e.sourceActionId === fresh.id && e.type === \"requires\",\n );\n const freshActions = await kv.list<Action>(KV.actions);\n const freshMap = new Map(\n freshActions.map((a) => [a.id, a]),\n );\n const stillAllDone = freshDeps.every((d) => {\n const target = freshMap.get(d.targetActionId);\n return target && target.status === \"done\";\n });\n if (!stillAllDone) return false;\n fresh.status = \"pending\";\n fresh.updatedAt = new Date().toISOString();\n await kv.set(KV.actions, fresh.id, fresh);\n return true;\n },\n );\n if (didFix) {\n details.push(\n `Unblocked action \"${action.title}\" (${action.id})`,\n );\n fixed++;\n } else {\n skipped++;\n }\n }\n }\n }\n\n if (action.status === \"pending\") {\n const deps = allEdges.filter(\n (e) => e.sourceActionId === action.id && e.type === \"requires\",\n );\n if (deps.length > 0) {\n const hasUnsatisfied = deps.some((d) => {\n const target = actionMap.get(d.targetActionId);\n return !target || target.status !== \"done\";\n });\n if (hasUnsatisfied) {\n if (dryRun) {\n details.push(\n `[dry-run] Would block action \"${action.title}\" (${action.id})`,\n );\n fixed++;\n continue;\n }\n const didFix = await withKeyedLock(\n `mem:action:${action.id}`,\n async () => {\n const fresh = await kv.get<Action>(KV.actions, action.id);\n if (!fresh || fresh.status !== \"pending\") return false;\n const freshEdges = await kv.list<ActionEdge>(KV.actionEdges);\n const freshDeps = freshEdges.filter(\n (e) =>\n e.sourceActionId === fresh.id && e.type === \"requires\",\n );\n const freshActions = await kv.list<Action>(KV.actions);\n const freshMap = new Map(\n freshActions.map((a) => [a.id, a]),\n );\n const stillUnsatisfied = freshDeps.some((d) => {\n const target = freshMap.get(d.targetActionId);\n return !target || target.status !== \"done\";\n });\n if (!stillUnsatisfied) return false;\n fresh.status = \"blocked\";\n fresh.updatedAt = new Date().toISOString();\n await kv.set(KV.actions, fresh.id, fresh);\n return true;\n },\n );\n if (didFix) {\n details.push(\n `Blocked action \"${action.title}\" (${action.id})`,\n );\n fixed++;\n } else {\n skipped++;\n }\n }\n }\n }\n }\n }\n\n if (categories.includes(\"leases\")) {\n const leases = await kv.list<Lease>(KV.leases);\n const actions = await kv.list<Action>(KV.actions);\n const actionIds = new Set(actions.map((a) => a.id));\n\n for (const lease of leases) {\n if (\n lease.status === \"active\" &&\n new Date(lease.expiresAt).getTime() <= now\n ) {\n if (dryRun) {\n details.push(\n `[dry-run] Would expire lease ${lease.id} for action ${lease.actionId}`,\n );\n fixed++;\n continue;\n }\n const didFix = await withKeyedLock(\n `mem:lease:${lease.actionId}`,\n async () => {\n const fresh = await kv.get<Lease>(KV.leases, lease.id);\n if (\n !fresh ||\n fresh.status !== \"active\" ||\n new Date(fresh.expiresAt).getTime() > Date.now()\n ) {\n return false;\n }\n fresh.status = \"expired\";\n await kv.set(KV.leases, fresh.id, fresh);\n\n const action = await kv.get<Action>(KV.actions, fresh.actionId);\n if (\n action &&\n action.status === \"active\" &&\n action.assignedTo === fresh.agentId\n ) {\n action.status = \"pending\";\n action.assignedTo = undefined;\n action.updatedAt = new Date().toISOString();\n await kv.set(KV.actions, action.id, action);\n }\n return true;\n },\n );\n if (didFix) {\n details.push(\n `Expired lease ${lease.id} for action ${lease.actionId}`,\n );\n fixed++;\n } else {\n skipped++;\n }\n continue;\n }\n\n if (!actionIds.has(lease.actionId)) {\n if (dryRun) {\n details.push(\n `[dry-run] Would delete orphaned lease ${lease.id}`,\n );\n fixed++;\n continue;\n }\n await kv.delete(KV.leases, lease.id);\n details.push(`Deleted orphaned lease ${lease.id}`);\n fixed++;\n }\n }\n }\n\n if (categories.includes(\"sentinels\")) {\n const sentinels = await kv.list<Sentinel>(KV.sentinels);\n\n for (const sentinel of sentinels) {\n if (\n sentinel.status === \"watching\" &&\n sentinel.expiresAt &&\n new Date(sentinel.expiresAt).getTime() <= now\n ) {\n if (dryRun) {\n details.push(\n `[dry-run] Would expire sentinel \"${sentinel.name}\" (${sentinel.id})`,\n );\n fixed++;\n continue;\n }\n const didFix = await withKeyedLock(\n `mem:sentinel:${sentinel.id}`,\n async () => {\n const fresh = await kv.get<Sentinel>(\n KV.sentinels,\n sentinel.id,\n );\n if (!fresh || fresh.status !== \"watching\") return false;\n if (\n !fresh.expiresAt ||\n new Date(fresh.expiresAt).getTime() > Date.now()\n ) {\n return false;\n }\n fresh.status = \"expired\";\n await kv.set(KV.sentinels, fresh.id, fresh);\n return true;\n },\n );\n if (didFix) {\n details.push(\n `Expired sentinel \"${sentinel.name}\" (${sentinel.id})`,\n );\n fixed++;\n } else {\n skipped++;\n }\n }\n }\n }\n\n if (categories.includes(\"sketches\")) {\n const sketches = await kv.list<Sketch>(KV.sketches);\n\n for (const sketch of sketches) {\n if (\n sketch.status === \"active\" &&\n new Date(sketch.expiresAt).getTime() <= now\n ) {\n if (dryRun) {\n details.push(\n `[dry-run] Would discard expired sketch \"${sketch.title}\" (${sketch.id})`,\n );\n fixed++;\n continue;\n }\n const didFix = await withKeyedLock(\n `mem:sketch:${sketch.id}`,\n async () => {\n const fresh = await kv.get<Sketch>(KV.sketches, sketch.id);\n if (\n !fresh ||\n fresh.status !== \"active\" ||\n new Date(fresh.expiresAt).getTime() > Date.now()\n ) {\n return false;\n }\n\n const allEdges = await kv.list<ActionEdge>(KV.actionEdges);\n const actionIdSet = new Set(fresh.actionIds);\n for (const edge of allEdges) {\n if (\n actionIdSet.has(edge.sourceActionId) ||\n actionIdSet.has(edge.targetActionId)\n ) {\n await kv.delete(KV.actionEdges, edge.id);\n }\n }\n for (const actionId of fresh.actionIds) {\n await kv.delete(KV.actions, actionId);\n }\n\n fresh.status = \"discarded\";\n fresh.discardedAt = new Date().toISOString();\n await kv.set(KV.sketches, fresh.id, fresh);\n return true;\n },\n );\n if (didFix) {\n details.push(\n `Discarded expired sketch \"${sketch.title}\" (${sketch.id})`,\n );\n fixed++;\n } else {\n skipped++;\n }\n }\n }\n }\n\n if (categories.includes(\"signals\")) {\n const signals = await kv.list<Signal>(KV.signals);\n\n for (const signal of signals) {\n if (\n signal.expiresAt &&\n new Date(signal.expiresAt).getTime() <= now\n ) {\n if (dryRun) {\n details.push(\n `[dry-run] Would delete expired signal ${signal.id}`,\n );\n fixed++;\n continue;\n }\n await kv.delete(KV.signals, signal.id);\n details.push(`Deleted expired signal ${signal.id}`);\n fixed++;\n }\n }\n }\n\n if (categories.includes(\"memories\")) {\n const memories = await kv.list<Memory>(KV.memories);\n const supersededBy = new Map<string, string>();\n\n for (const memory of memories) {\n if (memory.supersedes && memory.supersedes.length > 0) {\n for (const sid of memory.supersedes) {\n supersededBy.set(sid, memory.id);\n }\n }\n }\n\n for (const memory of memories) {\n if (memory.isLatest && supersededBy.has(memory.id)) {\n if (dryRun) {\n details.push(\n `[dry-run] Would set isLatest=false on memory \"${memory.title}\" (${memory.id})`,\n );\n fixed++;\n continue;\n }\n const didFix = await withKeyedLock(\n `mem:memory:${memory.id}`,\n async () => {\n const fresh = await kv.get<Memory>(KV.memories, memory.id);\n if (!fresh || !fresh.isLatest) return false;\n fresh.isLatest = false;\n fresh.updatedAt = new Date().toISOString();\n await kv.set(KV.memories, fresh.id, fresh);\n return true;\n },\n );\n if (didFix) {\n details.push(\n `Set isLatest=false on memory \"${memory.title}\" (${memory.id})`,\n );\n fixed++;\n } else {\n skipped++;\n }\n }\n }\n }\n\n return { success: true, fixed, skipped, details };\n },\n );\n}\n"],"mappings":";AAAA,MAAa,KAAK;CAChB,UAAU;CACV,eAAe,cAAsB,WAAW;CAChD,UAAU;CACV,WAAW;CACX,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,aAAa,UAAkB,WAAW;CAC1C,WAAW;CACX,WAAW;CACX,UAAU;CACV,cAAc;CACd,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,YAAY;CACZ,aAAa,WAAmB,YAAY,OAAO;CACnD,YAAY,QAAgB,WAC1B,YAAY,OAAO,SAAS;CAC9B,cAAc,WAAmB,YAAY,OAAO;CACpD,OAAO;CACP,SAAS;CACT,aAAa;CACb,QAAQ;CACR,UAAU;CACV,aAAa;CACb,SAAS;CACT,aAAa;CACb,MAAM;CACN,UAAU;CACV,QAAQ;CACR,WAAW;CACX,UAAU;CACX;;;;AClCD,MAAM,wBAAQ,IAAI,KAA4B;AAE9C,SAAgB,cACd,KACA,IACY;CAEZ,MAAM,QADO,MAAM,IAAI,IAAI,IAAI,QAAQ,SAAS,EAC9B,KAAK,IAAI,GAAG;CAC9B,MAAM,UAAU,KAAK,WACb,UACA,GACP;AACD,OAAM,IAAI,KAAK,QAAQ;AACvB,SAAQ,WAAW;AACjB,MAAI,MAAM,IAAI,IAAI,KAAK,QAAS,OAAM,OAAO,IAAI;GACjD;AACF,QAAO;;;;;ACsBT,MAAM,iBAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,uBAAuB,OAAU,KAAK;AAC5C,MAAM,cAAc,OAAU;AAE9B,SAAgB,4BAA4B,KAAW,IAAmB;AACxE,KAAI,iBACF,EAAE,IAAI,iBAA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