diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..6d86cf510a485946bcc32595ceca1b944f905a7d --- /dev/null +++ b/plugin/.claude-plugin/plugin.json @@ -0,0 +1,13 @@ +{ + "name": "agentmemory", + "version": "0.9.27", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 16 MCP tools, 16 skills, real-time viewer.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory", + "skills": ["./skills/"] +} diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..eb807087f270441d80e6aab6736245bb30d6bf30 --- /dev/null +++ b/plugin/.codex-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "agentmemory", + "version": "0.9.27", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 6 hooks, 16 MCP tools, 16 skills, real-time viewer.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory", + "skills": "./skills/", + "mcpServers": "./.mcp.json", + "hooks": "./hooks/hooks.codex.json" +} diff --git a/plugin/.mcp.copilot.json b/plugin/.mcp.copilot.json new file mode 100644 index 0000000000000000000000000000000000000000..ac03b2024010351e12cc4641d3d32b64a2cac43e --- /dev/null +++ b/plugin/.mcp.copilot.json @@ -0,0 +1,15 @@ +{ + "mcpServers": { + "agentmemory": { + "type": "local", + "command": "python", + "args": ["${COPILOT_PLUGIN_ROOT}/scripts/mcp_stdio.py"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL:-http://localhost:3111}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET:-}", + "AGENTMEMORY_TOOLS": "${AGENTMEMORY_TOOLS:-all}" + }, + "tools": ["*"] + } + } +} diff --git a/plugin/.mcp.json b/plugin/.mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..ece2451161d51b1c58d6708a2f1bd4a19435fdb8 --- /dev/null +++ b/plugin/.mcp.json @@ -0,0 +1,13 @@ +{ + "mcpServers": { + "agentmemory": { + "command": "python", + "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/mcp_stdio.py"], + "env": { + "AGENTMEMORY_URL": "${AGENTMEMORY_URL:-http://localhost:3111}", + "AGENTMEMORY_SECRET": "${AGENTMEMORY_SECRET:-}", + "AGENTMEMORY_TOOLS": "${AGENTMEMORY_TOOLS:-all}" + } + } + } +} diff --git a/plugin/hooks/hooks.codex.json b/plugin/hooks/hooks.codex.json new file mode 100644 index 0000000000000000000000000000000000000000..db76b1d43270863490945565b0d3f68e71e590b4 --- /dev/null +++ b/plugin/hooks/hooks.codex.json @@ -0,0 +1,67 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/session_start.py\"", + "statusMessage": "agentmemory: loading session context" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/prompt_submit.py\"", + "statusMessage": "agentmemory: recalling relevant memories" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Edit|Write|Read|Glob|Grep", + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/pre_tool_use.py\"" + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/post_tool_use.py\"" + } + ] + } + ], + "PreCompact": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/pre_compact.py\"" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/stop.py\"" + } + ] + } + ] + } +} diff --git a/plugin/hooks/hooks.copilot.json b/plugin/hooks/hooks.copilot.json new file mode 100644 index 0000000000000000000000000000000000000000..5b69524cc72cb79e77710fa4421e3edf5eb69777 --- /dev/null +++ b/plugin/hooks/hooks.copilot.json @@ -0,0 +1,72 @@ +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/session_start.py\"" + } + ], + "userPromptSubmitted": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/prompt_submit.py\"" + } + ], + "preToolUse": [ + { + "type": "command", + "matcher": "edit|write|create|read|view|glob|grep", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/pre_tool_use.py\"" + } + ], + "postToolUse": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/post_tool_use.py\"" + } + ], + "postToolUseFailure": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/post_tool_failure.py\"" + } + ], + "preCompact": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/pre_compact.py\"" + } + ], + "agentStop": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/stop.py\"" + } + ], + "sessionEnd": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/session_end.py\"" + } + ], + "subagentStart": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/subagent_start.py\"" + } + ], + "subagentStop": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/subagent_stop.py\"" + } + ], + "notification": [ + { + "type": "command", + "command": "python \"${COPILOT_PLUGIN_ROOT}/scripts/notification.py\"" + } + ] + } +} diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..3cf9af9d7bfd0c75b8dfdeec8bdb1ba6fcd1e2c7 --- /dev/null +++ b/plugin/hooks/hooks.json @@ -0,0 +1,125 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/session_start.py\"" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/prompt_submit.py\"" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Edit|Write|Read|Glob|Grep", + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/pre_tool_use.py\"" + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/post_tool_use.py\"" + } + ] + } + ], + "PostToolUseFailure": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/post_tool_failure.py\"" + } + ] + } + ], + "PreCompact": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/pre_compact.py\"" + } + ] + } + ], + "SubagentStart": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/subagent_start.py\"" + } + ] + } + ], + "SubagentStop": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/subagent_stop.py\"" + } + ] + } + ], + "Notification": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/notification.py\"" + } + ] + } + ], + "TaskCompleted": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/task_completed.py\"" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/stop.py\"" + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${CLAUDE_PLUGIN_ROOT}/scripts/session_end.py\"" + } + ] + } + ] + } +} diff --git a/plugin/plugin.json b/plugin/plugin.json new file mode 100644 index 0000000000000000000000000000000000000000..9a1e2519da712463d8734fcfa318ac7268fa3822 --- /dev/null +++ b/plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "agentmemory", + "version": "0.9.27", + "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 16 MCP tools, 16 skills, real-time viewer.", + "author": { + "name": "Rohit Ghumare", + "url": "https://github.com/rohitg00" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/rohitg00/agentmemory", + "repository": "https://github.com/rohitg00/agentmemory", + "skills": "skills/", + "mcpServers": ".mcp.copilot.json", + "hooks": "hooks/hooks.copilot.json" +} diff --git a/plugin/scripts/hook_utils.py b/plugin/scripts/hook_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc75aa8f948aa6820565887196b45cc9d7f55fea --- /dev/null +++ b/plugin/scripts/hook_utils.py @@ -0,0 +1,91 @@ +import os +import sys +import json +import urllib.request +import urllib.error +import subprocess +import threading +from pathlib import Path + +DEFAULT_BASE_URL = "http://localhost:3111" + +def load_env(): + """Load ~/.agentmemory/.env or XDG_CONFIG_HOME config into os.environ (best effort).""" + candidates = [] + home = os.environ.get("HOME") or os.environ.get("USERPROFILE") + if home: + candidates.append(Path(home) / ".agentmemory" / ".env") + xdg_config = os.environ.get("XDG_CONFIG_HOME") + if xdg_config: + candidates.append(Path(xdg_config) / "agentmemory" / ".env") + + for path in candidates: + try: + if not path.is_file(): + continue + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, val = line.partition("=") + key = key.strip() + val = val.strip().strip('"').strip("'") + if key: + os.environ.setdefault(key, val) + except Exception: + continue + os.environ.setdefault("AGENTMEMORY_URL", DEFAULT_BASE_URL) + +# Load env variables immediately upon importing this utility +load_env() + +def resolve_project(cwd=None): + explicit = os.environ.get("AGENTMEMORY_PROJECT_NAME") + if explicit and explicit.strip(): + return explicit.strip() + + directory = cwd if (cwd and cwd.strip()) else os.getcwd() + try: + top = subprocess.check_output( + ["git", "rev-parse", "--show-toplevel"], + cwd=directory, + stderr=subprocess.DEVNULL, + timeout=0.5 + ).decode().strip() + if top: + return os.path.basename(top) + except Exception: + pass + + return os.path.basename(os.path.abspath(directory)) + +def is_sdk_child(payload): + if os.environ.get("AGENTMEMORY_SDK_CHILD") == "1": + return True + if not isinstance(payload, dict): + return False + return payload.get("entrypoint") == "sdk-ts" or payload.get("entrypoint") == "sdk-python" + +def api_call(path, body=None, timeout=1.5): + base_url = os.environ.get("AGENTMEMORY_URL", DEFAULT_BASE_URL) + url = f"{base_url}/agentmemory/{path}" + headers = {"Content-Type": "application/json"} + secret = os.environ.get("AGENTMEMORY_SECRET", "") + if secret: + headers["Authorization"] = f"Bearer {secret}" + + req = urllib.request.Request( + url, + data=json.dumps(body).encode("utf-8") if body else None, + headers=headers, + method="POST" + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read().decode("utf-8")) + except Exception: + return None + +def api_call_bg(path, body=None): + t = threading.Thread(target=api_call, args=(path, body), daemon=True) + t.start() diff --git a/plugin/scripts/mcp_stdio.py b/plugin/scripts/mcp_stdio.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7c4de5393fee1e4b316e588dfb639faeb08ab2 --- /dev/null +++ b/plugin/scripts/mcp_stdio.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +""" +stdio MCP wrapper — bridges Claude Code's MCP stdio protocol to the +agentmemory Flask HTTP API running on localhost. + +Usage: python mcp_stdio.py +""" +import sys +import json +import requests + +BASE = "http://127.0.0.1:3111/agentmemory" +SECRET = None # set via AGENTMEMORY_SECRET env var if auth enabled + +import os +_secret = os.getenv("AGENTMEMORY_SECRET") + +def headers(): + h = {"Content-Type": "application/json"} + if _secret: + h["Authorization"] = f"Bearer {_secret}" + return h + +def send(msg): + line = json.dumps(msg, separators=(",", ":")) + sys.stdout.write(line + "\n") + sys.stdout.flush() + +def handle(req): + method = req.get("method", "") + req_id = req.get("id") + params = req.get("params") or {} + + if method == "initialize": + send({ + "jsonrpc": "2.0", "id": req_id, + "result": { + "protocolVersion": "2024-11-05", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "agentmemory-local", "version": "0.9.8"} + } + }) + + elif method == "initialized": + pass # notification — no response + + elif method == "ping": + send({"jsonrpc": "2.0", "id": req_id, "result": {}}) + + elif method == "tools/list": + try: + r = requests.get(f"{BASE}/mcp/tools", headers=headers(), timeout=5) + tools = r.json().get("tools", []) + send({"jsonrpc": "2.0", "id": req_id, "result": {"tools": tools}}) + except Exception as e: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32000, "message": f"agentmemory unreachable: {e}"}}) + + elif method == "tools/call": + name = params.get("name") + args = params.get("arguments") or {} + try: + r = requests.post(f"{BASE}/mcp/tools", + headers=headers(), + json={"name": name, "arguments": args}, + timeout=30) + result = r.json() + # MCP expects content array + if "content" not in result: + result = {"content": [{"type": "text", "text": json.dumps(result)}]} + send({"jsonrpc": "2.0", "id": req_id, "result": result}) + except Exception as e: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32000, "message": str(e)}}) + + elif req_id is not None: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32601, "message": "Method not found"}}) + + +def main(): + for raw_line in sys.stdin: + raw_line = raw_line.strip() + if not raw_line: + continue + try: + req = json.loads(raw_line) + except json.JSONDecodeError: + continue + try: + handle(req) + except Exception as e: + req_id = req.get("id") if isinstance(req, dict) else None + if req_id is not None: + send({"jsonrpc": "2.0", "id": req_id, + "error": {"code": -32603, "message": f"Internal error: {e}"}}) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/notification.py b/plugin/scripts/notification.py new file mode 100644 index 0000000000000000000000000000000000000000..19ce4cbf667e958751616d401a060d014f6a4dab --- /dev/null +++ b/plugin/scripts/notification.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +import sys +import json +import time +from datetime import datetime +from hook_utils import resolve_project, is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + notification_type = data.get("notification_type") or data.get("notificationType") + if notification_type != "permission_prompt": + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + + payload = { + "hookType": "notification", + "sessionId": session_id, + "project": resolve_project(data.get("cwd")), + "cwd": data.get("cwd") or "", + "timestamp": datetime.utcnow().isoformat() + "Z", + "data": { + "notification_type": notification_type, + "title": data.get("title"), + "message": data.get("message") + } + } + + api_call_bg("observe", payload) + time.sleep(0.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/post_tool_failure.py b/plugin/scripts/post_tool_failure.py new file mode 100644 index 0000000000000000000000000000000000000000..892e282396e038551b3f4e477000164c2d49d454 --- /dev/null +++ b/plugin/scripts/post_tool_failure.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +import sys +import json +import time +from datetime import datetime +from hook_utils import resolve_project, is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + if data.get("is_interrupt") or data.get("isInterrupt"): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + tool_name = data.get("tool_name") or data.get("toolName") + tool_input = data.get("tool_input") or data.get("toolArgs") + error = data.get("error") or data.get("errorMessage") + + def limit_str(val): + if not isinstance(val, str): + val = json.dumps(val or "") + return val[:4000] + + payload = { + "hookType": "post_tool_failure", + "sessionId": session_id, + "project": resolve_project(data.get("cwd")), + "cwd": data.get("cwd") or "", + "timestamp": datetime.utcnow().isoformat() + "Z", + "data": { + "tool_name": tool_name, + "tool_input": limit_str(tool_input), + "error": limit_str(error) + } + } + + api_call_bg("observe", payload) + # Allow background request to be flushed + time.sleep(0.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/post_tool_use.py b/plugin/scripts/post_tool_use.py new file mode 100644 index 0000000000000000000000000000000000000000..2b1b776d2e8b8b4f09d8348591165a0d40103a0f --- /dev/null +++ b/plugin/scripts/post_tool_use.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python +import sys +import json +import time +from datetime import datetime +from hook_utils import resolve_project, is_sdk_child, api_call_bg + +def is_base64_image(val): + if not isinstance(val, str): + return False + return ( + val.startswith("data:image/") or + val.startswith("iVBORw0KGgo") or + val.startswith("/9j/") + ) + +def extract_image_data(output): + if is_base64_image(output): + return output, "[image data extracted]" + + if isinstance(output, dict): + image_data = None + clean = {} + for k, v in output.items(): + if not image_data and is_base64_image(v): + image_data = v + clean[k] = "[image data extracted]" + else: + clean[k] = v + return image_data, clean + + return None, output + +def truncate(value, max_len): + if isinstance(value, str): + if len(value) > max_len: + return value[:max_len] + "\n[...truncated]" + return value + if isinstance(value, (dict, list)): + try: + serialized = json.dumps(value) + if len(serialized) > max_len: + return serialized[:max_len] + "...[truncated]" + return value + except Exception: + return str(value) + return value + +def get_tool_output(data): + if "tool_response" in data: + return data["tool_response"] + if "tool_output" in data: + return data["tool_output"] + result = data.get("tool_result") or data.get("toolResult") + if isinstance(result, dict): + return result.get("text_result_for_llm") or result.get("textResultForLlm") or result + return result + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + tool_name = data.get("tool_name") or data.get("toolName") + tool_input = data.get("tool_input") or data.get("toolArgs") + + raw_output = get_tool_output(data) + image_data, clean_output = extract_image_data(raw_output) + + payload = { + "hookType": "post_tool_use", + "sessionId": session_id, + "project": resolve_project(data.get("cwd")), + "cwd": data.get("cwd") or "", + "timestamp": datetime.utcnow().isoformat() + "Z", + "data": { + "tool_name": tool_name, + "tool_input": tool_input, + "tool_output": truncate(clean_output, 8000) + } + } + if image_data: + payload["data"]["image_data"] = image_data + + api_call_bg("observe", payload) + # Allow background request to be flushed + time.sleep(0.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/pre_compact.py b/plugin/scripts/pre_compact.py new file mode 100644 index 0000000000000000000000000000000000000000..a382c1b100736c45946853bbcd2411873649ad4d --- /dev/null +++ b/plugin/scripts/pre_compact.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +import sys +import os +import json +from hook_utils import resolve_project, is_sdk_child, api_call + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + project = resolve_project(data.get("cwd")) + + if os.environ.get("CLAUDE_MEMORY_BRIDGE") == "true": + api_call("claude-bridge/sync", {}, timeout=5.0) + + result = api_call("context", {"sessionId": session_id, "project": project, "budget": 1500}, timeout=5.0) + if result and result.get("context"): + sys.stdout.write(result["context"]) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/pre_tool_use.py b/plugin/scripts/pre_tool_use.py new file mode 100644 index 0000000000000000000000000000000000000000..b06c9d2e8750e1996e15efa3586bacbe566ee7e0 --- /dev/null +++ b/plugin/scripts/pre_tool_use.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +import sys +import os +import json +from hook_utils import resolve_project, is_sdk_child, api_call + +def main(): + inject_context = os.environ.get("AGENTMEMORY_INJECT_CONTEXT") == "true" + if not inject_context: + return + + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + tool_name = data.get("tool_name") or data.get("toolName") + if not isinstance(tool_name, str): + return + + normalized_tool = tool_name.lower() + file_tools = ["edit", "write", "create", "read", "view", "glob", "grep"] + if normalized_tool not in file_tools: + return + + raw_input = data.get("tool_input") or data.get("toolArgs") or {} + tool_input = raw_input if isinstance(raw_input, dict) else {} + + files = [] + file_keys = ["path", "file"] if normalized_tool == "grep" else ["file_path", "path", "file", "pattern"] + for key in file_keys: + val = tool_input.get(key) + if isinstance(val, str) and val.strip(): + files.append(val.strip()) + + if not files: + return + + terms = [] + if normalized_tool in ["grep", "glob"]: + pattern = tool_input.get("pattern") + if isinstance(pattern, str) and pattern.strip(): + terms.append(pattern.strip()) + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + project = data.get("project") or resolve_project(data.get("cwd")) + + payload = { + "sessionId": session_id, + "files": files, + "terms": terms, + "toolName": tool_name, + "project": project + } + + result = api_call("enrich", payload, timeout=2.0) + if result and result.get("context"): + sys.stdout.write(result["context"]) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/prompt_submit.py b/plugin/scripts/prompt_submit.py new file mode 100644 index 0000000000000000000000000000000000000000..52dda8844c0aa63ef517adbf12ee08c0093df646 --- /dev/null +++ b/plugin/scripts/prompt_submit.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +import sys +import json +import time +from datetime import datetime +from hook_utils import resolve_project, is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + cwd = data.get("cwd") or "" + project = resolve_project(cwd) + prompt = data.get("prompt") or data.get("userPrompt") or "" + + payload = { + "hookType": "prompt_submit", + "sessionId": session_id, + "project": project, + "cwd": cwd, + "timestamp": datetime.utcnow().isoformat() + "Z", + "data": { + "prompt": prompt + } + } + + api_call_bg("observe", payload) + # Allow background request to be flushed + time.sleep(0.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/session_end.py b/plugin/scripts/session_end.py new file mode 100644 index 0000000000000000000000000000000000000000..de5b1c68120b72d05f936751bb7cdd295d1f707e --- /dev/null +++ b/plugin/scripts/session_end.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +import sys +import os +import json +import time +from hook_utils import is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + + api_call_bg("session/end", {"sessionId": session_id}) + + if os.environ.get("CONSOLIDATION_ENABLED") == "true": + api_call_bg("crystals/auto", {"olderThanDays": 0}) + api_call_bg("consolidate-pipeline", {"tier": "all", "force": True}) + + if os.environ.get("CLAUDE_MEMORY_BRIDGE") == "true": + api_call_bg("claude-bridge/sync", {}) + + time.sleep(1.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/session_start.py b/plugin/scripts/session_start.py new file mode 100644 index 0000000000000000000000000000000000000000..c675ef337440360a58b4c45683b171d6d39baea7 --- /dev/null +++ b/plugin/scripts/session_start.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +import sys +import json +import time +from hook_utils import resolve_project, is_sdk_child, api_call, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or f"ses_{int(time.time() * 1000)}" + cwd = data.get("cwd") or "" + project = resolve_project(cwd) + + inject_context = "--inject" in sys.argv + import os + if os.environ.get("AGENTMEMORY_INJECT_CONTEXT") == "true": + inject_context = True + + payload = { + "sessionId": session_id, + "project": project, + "cwd": cwd + } + + if not inject_context: + # Run asynchronously and fail fast + api_call_bg("session/start", payload) + # Sleep briefly to let the background thread start socket send + time.sleep(0.1) + return + + # In synchronous mode, await and write context to stdout + result = api_call("session/start", payload, timeout=1.5) + if result and result.get("context"): + sys.stdout.write(result["context"]) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/stop.py b/plugin/scripts/stop.py new file mode 100644 index 0000000000000000000000000000000000000000..aabe90bc7d4796f34a4f8fdae7a84c7d4cd777dc --- /dev/null +++ b/plugin/scripts/stop.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +import sys +import json +import time +from hook_utils import is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + + api_call_bg("summarize", {"sessionId": session_id}) + api_call_bg("session/end", {"sessionId": session_id}) + + # Allow the background threads to start their socket sends + time.sleep(1.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/subagent_start.py b/plugin/scripts/subagent_start.py new file mode 100644 index 0000000000000000000000000000000000000000..5f5cdbef5bb2999089a94d340bffe9a8e09944ee --- /dev/null +++ b/plugin/scripts/subagent_start.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +import sys +import json +import time +from datetime import datetime +from hook_utils import resolve_project, is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + agent_id = data.get("agent_id") or data.get("agentName") + agent_type = data.get("agent_type") or data.get("agentDisplayName") or data.get("agentName") + + payload = { + "hookType": "subagent_start", + "sessionId": session_id, + "project": resolve_project(data.get("cwd")), + "cwd": data.get("cwd") or "", + "timestamp": datetime.utcnow().isoformat() + "Z", + "data": { + "agent_id": agent_id, + "agent_type": agent_type + } + } + + api_call_bg("observe", payload) + time.sleep(0.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/subagent_stop.py b/plugin/scripts/subagent_stop.py new file mode 100644 index 0000000000000000000000000000000000000000..e221565a05b1aaba97f2c9bdbae50818395940c6 --- /dev/null +++ b/plugin/scripts/subagent_stop.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +import sys +import json +import time +from datetime import datetime +from hook_utils import resolve_project, is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + agent_id = data.get("agent_id") or data.get("agentName") + agent_type = data.get("agent_type") or data.get("agentDisplayName") or data.get("agentName") + + last_msg = data.get("last_assistant_message") or "" + if isinstance(last_msg, str): + last_msg = last_msg[:4000] + else: + last_msg = "" + + payload = { + "hookType": "subagent_stop", + "sessionId": session_id, + "project": resolve_project(data.get("cwd")), + "cwd": data.get("cwd") or "", + "timestamp": datetime.utcnow().isoformat() + "Z", + "data": { + "agent_id": agent_id, + "agent_type": agent_type, + "last_message": last_msg + } + } + + api_call_bg("observe", payload) + time.sleep(0.5) + +if __name__ == "__main__": + main() diff --git a/plugin/scripts/task_completed.py b/plugin/scripts/task_completed.py new file mode 100644 index 0000000000000000000000000000000000000000..23eac7e53bdd26ca6e3781b7c695fb83be182b5a --- /dev/null +++ b/plugin/scripts/task_completed.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python +import sys +import json +import time +from datetime import datetime +from hook_utils import resolve_project, is_sdk_child, api_call_bg + +def main(): + try: + input_data = sys.stdin.read() + if not input_data: + return + data = json.loads(input_data) + except Exception: + return + + if is_sdk_child(data): + return + + session_id = data.get("session_id") or data.get("sessionId") or "unknown" + desc = data.get("task_description") or "" + if isinstance(desc, str): + desc = desc[:2000] + else: + desc = "" + + payload = { + "hookType": "task_completed", + "sessionId": session_id, + "project": resolve_project(data.get("cwd")), + "cwd": data.get("cwd") or "", + "timestamp": datetime.utcnow().isoformat() + "Z", + "data": { + "task_id": data.get("task_id"), + "task_subject": data.get("task_subject"), + "task_description": desc, + "teammate_name": data.get("teammate_name"), + "team_name": data.get("team_name") + } + } + + api_call_bg("observe", payload) + time.sleep(0.5) + +if __name__ == "__main__": + main() diff --git a/plugin/skills/_shared/TROUBLESHOOTING.md b/plugin/skills/_shared/TROUBLESHOOTING.md new file mode 100644 index 0000000000000000000000000000000000000000..ee082d0ceccc8784c89b4190924b111ba53e27b1 --- /dev/null +++ b/plugin/skills/_shared/TROUBLESHOOTING.md @@ -0,0 +1,38 @@ +# Troubleshooting agentmemory skills + +Shared recovery steps for all user-invocable agentmemory skills. Each skill's +Troubleshooting section points here instead of duplicating the block. + +## "MCP tool not available" + +If a `memory_*` MCP tool does not appear, the stdio MCP shim never started. +Walk these in order: + +1. Run `/plugin list` in the host and confirm `agentmemory` shows as enabled. +2. Restart the host. The plugin's `.mcp.json` is only read on startup, so a + freshly installed or re-enabled plugin will not register tools mid-session. +3. Check `/mcp` and confirm the `agentmemory` server shows a live connection. + +## REST fallback + +When the MCP tools stay unavailable but the daemon is running, call the REST +API directly: + +1. Set `AGENTMEMORY_URL` to the daemon base URL (default `http://localhost:3111`). +2. Add `Authorization: Bearer $AGENTMEMORY_SECRET` ONLY when `AGENTMEMORY_SECRET` + is set. The default localhost daemon is open and rejects a stray header. + +Endpoint map by skill: + +| Skill | REST call | +| --------------- | --------------------------------------------------------------- | +| remember | `POST /agentmemory/remember` | +| recall | `POST /agentmemory/smart-search` | +| recap | `GET /agentmemory/sessions` + `POST /agentmemory/smart-search` | +| handoff | `GET /agentmemory/sessions` + `POST /agentmemory/smart-search` | +| session-history | `GET /agentmemory/sessions` | +| commit-context | `GET /agentmemory/session/by-commit?sha=` | +| commit-history | `GET /agentmemory/commits` (URL-encode every query param) | + +The daemon reads `.mcp.json` on startup only, so any port or auth change needs a +restart before either transport sees it. diff --git a/plugin/skills/agentmemory-agents/REFERENCE.md b/plugin/skills/agentmemory-agents/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..7be767134a15a143530a968929562c603a344a10 --- /dev/null +++ b/plugin/skills/agentmemory-agents/REFERENCE.md @@ -0,0 +1,27 @@ +# agentmemory connect adapters reference + +Generated from `src/cli/connect/index.ts`. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing an adapter. + + +`agentmemory connect ` wires the memory server into a host agent. 17 adapters: + +| Agent | Name | Protocol | +| --- | --- | --- | +| Antigravity | `antigravity` | Using MCP via mcp_config.json. Antigravity replaces Gemini CLI (sunset 2026-06-18). | +| Claude Code | `claude-code` | Using MCP. Hooks are also available, see docs/claude-code.md. | +| Cline | `cline` | Using MCP via ~/.cline/mcp.json (CLI). VS Code users: add the same block via Cline Settings → MCP Servers → Edit JSON. | +| Codex CLI | `codex` | Using MCP. Hooks ship via the Codex plugin; on Codex Desktop, also pass --with-hooks to install the global hooks.json workaround for openai/codex#16430. | +| Continue | `continue` | Using MCP via ~/.continue/config.yaml (preferred) or config.json (legacy, only when no yaml). | +| GitHub Copilot CLI | `copilot-cli` | Using MCP. Install the plugin too for full hooks/skills coverage. | +| Cursor | `cursor` | Using MCP (the only protocol Cursor speaks). Memory bridge runs at :3111 underneath. | +| Droid (Factory.ai) | `droid` | Using MCP via ~/.factory/mcp.json. The `/mcp` slash command inside droid lists configured servers. | +| Gemini CLI | `gemini-cli` | Using MCP (the only protocol Gemini CLI speaks). Memory bridge runs at :3111 underneath. | +| Hermes Agent | `hermes` | Using MCP. Hooks are also available, see docs/hermes.md. | +| Kiro | `kiro` | Using MCP via ~/.kiro/settings/mcp.json (user-level). Workspace overrides live in .kiro/settings/mcp.json. | +| OpenClaw | `openclaw` | Using MCP. Hooks are also available, see docs/openclaw.md. | +| OpenHuman | `openhuman` | Using native hooks (REST API at :3111). MCP not required. | +| pi | `pi` | Using native hooks (REST API at :3111). MCP not required. | +| Qwen Code | `qwen` | Using MCP via ~/.qwen/settings.json. Qwen Code's hook system can also be wired separately, see docs. | +| Warp | `warp` | Using MCP via ~/.warp/.mcp.json. Skills auto-discover from .claude/skills/ if the Claude Code plugin is also installed. | +| Zed | `zed` | Using MCP via ~/.config/zed/settings.json (key: context_servers). | + diff --git a/plugin/skills/agentmemory-agents/SKILL.md b/plugin/skills/agentmemory-agents/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..e4cda491580da7006c485315a9f9cbb864cf5e43 --- /dev/null +++ b/plugin/skills/agentmemory-agents/SKILL.md @@ -0,0 +1,34 @@ +--- +name: agentmemory-agents +description: How agentmemory wires into host coding agents via the connect command. Use when installing agentmemory into a specific agent, when asked which agents are supported, or when a connect adapter writes the wrong config path. +user-invocable: false +--- + +`agentmemory connect ` merges the memory server into a host agent's config and preserves any existing servers. REST is the underlying protocol; for MCP-only hosts the adapter wires the stdio MCP bridge. + +## Quick start + +```bash +agentmemory connect claude-code # or cursor, codex, gemini-cli, ... +``` + +After wiring, restart the host or run its MCP reload (for example `/mcp` in Claude Code) so it picks up the server. Then confirm the agent lists agentmemory's tools. + +## Workflow + +1. Detect the calling agent. If unknown, default to `claude-code`. +2. Run `agentmemory connect ` using a name from the table in REFERENCE.md. +3. Verify: the host should show the full tool set with a server running. Only 7 tools means the MCP shim could not reach a server (see ../_shared/TROUBLESHOOTING.md). + +## Notes + +- The action skills (remember, recall, and the rest) are installed separately with `npx skills add rohitg00/agentmemory`. `connect` makes tools available; skills teach the agent when to use them. +- Windows: use WSL2. Native Windows runs the server but `connect` is not supported there. + +## See also + +- agentmemory-mcp-tools, agentmemory-rest-api, agentmemory-hooks. + +## Reference + +The full adapter list with display names and protocol notes lives in REFERENCE.md, generated from `src/cli/connect/`. diff --git a/plugin/skills/agentmemory-architecture/SKILL.md b/plugin/skills/agentmemory-architecture/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..431c26031a7c521b9c7d175a11ef1de964cc7033 --- /dev/null +++ b/plugin/skills/agentmemory-architecture/SKILL.md @@ -0,0 +1,33 @@ +--- +name: agentmemory-architecture +description: How agentmemory is built, the iii engine primitives it runs on, its storage model, ports, and the viewer. Use when reasoning about how memory is stored or retrieved end to end, when extending the system, or when answering how agentmemory works under the hood. +user-invocable: false +--- + +agentmemory is a memory server for coding agents. It runs locally, captures observations, indexes them for hybrid retrieval, and serves them back over REST and MCP. It is built on the iii engine. + +## iii primitives + +Everything is a function, a trigger, or worker state on the iii engine. There is no separate plugin system; the worker registers functions (`mem::*`) and HTTP triggers (`api::*`) and the engine routes calls. agentmemory does not bypass iii; new capability is a new function plus a trigger. + +## Retrieval model + +Recall is hybrid: BM25 keyword search plus vector similarity plus graph expansion over linked concepts. The default install needs no API key because embeddings run on-device and BM25 needs none. An LLM provider only adds richer summaries and auto-injection, both opt-in. + +## Storage and lifecycle + +Memories carry content, concepts, files, importance, and timestamps, grouped into sessions and optionally linked to commits. A lifecycle of capture, compress, consolidate, and forget keeps the store useful over time rather than letting it grow unbounded. + +## Ports + +REST is the anchor at 3111. Streams = N+1 (3112), viewer = N+2 (3113), engine = N+46023 (49134). `--instance N` shifts the whole block by N*100. + +## Viewer + +A real-time web viewer at `http://localhost:3113` shows memory building as sessions run. Useful for demos and for confirming capture is working. + +## See also + +- agentmemory-mcp-tools and agentmemory-rest-api for the surfaces. +- agentmemory-hooks for automatic capture. +- agentmemory-config for ports and feature flags. diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..08c873a44460b0c1da30c120644a351b22594be2 --- /dev/null +++ b/plugin/skills/agentmemory-config/REFERENCE.md @@ -0,0 +1,42 @@ +# agentmemory configuration reference + +Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded. + + +Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 34 recognized variables: + +- `AGENTMEMORY_AGENT_SCOPE` +- `AGENTMEMORY_ALLOW_AGENT_SDK` +- `AGENTMEMORY_AUTO_COMPRESS` +- `AGENTMEMORY_COMMIT_SHA` +- `AGENTMEMORY_COPILOT_MCP_BLOCK` +- `AGENTMEMORY_CWD` +- `AGENTMEMORY_DEBUG` +- `AGENTMEMORY_DROP_STALE_INDEX` +- `AGENTMEMORY_EXPORT_ROOT` +- `AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS` +- `AGENTMEMORY_FORCE_PROXY` +- `AGENTMEMORY_GRAPH_WEIGHT` +- `AGENTMEMORY_III_CONFIG` +- `AGENTMEMORY_III_VERSION` +- `AGENTMEMORY_IMAGE_EMBEDDINGS` +- `AGENTMEMORY_IMAGE_STORE_MAX_BYTES` +- `AGENTMEMORY_INJECT_CONTEXT` +- `AGENTMEMORY_LLM_TIMEOUT_MS` +- `AGENTMEMORY_MCP_BLOCK` +- `AGENTMEMORY_PROBE_TIMEOUT_MS` +- `AGENTMEMORY_PROJECT_NAME` +- `AGENTMEMORY_PROVIDER` +- `AGENTMEMORY_REFLECT` +- `AGENTMEMORY_SDK_CHILD` +- `AGENTMEMORY_SECRET` +- `AGENTMEMORY_SESSION_ID` +- `AGENTMEMORY_SLOTS` +- `AGENTMEMORY_SUPPRESS_COST_WARNING` +- `AGENTMEMORY_TOOLS` +- `AGENTMEMORY_URL` +- `AGENTMEMORY_USE_DOCKER` +- `AGENTMEMORY_VERBOSE` +- `AGENTMEMORY_VIEWER_HOST` +- `AGENTMEMORY_VIEWER_URL` + diff --git a/plugin/skills/agentmemory-config/SKILL.md b/plugin/skills/agentmemory-config/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..aea78c9bab2d3e0d1c3da04e594753ad209936c6 --- /dev/null +++ b/plugin/skills/agentmemory-config/SKILL.md @@ -0,0 +1,37 @@ +--- +name: agentmemory-config +description: agentmemory configuration, environment variables, ports, and feature flags. Use when enabling a feature, changing ports, setting an API key, configuring auth, or explaining why a feature is off by default. +user-invocable: false +--- + +agentmemory reads configuration from the environment and from `~/.agentmemory/.env` (one `KEY=value` per line, no `export` prefix). Restart the server after changing it. + +## Quick start + +Enable richer memory and set a provider key in `~/.agentmemory/.env`: + +```env +ANTHROPIC_API_KEY=sk-ant-... +AGENTMEMORY_AUTO_COMPRESS=true +AGENTMEMORY_INJECT_CONTEXT=true +``` + +## Defaults worth knowing + +- No API key is required. Without one, agentmemory runs zero-LLM with BM25 plus local embeddings. +- Token-spending features ship OFF on purpose: `AGENTMEMORY_AUTO_COMPRESS` (LLM summaries) and `AGENTMEMORY_INJECT_CONTEXT` (auto context injection) both cost tokens proportional to tool-use frequency. +- Tool visibility: `AGENTMEMORY_TOOLS=all` (default) or `core` for the lean set. +- Auth: set `AGENTMEMORY_SECRET` to require `Authorization: Bearer` on the REST API. + +## Ports + +REST is the anchor at 3111. Streams = N+1 (3112), viewer = N+2 (3113), engine = N+46023 (49134). Relocate the whole block with `--port ` or `--instance `. + +## See also + +- agentmemory-rest-api for how the secret is used. +- agentmemory-architecture for the port quartet rationale. + +## Reference + +The full recognized-variable list lives in REFERENCE.md, generated by scanning `src/`. diff --git a/plugin/skills/agentmemory-hooks/REFERENCE.md b/plugin/skills/agentmemory-hooks/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..2cf2dcec7da84b7ad4dd1b2fd404a495b780d77e --- /dev/null +++ b/plugin/skills/agentmemory-hooks/REFERENCE.md @@ -0,0 +1,20 @@ +# agentmemory hooks reference + +Generated from `plugin/hooks/hooks.json`. Do not edit the block below by hand; run `npm run skills:gen` after changing the hook registration. + + +The Claude Code plugin registers hooks on 12 lifecycle events to capture observations automatically: + +- `Notification` +- `PostToolUse` +- `PostToolUseFailure` +- `PreCompact` +- `PreToolUse` +- `SessionEnd` +- `SessionStart` +- `Stop` +- `SubagentStart` +- `SubagentStop` +- `TaskCompleted` +- `UserPromptSubmit` + diff --git a/plugin/skills/agentmemory-hooks/SKILL.md b/plugin/skills/agentmemory-hooks/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b8127f3feaff5d3748074cc206e66323a1b84d96 --- /dev/null +++ b/plugin/skills/agentmemory-hooks/SKILL.md @@ -0,0 +1,39 @@ +--- +name: agentmemory-hooks +description: The agentmemory plugin hooks that capture observations automatically across the agent session lifecycle. Use when explaining how memory gets captured without manual saves, when debugging missing observations, or when tuning what gets recorded. +user-invocable: false +--- + +The Claude Code plugin registers lifecycle hooks so memory is captured automatically. You do not have to call `memory_save` for routine work; the hooks observe tool use, prompts, and session boundaries and write observations for you. + +## Quick start + +Install the plugin and the hooks register themselves: + +```bash +/plugin marketplace add rohitg00/agentmemory +/plugin install agentmemory +``` + +Watch observations land live at `http://localhost:3113`. + +## What the hooks do + +- Session start and end frame each unit of work and let `handoff` resume it. +- Tool-use hooks capture what changed and why, the raw material for `recall` and `recap`. +- Prompt-submit captures intent. Pre-compact preserves context before the host trims it. +- A post-commit hook links commits to sessions, which powers `commit-context` and `commit-history`. + +## Important + +- Capture is on by default and is zero-LLM. Turning observations into LLM summaries (`AGENTMEMORY_AUTO_COMPRESS`) and injecting them back into context (`AGENTMEMORY_INJECT_CONTEXT`) are separate opt-ins because they spend tokens. +- If observations are missing, confirm the plugin is enabled and the server is running. See ../_shared/TROUBLESHOOTING.md. + +## See also + +- agentmemory-config for the capture and injection flags. +- The handoff, recap, and session-history skills consume what these hooks record. + +## Reference + +The exact registered hook events live in REFERENCE.md, generated from `plugin/hooks/hooks.json`. diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..0c556fc77feb95efc267d3f0bf283e8b226f9496 --- /dev/null +++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md @@ -0,0 +1,65 @@ +# agentmemory MCP tools reference + +Generated from `src/mcp/tools-registry.ts`. Do not edit the block below by hand; run `npm run skills:gen` after changing the registry. + + +agentmemory exposes 53 MCP tools. 8 are in the lean core set (`--tools core` or `AGENTMEMORY_TOOLS=core`); the rest load with `--tools all` (default). + +| Tool | Core | Parameters | Purpose | +| --- | --- | --- | --- | +| `memory_action_create` | | `title`*: string, `description`: string, `priority`: number, `project`: string, `tags`: string, `parentId`: string, `requires`: string | Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other. | +| `memory_action_update` | | `actionId`*: string, `status`: string, `result`: string, `priority`: number | Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions. | +| `memory_audit` | | `operation`: string, `limit`: number | View the audit trail of memory operations. | +| `memory_checkpoint` | | `operation`*: string, `name`: string, `checkpointId`: string, `status`: string, `type`: string, `linkedActionIds`: string | Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress. | +| `memory_claude_bridge_sync` | | `direction`*: string | Sync memory state to/from Claude Code's native MEMORY.md file. | +| `memory_commit_lookup` | | `sha`*: string | Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions. | +| `memory_commits` | | `branch`: string, `repo`: string, `limit`: number | List recent commits linked to agent sessions, optionally filtered by branch or repo. | +| `memory_compress_file` | | `filePath`*: string | Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing. | +| `memory_consolidate` | yes | `tier`: string | Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural). | +| `memory_crystallize` | | `actionIds`*: string, `project`: string, `sessionId`: string | Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons. | +| `memory_diagnose` | yes | `categories`: string | Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state. | +| `memory_export` | | none | Export all memory data as JSON. | +| `memory_facet_query` | | `matchAll`: string, `matchAny`: string, `targetType`: string | Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend. | +| `memory_facet_tag` | | `targetId`*: string, `targetType`*: string, `dimension`*: string, `value`*: string | Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization. | +| `memory_file_history` | | `files`*: string, `sessionId`: string | Get past observations about specific files. | +| `memory_frontier` | | `project`: string, `agentId`: string, `limit`: number | Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies. | +| `memory_governance_delete` | | `memoryIds`*: string, `reason`: string | Delete specific memories with audit trail. | +| `memory_graph_query` | | `startNodeId`: string, `nodeType`: string, `maxDepth`: number, `query`: string | Query the knowledge graph for entities and relationships. | +| `memory_heal` | | `categories`: string, `dryRun`: string | Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data. | +| `memory_insight_list` | | `project`: string, `minConfidence`: number, `limit`: number | List synthesized insights, higher-order observations derived from patterns across memories, lessons, and crystals. | +| `memory_lease` | | `actionId`*: string, `agentId`*: string, `operation`*: string, `result`: string, `ttlMs`: number | Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing. | +| `memory_lesson_recall` | | `query`*: string, `project`: string, `minConfidence`: number, `limit`: number | Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions. | +| `memory_lesson_save` | yes | `content`*: string, `context`: string, `confidence`: number, `project`: string, `tags`: string | 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. | +| `memory_mesh_sync` | | `peerId`: string, `direction`: string | Sync memories and actions with peer agentmemory instances for multi-agent collaboration. | +| `memory_next` | | `project`: string, `agentId`: string | Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score. | +| `memory_obsidian_export` | | `vaultDir`: string, `types`: string | Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view. | +| `memory_patterns` | | `project`: string | Detect recurring patterns across sessions. | +| `memory_profile` | | `project`*: string, `refresh`: string | User/project profile with top concepts and file patterns. | +| `memory_recall` | yes | `query`*: string, `limit`: number, `format`: string, `token_budget`: number | 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. | +| `memory_reflect` | yes | `project`: string, `maxClusters`: number | Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights. | +| `memory_relations` | | `memoryId`*: string, `maxHops`: number, `minConfidence`: number | Query the memory relationship graph. | +| `memory_routine_run` | | `routineId`*: string, `project`: string, `initiatedBy`: string | Instantiate a frozen workflow routine, creating actions for each step with proper dependencies. | +| `memory_save` | yes | `content`*: string, `type`: string, `concepts`: string, `files`: string, `project`: string | Explicitly save an important insight, decision, or pattern to long-term memory. | +| `memory_sentinel_create` | | `name`*: string, `type`*: string, `config`: string, `linkedActionIds`: string, `expiresInMs`: number | Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered. | +| `memory_sentinel_trigger` | | `sentinelId`*: string, `result`: string | Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions. | +| `memory_sessions` | yes | none | List recent sessions with their status and observation counts. | +| `memory_signal_read` | | `agentId`*: string, `unreadOnly`: string, `threadId`: string, `limit`: number | Read messages for an agent. Marks delivered messages as read. | +| `memory_signal_send` | | `from`*: string, `to`: string, `content`*: string, `type`: string, `replyTo`: string | Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration. | +| `memory_sketch_create` | | `title`*: string, `description`: string, `expiresInMs`: number, `project`: string | Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded. | +| `memory_sketch_promote` | | `sketchId`*: string, `project`: string | Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official. | +| `memory_slot_append` | | `label`*: string, `text`*: string | 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. | +| `memory_slot_create` | | `label`*: string, `content`: string, `sizeLimit`: number, `description`: string, `pinned`: string, `scope`: string | Create a new slot. Reject if a slot with the same label already exists. | +| `memory_slot_delete` | | `label`*: string | Delete a slot. Seeded default slots can be deleted unless marked readOnly. | +| `memory_slot_get` | | `label`*: string | Read a single slot by label. | +| `memory_slot_list` | | none | List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions. | +| `memory_slot_replace` | | `label`*: string, `content`*: string | Replace slot content in place. Fails if content exceeds sizeLimit. | +| `memory_smart_search` | yes | `query`*: string, `expandIds`: string, `limit`: number | Hybrid semantic+keyword search with progressive disclosure. | +| `memory_snapshot_create` | | `message`: string | Create a git-versioned snapshot of current memory state. | +| `memory_team_feed` | | `limit`: number | Get recent shared items from all team members. | +| `memory_team_share` | | `itemId`*: string, `itemType`*: string | Share a memory or observation with team members. | +| `memory_timeline` | | `anchor`*: string, `project`: string, `before`: number, `after`: number | Chronological observations around an anchor point. | +| `memory_verify` | | `id`*: string | Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores. | +| `memory_vision_search` | | `queryText`: string, `queryImageRef`: string, `queryImageBase64`: string, `topK`: number, `sessionId`: string | 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. | + +`*` marks required parameters. + diff --git a/plugin/skills/agentmemory-mcp-tools/SKILL.md b/plugin/skills/agentmemory-mcp-tools/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..00445ef3b4d3566a42682397d69e64a0d38ba7db --- /dev/null +++ b/plugin/skills/agentmemory-mcp-tools/SKILL.md @@ -0,0 +1,39 @@ +--- +name: agentmemory-mcp-tools +description: Map of every agentmemory MCP tool, what each does, and its parameters. Use when choosing which memory tool to call, when a tool name or argument is unclear, or when answering what agentmemory can do via MCP. +user-invocable: false +--- + +agentmemory exposes its full capability set as MCP tools. This skill is the index: it tells you which tool to reach for and where to find exact parameters. + +## Quick start + +Save then recall: + +1. `memory_save` with `content` (the insight), `concepts` (comma-separated keywords), `files` (comma-separated paths). +2. `memory_smart_search` with `query` and `limit` to retrieve it later. This runs hybrid BM25 plus vector plus graph-expanded search. + +## Tool families + +- Capture: `memory_save`, `memory_observe` flows, `memory_compress_file`. +- Retrieve: `memory_smart_search`, `memory_recall`, `memory_file_history`, `memory_timeline`, `memory_vision_search`. +- Sessions and commits: `memory_sessions`, `memory_commits`, `memory_commit_lookup`. +- Knowledge and graph: `memory_lesson_save`, `memory_lesson_recall`, `memory_graph_query`, `memory_relations`, `memory_patterns`, `memory_crystallize`. +- Structured slots: `memory_slot_create`, `memory_slot_append`, `memory_slot_get`, `memory_slot_list`, `memory_slot_replace`, `memory_slot_delete`. +- Governance and health: `memory_governance_delete`, `memory_audit`, `memory_verify`, `memory_heal`, `memory_diagnose`. + +## Workflow + +1. Pick the narrowest tool for the task. Prefer `memory_smart_search` for open recall, `memory_recall` when you already have a focused query, `memory_sessions` for session listings. +2. Look up exact parameter names and which are required in REFERENCE.md before calling. +3. Pass only documented fields. REST handlers whitelist fields and drop unknown ones. + +## See also + +- agentmemory-rest-api for the HTTP equivalents. +- agentmemory-config for tool-visibility and feature flags. +- The user-invocable action skills (remember, recall, recap, handoff, forget) wrap the most common tools. + +## Reference + +Full tool table with parameters and the core-set marking lives in REFERENCE.md, generated from source so it never drifts. diff --git a/plugin/skills/agentmemory-rest-api/REFERENCE.md b/plugin/skills/agentmemory-rest-api/REFERENCE.md new file mode 100644 index 0000000000000000000000000000000000000000..d36171defe5cdcd6692bd799bbb14e3eda77a44f --- /dev/null +++ b/plugin/skills/agentmemory-rest-api/REFERENCE.md @@ -0,0 +1,129 @@ +# agentmemory REST API reference + +Generated from `src/triggers/api.ts`. Do not edit the block below by hand; run `npm run skills:gen` after changing the registered endpoints. + + +The REST API is the primary surface. All paths are under `http://localhost:3111` (override with `--port`). When `AGENTMEMORY_SECRET` is set, send `Authorization: Bearer $AGENTMEMORY_SECRET`; localhost is otherwise open. + +117 registered endpoints: + +| Method | Path | +| --- | --- | +| POST | `/agentmemory/actions` | +| POST | `/agentmemory/actions/edges` | +| GET | `/agentmemory/actions/get` | +| POST | `/agentmemory/actions/update` | +| GET | `/agentmemory/audit` | +| POST | `/agentmemory/auto-forget` | +| GET | `/agentmemory/branch/detect` | +| GET | `/agentmemory/branch/sessions` | +| GET | `/agentmemory/branch/worktrees` | +| POST | `/agentmemory/cascade-update` | +| POST | `/agentmemory/checkpoints` | +| POST | `/agentmemory/checkpoints/resolve` | +| GET | `/agentmemory/claude-bridge/read` | +| POST | `/agentmemory/claude-bridge/sync` | +| GET | `/agentmemory/commits` | +| POST | `/agentmemory/compress-file` | +| GET | `/agentmemory/config/flags` | +| POST | `/agentmemory/consolidate` | +| POST | `/agentmemory/consolidate-pipeline` | +| POST | `/agentmemory/context` | +| GET | `/agentmemory/crystals` | +| POST | `/agentmemory/crystals/auto` | +| POST | `/agentmemory/crystals/create` | +| POST | `/agentmemory/diagnostics` | +| GET | `/agentmemory/diagnostics/followup` | +| POST | `/agentmemory/diagnostics/heal` | +| POST | `/agentmemory/enrich` | +| POST | `/agentmemory/evict` | +| POST | `/agentmemory/evolve` | +| GET | `/agentmemory/export` | +| POST | `/agentmemory/facets` | +| POST | `/agentmemory/facets/query` | +| POST | `/agentmemory/facets/remove` | +| GET | `/agentmemory/facets/stats` | +| POST | `/agentmemory/file-context` | +| POST | `/agentmemory/flow/compress` | +| POST | `/agentmemory/forget` | +| GET | `/agentmemory/frontier` | +| POST | `/agentmemory/generate-rules` | +| POST | `/agentmemory/governance/bulk-delete` | +| DELETE | `/agentmemory/governance/memories` | +| POST | `/agentmemory/graph/build` | +| POST | `/agentmemory/graph/extract` | +| POST | `/agentmemory/graph/query` | +| POST | `/agentmemory/graph/reset` | +| POST | `/agentmemory/graph/snapshot-rebuild` | +| GET | `/agentmemory/graph/stats` | +| GET | `/agentmemory/health` | +| POST | `/agentmemory/import` | +| GET | `/agentmemory/insights` | +| POST | `/agentmemory/insights/search` | +| POST | `/agentmemory/leases/acquire` | +| POST | `/agentmemory/leases/release` | +| POST | `/agentmemory/leases/renew` | +| POST | `/agentmemory/lessons` | +| POST | `/agentmemory/lessons/search` | +| POST | `/agentmemory/lessons/strengthen` | +| GET | `/agentmemory/livez` | +| GET | `/agentmemory/memories` | +| GET | `/agentmemory/memories/:id` | +| GET | `/agentmemory/mesh/export` | +| POST | `/agentmemory/mesh/peers` | +| POST | `/agentmemory/mesh/receive` | +| POST | `/agentmemory/mesh/sync` | +| POST | `/agentmemory/migrate` | +| GET | `/agentmemory/next` | +| GET | `/agentmemory/observations` | +| POST | `/agentmemory/observe` | +| POST | `/agentmemory/obsidian/export` | +| POST | `/agentmemory/patterns` | +| GET | `/agentmemory/procedural` | +| GET | `/agentmemory/profile` | +| POST | `/agentmemory/reflect` | +| POST | `/agentmemory/relations` | +| POST | `/agentmemory/remember` | +| POST | `/agentmemory/replay/import-jsonl` | +| GET | `/agentmemory/replay/load` | +| GET | `/agentmemory/replay/sessions` | +| POST | `/agentmemory/routines` | +| POST | `/agentmemory/routines/run` | +| GET | `/agentmemory/routines/status` | +| POST | `/agentmemory/search` | +| GET | `/agentmemory/semantic` | +| POST | `/agentmemory/sentinels` | +| POST | `/agentmemory/sentinels/cancel` | +| POST | `/agentmemory/sentinels/check` | +| POST | `/agentmemory/sentinels/trigger` | +| GET | `/agentmemory/session/by-commit` | +| POST | `/agentmemory/session/commit` | +| POST | `/agentmemory/session/end` | +| POST | `/agentmemory/session/start` | +| GET | `/agentmemory/sessions` | +| GET | `/agentmemory/signals` | +| POST | `/agentmemory/signals/send` | +| POST | `/agentmemory/sketches` | +| POST | `/agentmemory/sketches/add` | +| POST | `/agentmemory/sketches/discard` | +| POST | `/agentmemory/sketches/gc` | +| POST | `/agentmemory/sketches/promote` | +| GET | `/agentmemory/slot` | +| POST | `/agentmemory/slot/append` | +| POST | `/agentmemory/slot/reflect` | +| POST | `/agentmemory/slot/replace` | +| GET | `/agentmemory/slots` | +| POST | `/agentmemory/smart-search` | +| POST | `/agentmemory/snapshot/create` | +| POST | `/agentmemory/snapshot/restore` | +| GET | `/agentmemory/snapshots` | +| POST | `/agentmemory/summarize` | +| GET | `/agentmemory/team/feed` | +| GET | `/agentmemory/team/profile` | +| POST | `/agentmemory/team/share` | +| POST | `/agentmemory/timeline` | +| POST | `/agentmemory/verify` | +| GET | `/agentmemory/viewer` | +| POST | `/agentmemory/vision-embed` | +| POST | `/agentmemory/vision-search` | + diff --git a/plugin/skills/agentmemory-rest-api/SKILL.md b/plugin/skills/agentmemory-rest-api/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..898e94a6af5281a8c55e9ab31c93beed40745a4a --- /dev/null +++ b/plugin/skills/agentmemory-rest-api/SKILL.md @@ -0,0 +1,43 @@ +--- +name: agentmemory-rest-api +description: The agentmemory HTTP REST API surface, the primary protocol for talking to the memory server. Use when calling agentmemory over HTTP, when MCP is unavailable and you need a fallback, or when integrating a host that does not speak MCP. +user-invocable: false +--- + +REST is agentmemory's primary surface. MCP is a bridge on top of it. Every memory operation has an HTTP endpoint under `http://localhost:3111/agentmemory/*`. + +## Quick start + +```bash +# liveness +curl -fsS http://localhost:3111/agentmemory/livez + +# save +curl -X POST http://localhost:3111/agentmemory/remember \ + -H "Content-Type: application/json" \ + -d '{"content":"chose JWT refresh rotation","concepts":["jwt-refresh-rotation"]}' + +# recall +curl -X POST http://localhost:3111/agentmemory/smart-search \ + -H "Content-Type: application/json" \ + -d '{"query":"auth token strategy","limit":5}' +``` + +## Auth + +By default localhost is open and no auth is needed. When `AGENTMEMORY_SECRET` is set, every request needs `Authorization: Bearer $AGENTMEMORY_SECRET`. See agentmemory-config. + +## Conventions + +- Save returns `201`, reads return `200`, validation errors return `400`. +- Handlers whitelist body fields and drop unknown ones, so passing extra keys is safe but ignored. +- The port is configurable with `--port` or `--instance`; streams, viewer, and engine derive from it. + +## See also + +- agentmemory-mcp-tools for the MCP equivalents. +- agentmemory-config for the port quartet and the secret. + +## Reference + +The full endpoint list with methods lives in REFERENCE.md, generated from `src/triggers/api.ts`. diff --git a/plugin/skills/commit-context/EXAMPLES.md b/plugin/skills/commit-context/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..a0fe52cb80027cc39b82f4592c443c90a1845c92 --- /dev/null +++ b/plugin/skills/commit-context/EXAMPLES.md @@ -0,0 +1,71 @@ +# commit-context worked examples + +## 1. Line range with a linked session + +User: "Why is this retry loop here?" (pointing at lines 40-52 of refresh.ts) + +Find the SHA: + +```bash +git blame -L 40,52 src/auth/refresh.ts +# 9a1b2c3d (dev 2026-06-07) ... retry on revoked token +``` + +Look it up: + +```json +memory_commit_lookup { "sha": "9a1b2c3d4e5f60718293a4b5c6d7e8f901234567" } +``` + +Response: + +```json +{ + "commit": { "sha": "9a1b2c3d...", "short": "9a1b2c3", "branch": "main", + "author": "dev", "message": "rotate refresh tokens" }, + "sessions": [ { "id": "7f3a9c21", "project": "app", "observationCount": 14, + "summary": "Reworked refresh rotation" } ] +} +``` + +Present: + +> `9a1b2c3` on `main` by dev: "rotate refresh tokens". Linked to session +> `7f3a9c2` "Auth refresh rework" (14 obs). The retry loop handles a token +> revoked mid-flight, per the session's high-importance observations. + +## 2. Function lookup, commit predates linking + +User: "What was the agent doing when it wrote validateScope?" + +```bash +git log -L :validateScope:src/auth/scope.ts -n 1 +# 1122aabb ... +``` + +```json +memory_commit_lookup { "sha": "1122aabbccddeeff00112233445566778899aabb" } +``` + +Response: + +```json +{ "commit": null } +``` + +Present: + +> `1122aab` predates agent session linking, so there is no recorded session. +> From `git show`: it added `validateScope` to enforce per-token scopes. I can +> show the full diff if useful. + +## 3. Bare path + +User: "Give me context on src/middleware/limit.ts." + +```bash +git log -n 1 -- src/middleware/limit.ts +``` + +Take the SHA, run `memory_commit_lookup`, present commit plus linked session in +the same shape as example 1. diff --git a/plugin/skills/commit-context/SKILL.md b/plugin/skills/commit-context/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..fa782ef5aac466bcb3aad1e60c423e1030ff31b2 --- /dev/null +++ b/plugin/skills/commit-context/SKILL.md @@ -0,0 +1,64 @@ +--- +name: commit-context +description: Trace a file, function, or line back to the agent session that produced its current commit. Use when the user asks "why is this code here", "what was the agent doing when this changed", "who wrote this", or wants context on a specific location in the codebase. +argument-hint: "[file, function, or line]" +user-invocable: true +--- + +The user wants commit context for: $ARGUMENTS + +## Quick start + +```bash +git blame -L 40,52 src/auth/refresh.ts # -> SHA 9a1b2c3d +``` + +```json +memory_commit_lookup { "sha": "9a1b2c3d4e5f60718293a4b5c6d7e8f901234567" } +``` + +Expected output: + +```text +9a1b2c3 on main by dev: "rotate refresh tokens" +Linked session 7f3a9c2 "Auth refresh rework", 14 obs. +``` + +## Why + +Report only what git and the lookup return. When the lookup gives `commit: null`, +the commit predates session linking; do not invent intent. + +## Workflow + +1. Find the SHA: `git blame -L , ` for a line range; + `git log -L ::` for a function; `git log -n 1 -- ` for a + bare path. +2. Look it up: `memory_commit_lookup { "sha": "" }`. +3. Present the commit (sha, short sha, branch, author, message), the linked + session(s) (id, project, started/ended, observation count, summary), and the + importance >= 7 observations via `memory_recall` when available. + +## Anti-patterns + +WRONG: lookup returns `{ "commit": null }`, you narrate "the agent was +refactoring auth" from the diff alone. + +RIGHT: "This commit predates session linking, so there is no recorded agent +session. From `git show`: it changed token rotation in refresh.ts." + +## Checklist + +- SHA came from git blame/log, not a guess. +- `commit: null` reported as "predates linking", no fabricated session. +- Session details quote the lookup response verbatim. +- No intent claimed beyond what observations state. + +## See also + +- `commit-history`: list many agent-linked commits at once. +- `recall`: dig deeper into the linked session's observations. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_commit_lookup` is not available. diff --git a/plugin/skills/commit-history/EXAMPLES.md b/plugin/skills/commit-history/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..d04a6bb6a1786d03697e0023f4f775a345d35bc7 --- /dev/null +++ b/plugin/skills/commit-history/EXAMPLES.md @@ -0,0 +1,71 @@ +# commit-history worked examples + +## 1. Branch filter + +User: "Show agent commits on main." + +Invocation: + +```json +memory_commits { "branch": "main", "limit": 100 } +``` + +Response: + +```json +{ + "commits": [ + { "short": "9a1b2c3", "branch": "main", "authoredAt": "2026-06-07T09:12:00Z", + "message": "rotate refresh tokens", "sessionIds": ["7f3a9c21"], + "observationCount": 14, "files": 3 }, + { "short": "b21d004", "branch": "main", "authoredAt": "2026-06-05T14:40:00Z", + "message": "rate limiter audit", "sessionIds": ["b21d004e"], + "observationCount": 9, "files": 1 } + ] +} +``` + +Present: + +> - `9a1b2c3` main 2026-06-07 "rotate refresh tokens", session `7f3a9c2` (14 obs, 3 files) +> - `b21d004` main 2026-06-05 "rate limiter audit", session `b21d004` (9 obs, 1 file) + +## 2. Bare number as limit + +User: "commit-history 5" + +Treat `5` as the limit: + +```json +memory_commits { "limit": 5 } +``` + +Render the five newest linked commits in the same format. + +## 3. Empty result + +User: "Show agent commits on release-2.0." + +```json +memory_commits { "branch": "release-2.0", "limit": 100 } +``` + +Response: + +```json +{ "commits": [] } +``` + +Present: + +> No agent-linked commits on `release-2.0`. Drop the branch filter to see all +> linked commits, or try a different branch. + +REST fallback for this same call, with encoding: + +```http +GET /agentmemory/commits?branch=release-2.0&limit=100 +``` + +Build it with `URLSearchParams` so a branch like `feat/a&b` becomes +`feat%2Fa%26b` rather than breaking the query. diff --git a/plugin/skills/commit-history/SKILL.md b/plugin/skills/commit-history/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b05c00369918a70c372b6698340617d61e290cdd --- /dev/null +++ b/plugin/skills/commit-history/SKILL.md @@ -0,0 +1,62 @@ +--- +name: commit-history +description: List recent git commits linked to agent sessions, optionally filtered by branch or repo. Use when the user asks "show agent commits", "what has the agent shipped", "list linked commits", or wants commits with their session context. +argument-hint: "[branch=... repo=... limit=...]" +user-invocable: true +--- + +The user wants a list of agent-linked commits. Filter args: $ARGUMENTS + +## Quick start + +```json +memory_commits { "branch": "main", "limit": 20 } +``` + +Expected output: + +```text +9a1b2c3 main 2026-06-07 "rotate refresh tokens" · session 7f3a9c2 (14 obs) +b21d004 main 2026-06-05 "rate limiter audit" · session b21d004 (9 obs) +``` + +## Why + +Render only the commits the tool returned, newest first. An empty result means +the filter matched nothing, not that work is missing. + +## Workflow + +1. Parse `$ARGUMENTS` for `branch=`, `repo=`, + `limit=`. A bare numeric token is the limit. Defaults: no branch, no repo, + limit 100, max 500. +2. Call `memory_commits` with the parsed filters. +3. Render reverse-chronologically: short sha, branch, authored timestamp, first + line of the message, linked session id(s) (first 8) with observation counts, + and file count when `files` is present. +4. Empty result: tell the user the filter matched nothing and suggest dropping + the branch or repo filter. + +## Anti-patterns + +WRONG (REST fallback): concatenate `?branch=` + raw branch name, so a name with +`?`, `&`, or `#` corrupts the query string. + +RIGHT: URL-encode every value with `URLSearchParams`/`encodeURIComponent` before +appending to `GET /agentmemory/commits`. + +## Checklist + +- Filters parsed; bare number treated as limit; limit capped at 500. +- Output is reverse-chronological. +- Session ids and observation counts come straight from the response. +- REST fallback URL-encodes branch, repo, and limit. + +## See also + +- `commit-context`: drill into one commit's session. +- `recall`: search the observations behind a linked session. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_commits` is not available. diff --git a/plugin/skills/forget/EXAMPLES.md b/plugin/skills/forget/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..c391bda000abfae3780df311bd988b07d22c8fde --- /dev/null +++ b/plugin/skills/forget/EXAMPLES.md @@ -0,0 +1,75 @@ +# forget worked examples + +## 1. Delete a leaked secret + +User: "Forget that note where I pasted the API key." + +Search: + +```json +memory_smart_search { "query": "api key", "limit": 20 } +``` + +Response: + +```json +{ + "results": [ + { "id": "abc12345", "sessionId": "7f3a9c21", "title": "Pasted staging API key", + "narrative": "STAGING_KEY=sk-live-..." } + ] +} +``` + +Present and gate: + +> Found 1 match: +> - `abc12345` (session `7f3a9c2`) "Pasted staging API key" +> +> Delete this memory? (yes/no) + +After the user says yes: + +```json +memory_governance_delete { "memoryIds": ["abc12345"], "reason": "user privacy request" } +``` + +Response: + +```json +{ "deleted": 1 } +``` + +Present: + +> Deleted 1 memory (`abc12345`). + +## 2. Drop a whole session's observations + +User: "Delete everything from the throwaway spike session." + +Search, identify the session, then collect every memory id in it: + +```json +memory_smart_search { "query": "spike prototype throwaway", "limit": 20 } +``` + +Response has 4 results all with `sessionId: c98f1100`. Show all four, get a yes, +then pass every id: + +```json +memory_governance_delete { + "memoryIds": ["m1", "m2", "m3", "m4"], + "reason": "drop throwaway spike session" +} +``` + +Never send `{ "sessionId": "c98f1100" }`; the MCP deletes by memory id only. + +## 3. User declines + +User: "Actually, on second thought, keep them." + +Do not call delete. Confirm: + +> Understood, nothing deleted. The 4 memories from session `c98f110` are intact. diff --git a/plugin/skills/forget/SKILL.md b/plugin/skills/forget/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..32ec5396d00af0f7dd2adc497979085e7c9bb123 --- /dev/null +++ b/plugin/skills/forget/SKILL.md @@ -0,0 +1,66 @@ +--- +name: forget +description: Delete specific observations from agentmemory after showing them and getting explicit confirmation. Use when the user says "forget this", "delete memory", "remove that note", or wants to scrub specific data for privacy. +argument-hint: "[what to forget - session ID, file path, or search term]" +user-invocable: true +--- + +The user wants to remove data from agentmemory: $ARGUMENTS + +## Quick start + +```json +memory_smart_search { "query": "old api key in config", "limit": 20 } +``` + +Show the matches, get a yes, then: + +```json +memory_governance_delete { "memoryIds": ["abc12345", "def67890"], "reason": "user privacy request" } +``` + +Expected output: + +```text +Found 2 matching memories. Confirmed. Deleted 2 memories. +``` + +## Why + +This is destructive and irreversible. Show exactly what will be deleted and get +an explicit yes before calling delete. Delete by memory ID, never a bare session. + +## Workflow + +1. Search with `memory_smart_search`, the user's text as `query`, `limit: 20`. +2. Show what matched: session ids, memory ids, titles. Ask for explicit + confirmation. Do not proceed on silence or a vague "sure, whatever". +3. On confirmation, call `memory_governance_delete` with `memoryIds` (array or + comma-separated string) and optional `reason` (default `plugin skill request`). +4. To drop a whole session, collect every memory id in that session from the + search results and pass them all. The MCP does not accept a bare `sessionId`. +5. Report the deletion count back. + +## Anti-patterns + +WRONG: search returns matches, you immediately call `memory_governance_delete` +without showing them or waiting for a yes. + +RIGHT: list the matches, ask "Delete these 2? (yes/no)", and only delete after +an explicit yes. + +## Checklist + +- Matches were shown to the user before any delete. +- An explicit yes was received, not assumed. +- `memoryIds` holds real ids from the search, never a bare `sessionId`. +- Final message states the actual count deleted. + +## See also + +- `remember`: the write side; forget is its undo. +- `recall`: find the exact memory id before deleting. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_smart_search` or `memory_governance_delete` is not available. diff --git a/plugin/skills/handoff/EXAMPLES.md b/plugin/skills/handoff/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..11e1d58460325596f5392d724e4ab71a8431579e --- /dev/null +++ b/plugin/skills/handoff/EXAMPLES.md @@ -0,0 +1,56 @@ +# handoff worked examples + +## 1. Resume with an open question + +User: "Where were we?" + +Project cwd: `/Users/dev/app`. Invocation: + +```json +memory_sessions { "limit": 20 } +``` + +Response: + +```json +{ + "sessions": [ + { "id": "7f3a9c21", "cwd": "/Users/dev/app", "title": "Auth refresh rework", + "status": "completed", "startedAt": "2026-06-07T09:00:00Z", + "summary": "Reworked refresh rotation. Open: should logout revoke all device tokens?", + "concepts": ["jwt-refresh-rotation", "logout"] } + ] +} +``` + +Pull supporting context: + +```json +memory_recall { "query": "jwt-refresh-rotation logout", "limit": 10 } +``` + +Present: + +> Resuming `7f3a9c2` "Auth refresh rework". +> **Open question:** should logout revoke all device tokens or just the current one? +> Touched `auth/refresh.ts`, `auth/logout.ts`. Refresh rotation is done. +> **Next step:** decide the revoke scope, then finish `auth/logout.ts`. + +## 2. Sibling-repo guard + +Project cwd: `/Users/dev/repo-a`. Sessions include one with `cwd: +/Users/dev/repo-a-staging`. + +A raw prefix would match `repo-a-staging`. The boundary check rejects it because +`/Users/dev/repo-a-staging` does not equal `/Users/dev/repo-a` and does not start +with `/Users/dev/repo-a/`. Pick the real `repo-a` session instead, or fall back +to the most recent session overall if none matches. + +## 3. Empty session + +User: "Resume." + +If the matched session has zero observations: + +> The most recent session `c98f110` for this project has no recorded +> observations. Nothing to hand off. Want to start fresh from the current state? diff --git a/plugin/skills/handoff/SKILL.md b/plugin/skills/handoff/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..3b4e51492559fa3a21828e69e7bbf8eb04ce7ce6 --- /dev/null +++ b/plugin/skills/handoff/SKILL.md @@ -0,0 +1,68 @@ +--- +name: handoff +description: Resume the most recent agent session for the current working directory, leading with any unanswered question. Use when the user says "where were we", "resume", "handoff", "pick up where I left off", or starts a session with no fresh context. +argument-hint: "[optional cwd override]" +user-invocable: true +--- + +The user wants to resume work. Optional cwd override: $ARGUMENTS + +## Quick start + +```json +memory_sessions { "limit": 20 } +``` + +Pick the most recent session whose `cwd` matches this project, then: +`memory_recall { "query": "", "limit": 10 }`. + +Expected output: + +```text +Resuming 7f3a9c2 "Auth refresh rework". +Open question: should logout revoke all device tokens or just the current one? +Next step: decide revoke scope, then update auth/logout.ts. +``` + +## Why + +Match the session by directory boundary, not raw prefix, so a sibling repo never +gets mistaken for this one. Never invent observations for an empty session. + +## Workflow + +1. Resolve the project path: if `$ARGUMENTS` is given, normalize it to absolute + (`path.resolve(process.cwd(), $ARGUMENTS)`); else use the cwd. +2. Call `memory_sessions`. Pick the most recent session whose normalized `cwd` + matches by directory boundary: equality, OR `cwd.startsWith(projectPath + sep)`, + OR `projectPath.startsWith(cwd + sep)`. Prefer `completed` over `abandoned`. + No match: fall back to the single most recent session overall. +3. If the session ended on an unanswered user-facing question, surface it FIRST. + Look in `summary` or recent `conversation` observations whose `narrative` + ends in `?`. +4. Summarize: title/summary, key files, key decisions or errors, using + `memory_recall` on the top concepts, limit 10. +5. End with one concrete "next step?" pointer. + +## Anti-patterns + +WRONG: `session.cwd.startsWith(projectPath)` matches `/repo-a-staging` when the +project is `/repo-a`, resuming the wrong repo's session. + +RIGHT: `session.cwd === projectPath || session.cwd.startsWith(projectPath + sep)`, +a directory-boundary check that cannot cross sibling repos. + +## Checklist + +- cwd override resolved to an absolute, normalized path. +- Match used a directory-boundary check, not a raw prefix. +- Unanswered question (if any) leads the response. +- Empty session is reported plainly, with an offer to start fresh. + +## See also + +- `recap`, `session-history`, `recall`: same session data, broader views. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_sessions` or `memory_recall` is not available. diff --git a/plugin/skills/recall/EXAMPLES.md b/plugin/skills/recall/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..8e58c56dc450e20f1b3a2d7b59dd358ecf9db07b --- /dev/null +++ b/plugin/skills/recall/EXAMPLES.md @@ -0,0 +1,74 @@ +# recall worked examples + +## 1. Hit on a past decision + +User: "Did we ever decide how to cache sessions?" + +Invocation: + +```json +memory_smart_search { "query": "session caching decision", "limit": 10 } +``` + +Response: + +```json +{ + "results": [ + { "sessionId": "7f3a9c21", "type": "decision", "title": "Drop Redis for iii state store", + "narrative": "We decided to drop Redis and use the iii-engine state store for session caching.", + "importance": 8 } + ] +} +``` + +Present: + +> Yes. In session `7f3a9c21` you decided to drop Redis and use the iii-engine +> state store for session caching (importance 8). + +## 2. Multiple results across sessions + +User: "Recall anything about the rate limiter." + +Invocation: + +```json +memory_smart_search { "query": "rate limiter", "limit": 10 } +``` + +Response: + +```json +{ + "results": [ + { "sessionId": "b21d004e", "type": "code", "title": "limit.ts counts per-IP", + "narrative": "Rate limiter counts per-IP, not per-user.", "importance": 6 }, + { "sessionId": "c98f1100", "type": "conversation", "title": "Discussed sliding window", + "narrative": "Considered a sliding-window limiter, deferred.", "importance": 4 } + ] +} +``` + +Present them grouped by session, leading with the per-IP code note. + +## 3. No results + +User: "Recall the GraphQL schema migration." + +Invocation: + +```json +memory_smart_search { "query": "graphql schema migration", "limit": 10 } +``` + +Response: + +```json +{ "results": [] } +``` + +Present: + +> No memories matched that. Try `schema change`, `graphql`, or `migration` as +> narrower terms, or `recap this week` to scan recent sessions. diff --git a/plugin/skills/recall/SKILL.md b/plugin/skills/recall/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..00f71fc2e5f737503ae241c025f1bb2af73f2f65 --- /dev/null +++ b/plugin/skills/recall/SKILL.md @@ -0,0 +1,60 @@ +--- +name: recall +description: Search agentmemory for past observations, sessions, and learnings about a topic using hybrid BM25 plus vector plus graph search. Use when the user says "recall", "what did we do about", "did we ever", "have we seen", or needs context from past sessions. +argument-hint: "[search query]" +user-invocable: true +--- + +The user wants to recall past context about: $ARGUMENTS + +## Quick start + +```json +memory_smart_search { "query": "jwt refresh token rotation", "limit": 10 } +``` + +Expected output: + +```text +2 results across 2 sessions. +[importance 8] decision · "Rotate refresh tokens on every use" (session 7f3a9c21) +[importance 5] code · "limit.ts counts per-IP" (session b21d004e) +``` + +## Why + +Only surface what the tool returned. Never fabricate an observation, a session +id, or an importance score. If nothing comes back, say so. + +## Workflow + +1. Call `memory_smart_search` with the user's text as `query` and `limit: 10`. + Pass `project` when the user scopes to a specific repo. +2. Group results by session. +3. For each observation show its type, title, and narrative. +4. Lead with the high-signal observations (importance >= 7). +5. If zero results, suggest 2-3 alternative search terms and stop. Do not guess. + +## Anti-patterns + +WRONG: results are empty, so you write "We probably discussed token expiry last +week" from assumption. + +RIGHT: "No memories matched that query. Try `refresh token`, `session expiry`, +or `auth rotation`." + +## Checklist + +- Every observation shown came from the tool response. +- Results grouped by session, high-importance first. +- Empty results trigger alternative-term suggestions, not invention. +- No session id or score was paraphrased or rounded. + +## See also + +- `remember`: the write side; recall retrieves what it stores. +- `recap`, `handoff`, `session-history`: session-scoped views of the same data. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_smart_search` is not available. diff --git a/plugin/skills/recap/EXAMPLES.md b/plugin/skills/recap/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..4426c8cb4c7992050f051873ba256736c61e5fd6 --- /dev/null +++ b/plugin/skills/recap/EXAMPLES.md @@ -0,0 +1,60 @@ +# recap worked examples + +## 1. This week + +User: "Recap this week." + +Window: last 7 days. Invocation: + +```json +memory_sessions { "limit": 30 } +``` + +Response (after filtering to cwd and the 7-day window): + +```json +{ + "sessions": [ + { "id": "7f3a9c21", "cwd": "/Users/dev/app", "title": "Auth refresh rework", + "startedAt": "2026-06-07T09:00:00Z", "observationCount": 14, "status": "completed", + "concepts": ["jwt-refresh-rotation", "auth-flow"] }, + { "id": "b21d004e", "cwd": "/Users/dev/app", "title": "Rate limiter audit", + "startedAt": "2026-06-05T14:00:00Z", "observationCount": 9, "status": "completed", + "concepts": ["rate-limiter", "per-ip-bug"] } + ] +} +``` + +Per session, pull highlights: + +```json +memory_recall { "query": "jwt-refresh-rotation auth-flow", "limit": 3 } +``` + +Present: + +> **2026-06-07** +> - `7f3a9c2` Auth refresh rework, 14 obs, completed +> - [8] Rotate refresh tokens on every use +> +> **2026-06-05** +> - `b21d004e` Rate limiter audit, 9 obs, completed +> - [7] limit.ts counts per-IP, not per-user +> +> 2 sessions across 2 days, 23 observations. + +## 2. Bare number + +User: "recap 3" + +Treat as `last 3`. Call `memory_sessions { "limit": 3 }`, group by date, same format. + +## 3. Empty window + +User: "Recap today." + +If `memory_sessions` returns no session whose `startedAt` is today and whose +`cwd` matches: + +> No sessions today for this project. The most recent was yesterday, `7f3a9c2` +> Auth refresh rework. Want a recap of that instead? diff --git a/plugin/skills/recap/SKILL.md b/plugin/skills/recap/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..b3ea5e9c133a0506ac87107fb9422202e22f48fe --- /dev/null +++ b/plugin/skills/recap/SKILL.md @@ -0,0 +1,63 @@ +--- +name: recap +description: Summarize the last N agent sessions for the current project, grouped by date, with highlight observations per session. Use when the user asks "recap", "what have we been doing", "today", "this week", or wants a rollup of recent work. +argument-hint: "[last N | today | this week]" +user-invocable: true +--- + +The user wants a recap. Time window args: $ARGUMENTS + +## Quick start + +```json +memory_sessions { "limit": 30 } +``` + +Then per surviving session: `memory_recall { "query": "", "limit": 3 }`. + +Expected output: + +```text +2026-06-07 + 7f3a9c2 · "Auth refresh rework" · 14 obs · completed + - [8] Rotate refresh tokens on every use +3 sessions across 2 days, 41 observations. +``` + +## Why + +Only summarize sessions and observations the tools returned. An empty window is +a real answer, not a prompt to invent activity. + +## Workflow + +1. Parse `$ARGUMENTS`: `today` = current local date; `this week` = last 7 days; + `last ` or bare numeric = most recent N; empty = `last 10`. +2. Call `memory_sessions`, filter to the current project (match `cwd` against the + working directory), apply the window, sort by `startedAt` descending. +3. Group survivors by local calendar date (YYYY-MM-DD). +4. Per session list id (first 8), title or first prompt, observation count, + status. Indent 2-3 highlights (importance >= 7) from `memory_recall`. +5. End with "N sessions across M days, K observations." + +## Anti-patterns + +WRONG: window is empty, so you summarize "a productive week of auth work" from +memory of the conversation. + +RIGHT: "No sessions in the last 7 days for this project." + +## Checklist + +- Window parsed correctly from the argument. +- Sessions filtered to the current project's cwd. +- Highlights come from `memory_recall`, not paraphrase. +- Totals line reflects the actual counts shown. + +## See also + +- `handoff`, `session-history`, `recall`: same session data, different lens. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_sessions` or `memory_recall` is not available. diff --git a/plugin/skills/remember/EXAMPLES.md b/plugin/skills/remember/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..e220cb79a0a37a58d6b1e41de8979f6c4ba49a01 --- /dev/null +++ b/plugin/skills/remember/EXAMPLES.md @@ -0,0 +1,67 @@ +# remember worked examples + +## 1. Saving a decision + +User: "Remember that we decided to drop Redis and use the iii-engine state store for session caching." + +Invocation: + +```json +memory_save { + "content": "We decided to drop Redis and use the iii-engine state store for session caching to remove a moving part.", + "concepts": "session-caching, iii-state-store, dropped-redis", + "files": "" +} +``` + +Response: + +```json +{ "id": "7f3a9c21", "concepts": ["session-caching", "iii-state-store", "dropped-redis"], "saved": true } +``` + +Present: + +> Saved. Tagged it `session-caching`, `iii-state-store`, `dropped-redis`, so a +> later recall on caching or Redis will surface this decision. + +## 2. Saving a code-specific gotcha + +User: "Save this: the rate limiter in middleware/limit.ts counts per-IP, not per-user, so logged-in users on shared IPs collide." + +Invocation: + +```json +memory_save { + "content": "The rate limiter in middleware/limit.ts counts per-IP, not per-user, so logged-in users on shared IPs collide.", + "concepts": "rate-limiter, per-ip-bug, shared-ip-collision", + "files": "src/middleware/limit.ts" +} +``` + +Response: + +```json +{ "id": "b21d004e", "concepts": ["rate-limiter", "per-ip-bug", "shared-ip-collision"], "saved": true } +``` + +Present: + +> Saved memory `b21d004e` referencing `src/middleware/limit.ts`. Concepts: +> `rate-limiter`, `per-ip-bug`, `shared-ip-collision`. + +## 3. Vague request, no files + +User: "Remember this for later." + +Ask once for the substance, then save: + +```json +memory_save { + "content": "Staging deploys must run the migration job before the app rollout, never after.", + "concepts": "staging-deploy, migration-ordering, rollout-sequence", + "files": "" +} +``` + +Present the confirmation with the concepts echoed back. diff --git a/plugin/skills/remember/SKILL.md b/plugin/skills/remember/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..83e950d6e7f8e1feb2dd40c566e5146cd0c29efb --- /dev/null +++ b/plugin/skills/remember/SKILL.md @@ -0,0 +1,61 @@ +--- +name: remember +description: Save an insight, decision, or learning to agentmemory's long-term storage with searchable concept tags. Use when the user says "remember this", "save this", "note that", "don't forget", or wants to preserve knowledge for future sessions. +argument-hint: "[what to remember]" +user-invocable: true +--- + +The user wants to save this to long-term memory: $ARGUMENTS + +## Quick start + +```json +memory_save { + "content": "We rotate JWT refresh tokens on every use; the old token is revoked server-side in auth/refresh.ts.", + "concepts": "jwt-refresh-rotation, token-revocation, auth-flow", + "files": "src/auth/refresh.ts" +} +``` + +Expected output: + +```text +Saved memory abc12345 with 3 concepts: jwt-refresh-rotation, token-revocation, auth-flow. +``` + +## Why + +A memory is only as useful as the terms that retrieve it. Tag with specific +concepts so a future `recall` finds it, and preserve the user's own phrasing. + +## Workflow + +1. Pull the core insight, decision, or fact out of `$ARGUMENTS`. +2. Extract 2-5 lowercased concept phrases. Prefer specific over generic + (`jwt-refresh-rotation` beats `auth`). +3. Extract referenced file paths (absolute or repo-relative). Empty if none. +4. Call `memory_save` with `content`, `concepts` (comma-separated string), and + `files` (comma-separated string). +5. Confirm the save and echo the concepts so the user knows the retrieval terms. + +## Anti-patterns + +WRONG: `concepts: "stuff, code, notes"` (generic tags nothing can find later). + +RIGHT: `concepts: "jwt-refresh-rotation, token-revocation"` (specific, retrievable). + +## Checklist + +- Content preserves the user's phrasing, not a paraphrase. +- Concepts are specific, lowercased, 2-5 items. +- File paths are real references, not guesses. +- Confirmation echoes the exact concepts tagged. + +## See also + +- `recall`: retrieve what you save here (the pair to this skill). +- `forget`: remove a memory you saved by mistake. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_save` is not available. diff --git a/plugin/skills/session-history/EXAMPLES.md b/plugin/skills/session-history/EXAMPLES.md new file mode 100644 index 0000000000000000000000000000000000000000..e58654f62482a130edab2ba608f3a2af3e70c2ea --- /dev/null +++ b/plugin/skills/session-history/EXAMPLES.md @@ -0,0 +1,59 @@ +# session-history worked examples + +## 1. Standard timeline + +User: "Show me the session history." + +Invocation: + +```json +memory_sessions { "limit": 20 } +``` + +Response: + +```json +{ + "sessions": [ + { "id": "7f3a9c21", "project": "app", "startedAt": "2026-06-07T09:00:00Z", + "status": "completed", "observationCount": 14, + "summary": "Reworked refresh rotation", + "highlights": [ { "type": "decision", "title": "Rotate refresh tokens on every use" } ] }, + { "id": "b21d004e", "project": "app", "startedAt": "2026-06-05T14:00:00Z", + "status": "completed", "observationCount": 9, + "highlights": [ { "type": "code", "title": "limit.ts counts per-IP" } ] } + ] +} +``` + +Present: + +> - `7f3a9c2` app, 2026-06-07 09:00, completed, 14 obs +> - decision: Rotate refresh tokens on every use (summary: Reworked refresh rotation) +> - `b21d004` app, 2026-06-05 14:00, completed, 9 obs +> - code: limit.ts counts per-IP + +## 2. Session with no observations + +If a returned session has `observationCount: 0`, list it but say so: + +> - `c98f110` app, 2026-06-04 11:00, abandoned, 0 obs (no recorded work) + +## 3. Empty history + +User: "What did we do last time?" + +```json +memory_sessions { "limit": 20 } +``` + +Response: + +```json +{ "sessions": [] } +``` + +Present: + +> No recorded sessions yet for this project. Once you work with memory capture +> on, they will show here. Use `remember` to save a note now. diff --git a/plugin/skills/session-history/SKILL.md b/plugin/skills/session-history/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..dd5147981a5a3813b6679557d067d58b85de420e --- /dev/null +++ b/plugin/skills/session-history/SKILL.md @@ -0,0 +1,61 @@ +--- +name: session-history +description: Show what happened in recent past sessions on this project as a clean timeline. Use when the user asks "what did we do last time", "session history", "past sessions", or wants an overview of previous work. +user-invocable: true +--- + +The user wants an overview of recent sessions on this project. + +## Quick start + +```json +memory_sessions { "limit": 20 } +``` + +Expected output: + +```text +7f3a9c2 · app · 2026-06-07 09:00 · completed · 14 obs + - decision: Rotate refresh tokens on every use +b21d004 · app · 2026-06-05 14:00 · completed · 9 obs + - code: limit.ts counts per-IP +``` + +## Why + +Only show sessions and observations the tool returned. An empty history is a +real answer, never a cue to invent past work. + +## Workflow + +1. Call `memory_sessions` with `limit: 20` for a meaningful window. +2. Present in reverse chronological order: session id (first 8), project, start + time, status. +3. For sessions with observations, show the key highlights (type plus title). +4. Note the total observation count per session. +5. When a session summary exists, surface its title and the key decisions. + +## Anti-patterns + +WRONG: the tool returns two sessions, you describe "several sessions of steady +progress" and add ones you remember from the conversation. + +RIGHT: show exactly the two sessions returned, each with its real id, status, and +observation count. + +## Checklist + +- Every session shown came from the tool response. +- Order is reverse-chronological. +- Per-session observation counts match the response. +- No session or highlight was invented or merged. + +## See also + +- `recap`: same data grouped by date with highlights. +- `handoff`: jump straight into the most recent session. +- `recall`: search across all sessions by topic. + +## Troubleshooting + +See ../_shared/TROUBLESHOOTING.md if `memory_sessions` is not available. diff --git a/plugin/skills/write-agentmemory-skill/SKILL.md b/plugin/skills/write-agentmemory-skill/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..d46a1910c21e7c0dc79a5edb65d2d99efad586d1 --- /dev/null +++ b/plugin/skills/write-agentmemory-skill/SKILL.md @@ -0,0 +1,40 @@ +--- +name: write-agentmemory-skill +description: The house format and rules for writing or updating an agentmemory skill. Use when adding a new skill, restructuring an existing one, or reviewing a skill contribution for consistency. +user-invocable: false +--- + +agentmemory skills follow one tiered format so they stay skimmable, accurate, and current. Match it exactly. + +## Directory layout + +```text +plugin/skills// + SKILL.md (required, under 100 lines) + REFERENCE.md (optional, dense facts; auto-generate data tables) + EXAMPLES.md (optional, worked transcripts) +``` + +## SKILL.md rules + +- Frontmatter: `name`, `description`, optional `argument-hint`, and `user-invocable`. Set `user-invocable: true` only for skills the user runs as a slash command; reference and knowledge skills are `false`. +- Description is two sentences and the only thing the agent sees when deciding to load the skill. Sentence one states the capability. Sentence two starts "Use when" and lists concrete triggers. Keep it distinct from sibling skills, under 1024 chars, third person. +- Body order: Quick start (one concrete example), Why (the governing principle), Workflow (numbered steps with decision gates), Anti-patterns (a WRONG vs RIGHT callout for the top mistake), Checklist, See also (cross-link siblings), Reference or Troubleshooting pointer. +- Stay under 100 lines. Move dense facts to REFERENCE.md and examples to EXAMPLES.md. +- Cross-references link one level deep only. Shared recovery steps live in `../_shared/TROUBLESHOOTING.md`, never inlined. + +## Keep it current + +Facts that exist in source (tool names and parameters, REST endpoints, env vars, connect adapters, hook events) are generated, never hand-typed. Edit the source, then run `npm run skills:gen`. CI runs `npm run skills:check` and fails on drift, so generated tables cannot fall behind the code. + +## Style + +No external or competitor product names. No emojis. No em-dashes. No filler. State the thing and stop. + +## Checklist + +- Description has a "Use when" sentence with real triggers. +- SKILL.md is under 100 lines. +- No time-sensitive claims and no duplicated troubleshooting block. +- Concrete example present; generated facts come from the generator. +- Cross-links resolve and go one level deep. diff --git a/src/app.py b/src/app.py index a2d1dbfb0f233919680ff9113c12e709b89e8ad5..f8bfcc6f76ffc5c31d07f4fbc4f3366f90b72fd1 100644 --- a/src/app.py +++ b/src/app.py @@ -346,7 +346,7 @@ def api_agent_observe(): session_id = body.get("sessionId") project = body.get("project") cwd = body.get("cwd") or "" - text = body.get("text") or "" + text = body.get("text") or body.get("content") or "" obs_type = body.get("type") or "other" title = body.get("title") or f"agent_{obs_type}" image_data = body.get("imageData") @@ -409,10 +409,27 @@ def api_search(): # smart search / hybrid search query res = functions._hybrid_search.search(query, limit) + res = enrich_search_results(kv, res) return jsonify(res), 200 except Exception as e: return jsonify({"error": str(e)}), 400 +@app.route("/agentmemory/export", methods=["GET"]) +def api_export(): + auth_err = check_auth() + if auth_err: + return auth_err + try: + max_sess = request.args.get("maxSessions") + offset = request.args.get("offset") + payload = {} + if max_sess is not None: payload["maxSessions"] = max_sess + if offset is not None: payload["offset"] = offset + res = functions.export_data(kv, payload) + return jsonify(res), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 + @app.route("/agentmemory/replay/sessions", methods=["GET"]) def api_replay_sessions(): auth_err = check_auth() @@ -927,90 +944,13 @@ def api_profile(): project = request.args.get("project") if not project: sessions = kv.list(KV.sessions) - projects = sorted(set(s.get("project", "") for s in sessions if s.get("project"))) - return jsonify({"projects": projects, "success": True}), 200 + projects = set(s.get("project", "") for s in sessions if s.get("project")) + memories = kv.list(KV.memories) + mem_projects = set(m.get("project", "") for m in memories if m.get("project")) + all_projects = sorted(projects.union(mem_projects)) + return jsonify({"projects": all_projects, "success": True}), 200 res = functions.get_project_profile(kv, project) - - # Stored profile may lack topConcepts/topFiles — compute from observations if empty - if not res.get("topConcepts") and not res.get("topFiles"): - import re as _re, json as _j, os.path as _osp - from collections import Counter - sessions = kv.list(KV.sessions) - project_sessions = [s for s in sessions if s.get("project") == project] - concept_counts = Counter() - file_counts = Counter() - - def _harvest_file(path, fc, cc): - if not isinstance(path, str) or not path: - return - fc[path] += 1 - # dirname components → concepts - parts = _re.split(r'[\\/]', path) - fname = parts[-1] if parts else "" - # dir components (skip drive letters, temp paths) - skip = {"tmp", "temp", "claude", "appdata", "local", "users", "windows"} - for part in parts[:-1]: - p = part.lower().strip() - if p and len(p) > 2 and p not in skip and not _re.match(r'^[a-z]:|^\.|^--', p): - cc[p] += 1 - # file stem → concept - stem = _osp.splitext(fname)[0] - if stem and len(stem) > 2: - cc[stem.lower()] += 1 - # extension → technology concept - ext = _osp.splitext(fname)[1].lstrip(".") - if ext in ("py", "ts", "js", "jsx", "tsx", "go", "rs", "java", "cs", "cpp"): - cc[ext] += 1 - - for s in project_sessions: - sid = s.get("id", "") - if not sid: - continue - for o in kv.list(KV.observations(sid)): - # top-level concepts / files - for c in (o.get("concepts") or []): - if isinstance(c, str) and c: - concept_counts[c] += 1 - for f in (o.get("files") or []): - _harvest_file(f, file_counts, concept_counts) - # toolName → concept - tn = o.get("toolName") - if tn: - concept_counts[tn] += 1 - # toolInput path fields - ti = o.get("toolInput") - if isinstance(ti, str): - try: ti = _j.loads(ti) - except Exception: ti = {} - if isinstance(ti, dict): - for fk in ("path", "file_path", "file", "filename"): - _harvest_file(ti.get(fk, ""), file_counts, concept_counts) - # narrative may be JSON string with path/tool info - narr = o.get("narrative") or o.get("raw") or "" - if isinstance(narr, str) and narr.startswith("{"): - try: - nd = _j.loads(narr) - if isinstance(nd, dict): - tn2 = nd.get("toolName") or nd.get("tool_name") - if tn2: concept_counts[tn2] += 1 - for fk in ("path", "file_path", "file", "filename"): - _harvest_file(nd.get(fk, ""), file_counts, concept_counts) - except Exception: - pass - - # memories for this project - for m in kv.list(KV.memories): - if m.get("project") == project: - for c in (m.get("concepts") or []): - if c: concept_counts[c] += 1 - for f in (m.get("files") or []): - _harvest_file(f, file_counts, concept_counts) - - res["topConcepts"] = [{"concept": c, "frequency": n} for c, n in concept_counts.most_common(20)] - res["topFiles"] = [{"file": f, "frequency": n} for f, n in file_counts.most_common(20)] - res["sessionCount"] = len(project_sessions) - return jsonify(res), 200 # ===================================================================== @@ -1064,6 +1004,182 @@ def api_crystals_list(): items = kv.list(KV.crystals) return jsonify({"crystals": items, "total": len(items)}), 200 + +def escape_xml(s: str) -> str: + return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'") + + +def get_file_context(kv_inst, session_id, files, project): + try: + sessions = kv_inst.list(KV.sessions) + other_sessions = [s for s in sessions if s.get("id") != session_id] if session_id else sessions + if project: + other_sessions = [s for s in other_sessions if s.get("project") == project] + + # Sort sessions by startedAt desc + other_sessions.sort(key=lambda s: s.get("startedAt") or "", reverse=True) + other_sessions = other_sessions[:15] + + obs_cache = {} + for s in other_sessions: + s_id = s["id"] + obs_cache[s_id] = kv_inst.list(KV.observations(s_id)) + + results = [] + for file in files: + history = {"file": file, "observations": []} + normalized_file = file.replace("./", "", 1) + + for s in other_sessions: + s_id = s["id"] + observations = obs_cache.get(s_id) or [] + + for obs in observations: + obs_files = obs.get("files") or [] + if isinstance(obs_files, str): + obs_files = [f.strip() for f in obs_files.split(",") if f.strip()] + obs_title = obs.get("title") + if not obs_files or not obs_title: + continue + + # Check match + matches = False + for f in obs_files: + if f == file or f == normalized_file or f.endswith(f"/{normalized_file}") or normalized_file.endswith(f"/{f}"): + matches = True + break + + importance = int(obs.get("importance") or 0) + if matches and importance >= 4: + history["observations"].append({ + "sessionId": s_id, + "obsId": obs.get("id"), + "type": obs.get("type", "other"), + "title": obs_title, + "narrative": obs.get("narrative") or obs.get("content") or "", + "importance": importance, + "timestamp": obs.get("timestamp", "") + }) + + # Sort by importance desc + history["observations"].sort(key=lambda o: o["importance"], reverse=True) + history["observations"] = history["observations"][:5] + if history["observations"]: + results.append(history) + + if not results: + return "" + + lines = [""] + for fh in results: + lines.append(f"## {fh['file']}") + for obs in fh["observations"]: + lines.append(f"- [{obs['type']}] {obs['title']}: {obs['narrative']}") + lines.append("") + return "\n".join(lines) + except Exception as e: + print(f"[enrich] Error generating file context: {e}") + return "" + + +@app.route("/agentmemory/enrich", methods=["POST"]) +def api_enrich(): + auth_err = check_auth() + if auth_err: + return auth_err + try: + data = request.get_json(force=True) or {} + session_id = data.get("sessionId") + files = data.get("files") or [] + terms = data.get("terms") or [] + project = data.get("project") + + parts = [] + # 1. File Context + if files: + file_context = get_file_context(kv, session_id, files, project) + if file_context: + parts.append(file_context) + + # 2. Search + search_queries = [os.path.basename(f) for f in files] + terms + search_queries = [q for q in search_queries if q] + if search_queries: + query_str = " ".join(search_queries) + res = functions._hybrid_search.search(query_str, 5) + if project: + res = [r for r in res if r.get("observation", {}).get("project") == project or r.get("project") == project] + + obs_texts = [] + for r in res: + obs = r.get("observation", r) + narrative = obs.get("narrative") or obs.get("content") + if narrative: + obs_texts.append(escape_xml(narrative)) + if obs_texts: + parts.append("\n" + "\n".join(obs_texts) + "\n") + + # 3. Bug memories + if files: + bugs = [] + memories = kv.list(KV.memories) + for m in memories: + m_type = m.get("type") + m_is_latest = m.get("isLatest", True) + m_project = m.get("project") + m_files = m.get("files") or [] + if isinstance(m_files, str): + m_files = [f.strip() for f in m_files.split(",") if f.strip()] + + if m_type == "bug" and m_is_latest: + if project and m_project and m_project != project: + continue + + has_overlap = False + for f in m_files: + for df in files: + if f in df or df in f: + has_overlap = True + break + if has_overlap: + break + + if has_overlap: + bugs.append(m) + + bugs.sort(key=lambda m: m.get("updatedAt") or m.get("createdAt") or "", reverse=True) + bugs_lines = [] + for m in bugs[:3]: + title = escape_xml(m.get("title") or "") + content = escape_xml(m.get("content") or "") + bugs_lines.append(f"- {title}: {content}") + if bugs_lines: + parts.append("\n" + "\n".join(bugs_lines) + "\n") + + context = "\n\n".join(parts) + if len(context) > 4000: + context = context[:4000] + + return jsonify({"context": context}), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 + + +@app.route("/agentmemory/crystals/auto", methods=["POST"]) +def api_crystals_auto(): + auth_err = check_auth() + if auth_err: + return auth_err + return jsonify({"success": True, "message": "auto-crystallize stub (not implemented in Python version)"}), 200 + + +@app.route("/agentmemory/claude-bridge/sync", methods=["POST"]) +def api_claude_bridge_sync(): + auth_err = check_auth() + if auth_err: + return auth_err + return jsonify({"success": True, "message": "claude-bridge/sync stub"}), 200 + @app.route("/agentmemory/actions", methods=["GET"]) def api_actions_list(): auth_err = check_auth() @@ -1392,13 +1508,55 @@ def api_update_second_brain(): # MCP Server Integration (JSON-RPC) # ===================================================================== +def parse_mcp_list_arg(arg_val): + if isinstance(arg_val, list): + return [str(item).strip() for item in arg_val if item] + if isinstance(arg_val, str) and arg_val: + return [item.strip() for item in arg_val.split(",") if item.strip()] + return [] + +def enrich_search_results(kv_inst, results): + enriched = [] + for r in results: + item = dict(r) + obs_id = item.get("obsId") + session_id = item.get("sessionId") + if not obs_id: + continue + + obj = None + if session_id == "memory" or obs_id.startswith("mem_"): + obj = kv_inst.get(KV.memories, obs_id) + elif session_id: + obj = kv_inst.get(KV.observations(session_id), obs_id) + + if obj: + item["title"] = obj.get("title") or "" + content_val = obj.get("content") or obj.get("narrative") or obj.get("raw") or "" + if not isinstance(content_val, str): + try: + content_val = json.dumps(content_val) + except Exception: + content_val = str(content_val) + item["content"] = content_val + item["type"] = obj.get("type") or "" + item["concepts"] = obj.get("concepts") or [] + item["files"] = obj.get("files") or [] + else: + item["title"] = "" + item["content"] = "" + item["type"] = "" + item["concepts"] = [] + item["files"] = [] + enriched.append(item) + return enriched + @app.route("/agentmemory/mcp/tools", methods=["GET"]) def mcp_tools_list(): auth_err = check_auth() if auth_err: return auth_err - # Return core tools supported by our python daemon tools = [ { "name": "memory_recall", @@ -1420,8 +1578,18 @@ def mcp_tools_list(): "properties": { "content": {"type": "string", "description": "The insight or decision to remember"}, "type": {"type": "string", "description": "Memory type: pattern, preference, architecture, bug, workflow, or fact"}, - "concepts": {"type": "string", "description": "Comma-separated key concepts"}, - "files": {"type": "string", "description": "Comma-separated relevant file paths"}, + "concepts": { + "oneOf": [ + {"type": "string", "description": "Comma-separated key concepts"}, + {"type": "array", "items": {"type": "string"}, "description": "List of key concepts"} + ] + }, + "files": { + "oneOf": [ + {"type": "string", "description": "Comma-separated relevant file paths"}, + {"type": "array", "items": {"type": "string"}, "description": "List of relevant file paths"} + ] + }, "project": {"type": "string", "description": "Canonical project identifier"} }, "required": ["content"] @@ -1432,6 +1600,11 @@ def mcp_tools_list(): "description": "List recent sessions with their status and observation counts.", "inputSchema": {"type": "object", "properties": {}} }, + { + "name": "memory_sessions_list", + "description": "Retrieve list of all memory sessions.", + "inputSchema": {"type": "object", "properties": {}} + }, { "name": "memory_smart_search", "description": "Hybrid semantic+keyword search with progressive disclosure.", @@ -1451,11 +1624,23 @@ def mcp_tools_list(): "type": "object", "properties": { "anchor": {"type": "string", "description": "Anchor point date or keyword"}, - "project": {"type": "string", "description": "Filter by project path"} + "project": {"type": "string", "description": "Filter by project path"}, + "sessionId": {"type": "string", "description": "Filter by session ID"} }, "required": ["anchor"] } }, + { + "name": "memory_observations", + "description": "Retrieve all observations for a given session ID.", + "inputSchema": { + "type": "object", + "properties": { + "sessionId": {"type": "string", "description": "Session ID to fetch observations for"} + }, + "required": ["sessionId"] + } + }, { "name": "memory_profile", "description": "User/project profile with top concepts and file patterns.", @@ -1467,6 +1652,18 @@ def mcp_tools_list(): "required": ["project"] } }, + { + "name": "memory_lessons", + "description": "List all saved lessons, optionally filtered by project.", + "inputSchema": { + "type": "object", + "properties": { + "project": {"type": "string", "description": "Filter by project (optional)"}, + "minConfidence": {"type": "number", "description": "Filter by minimum confidence (optional, default 0.0)"}, + "limit": {"type": "number", "description": "Max results to return (optional, default 50)"} + } + } + }, { "name": "memory_lesson_save", "description": "Save a lesson learned from this session.", @@ -1492,21 +1689,84 @@ def mcp_tools_list(): "required": ["query"] } }, + { + "name": "memory_lesson_search", + "description": "Search lessons learned by query.", + "inputSchema": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Search query keywords"}, + "project": {"type": "string", "description": "Filter by project path (optional)"} + }, + "required": ["query"] + } + }, + { + "name": "memory_consolidate", + "description": "Trigger the consolidation pipeline to summarize sessions and extract semantic/procedural memory.", + "inputSchema": {"type": "object", "properties": {}} + }, + { + "name": "memory_reflect", + "description": "Trigger reflection for a session, updating pending items, project context, and session patterns.", + "inputSchema": { + "type": "object", + "properties": { + "sessionId": {"type": "string", "description": "Session ID to reflect upon"}, + "maxObservations": {"type": "number", "description": "Max observations to scan (optional, default 50)"} + }, + "required": ["sessionId"] + } + }, + { + "name": "memory_diagnose", + "description": "Run diagnostic health checks across all memory subsystems.", + "inputSchema": {"type": "object", "properties": {}} + }, + { + "name": "memory_forget", + "description": "Delete a memory, a session, or specific observations within a session.", + "inputSchema": { + "type": "object", + "properties": { + "memoryId": {"type": "string", "description": "Memory ID to delete"}, + "sessionId": {"type": "string", "description": "Session ID to delete"}, + "observationIds": { + "oneOf": [ + {"type": "string", "description": "Comma-separated observation IDs to delete"}, + {"type": "array", "items": {"type": "string"}, "description": "List of observation IDs to delete"} + ] + } + } + } + }, + { + "name": "memory_export", + "description": "Export all memory data including sessions, memories, lessons, observations, and slots as JSON.", + "inputSchema": { + "type": "object", + "properties": { + "maxSessions": {"type": "number", "description": "Max sessions to export (optional)"}, + "offset": {"type": "number", "description": "Pagination offset for sessions (optional)"} + } + } + }, { "name": "agent_observe", "description": "Log a direct observation, thought, command execution, or action from the agent's active execution.", "inputSchema": { "type": "object", "properties": { - "agentId": {"type": "string", "description": "ID/Name of the agent logging this (e.g. 'antigravity')"}, + "agentId": {"type": "string", "description": "ID/Name of the agent logging this (e.g. 'antigravity', optional)"}, "sessionId": {"type": "string", "description": "Active session ID"}, "project": {"type": "string", "description": "Canonical project path/identifier"}, "text": {"type": "string", "description": "The observation log, thought, or content"}, + "content": {"type": "string", "description": "The observation log, thought, or content (alternative to text)"}, "type": {"type": "string", "description": "Observation type: thought, command, tool, error, result, conversation, other"}, "title": {"type": "string", "description": "A short summary title for the observation"}, "cwd": {"type": "string", "description": "Current working directory"} }, - "required": ["agentId", "sessionId", "project", "text"] + "required": ["sessionId", "project"] } }, { @@ -1515,14 +1775,24 @@ def mcp_tools_list(): "inputSchema": { "type": "object", "properties": { - "agentId": {"type": "string", "description": "ID/Name of the agent (e.g. 'antigravity')"}, + "agentId": {"type": "string", "description": "ID/Name of the agent (e.g. 'antigravity', optional)"}, "content": {"type": "string", "description": "The memory content/insight"}, "project": {"type": "string", "description": "Canonical project path/identifier"}, "type": {"type": "string", "description": "Memory type: fact, preference, bug, workflow, architecture"}, - "concepts": {"type": "string", "description": "Comma-separated key concepts"}, - "files": {"type": "string", "description": "Comma-separated relevant file paths"} + "concepts": { + "oneOf": [ + {"type": "string", "description": "Comma-separated key concepts"}, + {"type": "array", "items": {"type": "string"}, "description": "List of key concepts"} + ] + }, + "files": { + "oneOf": [ + {"type": "string", "description": "Comma-separated relevant file paths"}, + {"type": "array", "items": {"type": "string"}, "description": "List of relevant file paths"} + ] + } }, - "required": ["agentId", "content", "project"] + "required": ["content", "project"] } } ] @@ -1549,22 +1819,23 @@ def mcp_tools_call(): q = args.get("query") limit = int(args.get("limit") or 10) res = functions._hybrid_search.search(q, limit) + res = enrich_search_results(kv, res) text_out = json.dumps(res, indent=2) elif name == "memory_save": content = args.get("content") - concepts = args.get("concepts", "").split(",") if args.get("concepts") else [] - files = args.get("files", "").split(",") if args.get("files") else [] + concepts = parse_mcp_list_arg(args.get("concepts")) + files = parse_mcp_list_arg(args.get("files")) res = functions.remember(kv, { "content": content, "type": args.get("type") or "fact", - "concepts": [c.strip() for c in concepts if c.strip()], - "files": [f.strip() for f in files if f.strip()], + "concepts": concepts, + "files": files, "project": args.get("project") }) text_out = json.dumps(res) - elif name == "memory_sessions": + elif name in ("memory_sessions", "memory_sessions_list"): sessions = functions.list_sessions(kv) text_out = json.dumps({"sessions": sessions}, indent=2) @@ -1572,19 +1843,37 @@ def mcp_tools_call(): q = args.get("query") limit = int(args.get("limit") or 10) res = functions._hybrid_search.search(q, limit) + res = enrich_search_results(kv, res) text_out = json.dumps(res, indent=2) elif name == "memory_timeline": res = functions.timeline(kv, { "anchor": args.get("anchor"), - "project": args.get("project") + "project": args.get("project"), + "sessionId": args.get("sessionId") }) text_out = json.dumps(res, indent=2) + elif name == "memory_observations": + session_id = args.get("sessionId") + if not session_id: + return jsonify({"error": "sessionId is required"}), 400 + obs = kv.list(KV.observations(session_id)) + obs.sort(key=lambda o: o.get("timestamp", "")) + text_out = json.dumps({"observations": obs}, indent=2) + elif name == "memory_profile": - res = functions.get_project_profile(kv, args.get("project")) + res = functions.build_project_profile(kv, args.get("project")) text_out = json.dumps(res, indent=2) + elif name == "memory_lessons": + res = functions.lesson_list(kv, { + "project": args.get("project"), + "minConfidence": args.get("minConfidence"), + "limit": args.get("limit") + }) + text_out = json.dumps(res, indent=2) + elif name == "memory_lesson_save": res = functions.lesson_save(kv, { "content": args.get("content"), @@ -1593,24 +1882,58 @@ def mcp_tools_call(): }) text_out = json.dumps(res) - elif name == "memory_lesson_recall": + elif name in ("memory_lesson_recall", "memory_lesson_search"): res = functions.lesson_recall(kv, { "query": args.get("query"), "project": args.get("project") }) text_out = json.dumps(res, indent=2) + + elif name == "memory_consolidate": + res = functions.consolidate(kv) + text_out = json.dumps(res, indent=2) + + elif name == "memory_reflect": + session_id = args.get("sessionId") + max_obs = int(args.get("maxObservations") or 50) + if not session_id: + return jsonify({"error": "sessionId is required"}), 400 + res = functions.slot_reflect(kv, session_id, max_obs) + text_out = json.dumps(res, indent=2) + + elif name == "memory_diagnose": + res = functions.health_check(kv) + text_out = json.dumps(res, indent=2) + + elif name == "memory_forget": + obs_ids = parse_mcp_list_arg(args.get("observationIds")) + res = functions.forget(kv, { + "memoryId": args.get("memoryId"), + "sessionId": args.get("sessionId"), + "observationIds": obs_ids + }) + text_out = json.dumps(res, indent=2) + + elif name == "memory_export": + max_sess = args.get("maxSessions") + offset = args.get("offset") + payload = {} + if max_sess is not None: payload["maxSessions"] = max_sess + if offset is not None: payload["offset"] = offset + res = functions.export_data(kv, payload) + text_out = json.dumps(res, indent=2) elif name == "agent_observe": - agent_id = args.get("agentId") + agent_id = args.get("agentId") or functions.get_agent_id() or "agent" session_id = args.get("sessionId") project = args.get("project") - text = args.get("text") + text = args.get("text") or args.get("content") obs_type = args.get("type") or "other" title = args.get("title") or f"agent_{obs_type}" cwd = args.get("cwd") or "" - if not agent_id or not session_id or not project or not text: - return jsonify({"error": "agentId, sessionId, project, and text are required"}), 400 + if not session_id or not project or not text: + return jsonify({"error": "sessionId, project, and text (or content) are required"}), 400 payload = { "sessionId": session_id, @@ -1629,21 +1952,21 @@ def mcp_tools_call(): text_out = json.dumps(res) elif name == "agent_remember": - agent_id = args.get("agentId") + agent_id = args.get("agentId") or functions.get_agent_id() or "agent" content = args.get("content") project = args.get("project") mem_type = args.get("type") or "fact" - concepts = args.get("concepts", "").split(",") if args.get("concepts") else [] - files = args.get("files", "").split(",") if args.get("files") else [] + concepts = parse_mcp_list_arg(args.get("concepts")) + files = parse_mcp_list_arg(args.get("files")) - if not agent_id or not content or not project: - return jsonify({"error": "agentId, content, and project are required"}), 400 + if not content or not project: + return jsonify({"error": "content and project are required"}), 400 payload = { "content": content, "type": mem_type, - "concepts": [c.strip() for c in concepts if c.strip()], - "files": [f.strip() for f in files if f.strip()], + "concepts": concepts, + "files": files, "project": project, "agentId": agent_id } @@ -1652,7 +1975,6 @@ def mcp_tools_call(): else: return jsonify({"error": f"unknown tool: {name}"}), 400 - return jsonify({ "content": [ diff --git a/src/connect.py b/src/connect.py new file mode 100644 index 0000000000000000000000000000000000000000..88c0f23b6afb2c88dfbb13b1fe6cc9fc7cc37632 --- /dev/null +++ b/src/connect.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +import os +import sys +import json +import shutil +import argparse +from pathlib import Path + +# Helper functions for connect module + +def get_home_dir(): + return os.path.expanduser("~") + +def get_appdata_dir(): + return os.environ.get("APPDATA") or os.environ.get("LOCALAPPDATA") or get_home_dir() + +def read_json_safe(path): + if not os.path.exists(path): + return {} + try: + with open(path, "r", encoding="utf-8") as f: + return json.load(f) + except Exception: + return {} + +def write_json_atomic(path, data): + os.makedirs(os.path.dirname(path), exist_ok=True) + temp_path = f"{path}.tmp" + with open(temp_path, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + f.write("\n") + # Atomic rename + shutil.move(temp_path, path) + +def backup_file(path, prefix, ext="json"): + if not os.path.exists(path): + return None + backup_path = f"{path}.{prefix}.backup-{int(os.path.getmtime(path))}.{ext}" + shutil.copy2(path, backup_path) + return backup_path + +def get_plugin_root(): + # connect.py resides in src/, plugin/ is in the parent directory + src_dir = os.path.dirname(os.path.abspath(__file__)) + project_root = os.path.dirname(src_dir) + plugin_path = os.path.join(project_root, "plugin") + if os.path.exists(os.path.join(plugin_path, "scripts")): + return plugin_path + raise RuntimeError("Could not find plugin root directory.") + +def get_mcp_stdio_path(): + src_dir = os.path.dirname(os.path.abspath(__file__)) + mcp_path = os.path.join(src_dir, "mcp_stdio.py") + if os.path.exists(mcp_path): + return mcp_path + raise RuntimeError("Could not find mcp_stdio.py.") + +def build_merged_hooks(existing_hooks, plugin_root, manifest_filename="hooks.json"): + manifest_path = os.path.join(plugin_root, "hooks", manifest_filename) + with open(manifest_path, "r", encoding="utf-8") as f: + ours = json.load(f) + + # Normalize paths for comparison + normalized_scripts_dir = os.path.join(plugin_root, "scripts").replace("\\", "/") + + # Clean existing agentmemory hooks + cleaned_hooks = {} + if existing_hooks and "hooks" in existing_hooks: + for event, entries in existing_hooks["hooks"].items(): + kept = [] + for entry in entries: + is_ours = False + for handler in entry.get("hooks", []): + cmd = handler.get("command", "").replace("\\", "/") + if normalized_scripts_dir in cmd: + is_ours = True + break + if not is_ours: + kept.append(entry) + if kept: + cleaned_hooks[event] = kept + + # Add ours + for event, entries in ours.get("hooks", {}).items(): + resolved_entries = [] + for entry in entries: + next_entry = {} + if "matcher" in entry: + next_entry["matcher"] = entry["matcher"] + + resolved_handlers = [] + for handler in entry.get("hooks", []): + cmd = handler.get("command", "") + resolved_cmd = cmd.replace("${CLAUDE_PLUGIN_ROOT}", plugin_root.replace("\\", "/")) + # Also replace python with sys.executable to use the correct Python instance + if resolved_cmd.startswith("python "): + resolved_cmd = f'"{sys.executable.replace("\\", "/")}" ' + resolved_cmd[7:] + resolved_handlers.append({ + "type": handler.get("type"), + "command": resolved_cmd + }) + next_entry["hooks"] = resolved_handlers + resolved_entries.append(next_entry) + + cleaned_hooks[event] = cleaned_hooks.get(event, []) + resolved_entries + + return {"hooks": cleaned_hooks} + +# ----------------- Adapters ----------------- + +class ClaudeCodeAdapter: + name = "claude-code" + display_name = "Claude Code" + + def detect(self): + claude_dir = os.path.join(get_home_dir(), ".claude") + return os.path.exists(claude_dir) + + def install(self, args): + claude_json = os.path.join(get_home_dir(), ".claude.json") + mcp_stdio_path = get_mcp_stdio_path() + + existing = read_json_safe(claude_json) + next_cfg = existing.copy() + servers = next_cfg.get("mcpServers", {}) + + already_has = "agentmemory" in servers + if already_has and not args.force: + print(f"[OK] Claude Code already wired in {claude_json}") + else: + if args.dry_run: + print(f"[dry-run] Would write mcpServers.agentmemory in {claude_json}") + else: + backup = backup_file(claude_json, "claude-code") + if backup: + print(f"Backed up configuration to {backup}") + + servers["agentmemory"] = { + "command": sys.executable, + "args": [mcp_stdio_path], + "env": { + "AGENTMEMORY_URL": "http://localhost:3111" + } + } + next_cfg["mcpServers"] = servers + write_json_atomic(claude_json, next_cfg) + print(f"[OK] Wired Claude Code MCP to {claude_json}") + + if args.with_hooks: + claude_settings = os.path.join(get_home_dir(), ".claude", "settings.json") + try: + plugin_root = get_plugin_root() + existing_settings = read_json_safe(claude_settings) + merged = build_merged_hooks(existing_settings, plugin_root, "hooks.json") + + if args.dry_run: + print(f"[dry-run] Would merge hooks into {claude_settings}") + else: + backup = backup_file(claude_settings, "claude-settings") + if backup: + print(f"Backed up settings to {backup}") + existing_settings["hooks"] = merged["hooks"] + write_json_atomic(claude_settings, existing_settings) + print(f"[OK] Wired Claude Code hooks to {claude_settings}") + except Exception as e: + print(f"[FAIL] Failed to configure Claude Code hooks: {e}") + +class CodexAdapter: + name = "codex" + display_name = "Codex CLI" + + def detect(self): + codex_dir = os.path.join(get_home_dir(), ".codex") + return os.path.exists(codex_dir) + + def install(self, args): + codex_toml = os.path.join(get_home_dir(), ".codex", "config.toml") + mcp_stdio_path = get_mcp_stdio_path() + + toml_block = f""" +[mcp_servers.agentmemory] +command = "{sys.executable.replace('\\', '/')}" +args = ["{mcp_stdio_path.replace('\\', '/')}"] +[mcp_servers.agentmemory.env] +AGENTMEMORY_URL = "http://localhost:3111" +""" + + exists = os.path.exists(codex_toml) + current = "" + if exists: + with open(codex_toml, "r", encoding="utf-8") as f: + current = f.read() + + wired = "[mcp_servers.agentmemory]" in current + if wired and not args.force: + print(f"[OK] Codex CLI already wired in {codex_toml}") + else: + if args.dry_run: + print(f"[dry-run] Would write [mcp_servers.agentmemory] block to {codex_toml}") + else: + backup = backup_file(codex_toml, "codex", "toml") + if backup: + print(f"Backed up config to {backup}") + + # Strip existing block if forcing + cleaned = current + if wired: + lines = current.splitlines() + out = [] + skipping = False + for line in lines: + trimmed = line.strip() + if trimmed == "[mcp_servers.agentmemory]" or trimmed == "[mcp_servers.agentmemory.env]": + skipping = True + continue + if skipping and trimmed.startswith("[") and trimmed != "[mcp_servers.agentmemory.env]": + skipping = False + if not skipping: + out.append(line) + cleaned = "\n".join(out).strip() + + next_toml = cleaned + ("\n\n" if cleaned else "") + toml_block.strip() + "\n" + os.makedirs(os.path.dirname(codex_toml), exist_ok=True) + with open(codex_toml, "w", encoding="utf-8") as f: + f.write(next_toml) + print(f"[OK] Wired Codex CLI TOML configuration to {codex_toml}") + + if args.with_hooks: + codex_hooks = os.path.join(get_home_dir(), ".codex", "hooks.json") + try: + plugin_root = get_plugin_root() + existing_hooks = read_json_safe(codex_hooks) + merged = build_merged_hooks(existing_hooks, plugin_root, "hooks.codex.json") + + if args.dry_run: + print(f"[dry-run] Would merge hooks into {codex_hooks}") + else: + backup = backup_file(codex_hooks, "codex-hooks") + if backup: + print(f"Backed up hooks to {backup}") + write_json_atomic(codex_hooks, merged) + print(f"[OK] Wired Codex hooks workaround to {codex_hooks}") + except Exception as e: + print(f"[FAIL] Failed to configure Codex hooks: {e}") + +class HermesAdapter: + name = "hermes" + display_name = "Hermes Agent" + + def detect(self): + hermes_dir = os.path.join(get_home_dir(), ".hermes") + return os.path.exists(hermes_dir) + + def install(self, args): + dest_dir = os.path.join(get_home_dir(), ".hermes", "plugins", "agentmemory") + src_dir = os.path.dirname(os.path.abspath(__file__)) + project_root = os.path.dirname(src_dir) + hermes_src = os.path.join(project_root, "integrations", "hermes") + + if not os.path.exists(hermes_src): + print(f"[FAIL] Failed: Source integrations/hermes not found at {hermes_src}") + return + + if args.dry_run: + print(f"[dry-run] Would copy {hermes_src} to {dest_dir}") + else: + if os.path.exists(dest_dir): + if not args.force: + print(f"[OK] Hermes plugin directory already exists at {dest_dir}. Use --force to overwrite.") + return + shutil.rmtree(dest_dir) + + shutil.copytree(hermes_src, dest_dir) + print(f"[OK] Copied Hermes memory provider plugin to {dest_dir}") + print("To finish configuration, add to ~/.hermes/config.yaml:") + print(" mcp_servers:") + print(" agentmemory:") + print(" command: python") + print(f' args: ["{get_mcp_stdio_path()}"]') + print(" memory:") + print(" provider: agentmemory") + +class AntigravityAdapter: + name = "antigravity" + display_name = "Antigravity" + + def get_user_dir(self): + if sys.platform == "darwin": + return os.path.join(get_home_dir(), "Library", "Application Support", "Antigravity", "User") + elif sys.platform == "win32": + appdata = get_appdata_dir() + return os.path.join(appdata, "Antigravity", "User") + else: + return os.path.join(get_home_dir(), ".config", "Antigravity", "User") + + def detect(self): + return os.path.exists(self.get_user_dir()) + + def install(self, args): + mcp_config_path = os.path.join(self.get_user_dir(), "mcp_config.json") + mcp_stdio_path = get_mcp_stdio_path() + + existing = read_json_safe(mcp_config_path) + next_cfg = existing.copy() + servers = next_cfg.get("mcpServers", {}) + + already_has = "agentmemory" in servers + if already_has and not args.force: + print(f"[OK] Antigravity already wired in {mcp_config_path}") + else: + if args.dry_run: + print(f"[dry-run] Would write mcpServers.agentmemory in {mcp_config_path}") + else: + backup = backup_file(mcp_config_path, "antigravity") + if backup: + print(f"Backed up config to {backup}") + + servers["agentmemory"] = { + "command": sys.executable, + "args": [mcp_stdio_path], + "env": { + "AGENTMEMORY_URL": "http://localhost:3111" + } + } + next_cfg["mcpServers"] = servers + write_json_atomic(mcp_config_path, next_cfg) + print(f"[OK] Wired Antigravity MCP config in {mcp_config_path}") + +class KiroAdapter: + name = "kiro" + display_name = "Kiro" + + def detect(self): + kiro_dir = os.path.join(get_home_dir(), ".kiro") + return os.path.exists(kiro_dir) + + def install(self, args): + mcp_config_path = os.path.join(get_home_dir(), ".kiro", "settings", "mcp.json") + mcp_stdio_path = get_mcp_stdio_path() + + existing = read_json_safe(mcp_config_path) + next_cfg = existing.copy() + servers = next_cfg.get("mcpServers", {}) + + already_has = "agentmemory" in servers + if already_has and not args.force: + print(f"[OK] Kiro already wired in {mcp_config_path}") + else: + if args.dry_run: + print(f"[dry-run] Would write mcpServers.agentmemory in {mcp_config_path}") + else: + backup = backup_file(mcp_config_path, "kiro") + if backup: + print(f"Backed up config to {backup}") + + servers["agentmemory"] = { + "command": sys.executable, + "args": [mcp_stdio_path], + "env": { + "AGENTMEMORY_URL": "http://localhost:3111" + } + } + next_cfg["mcpServers"] = servers + write_json_atomic(mcp_config_path, next_cfg) + print(f"[OK] Wired Kiro MCP config in {mcp_config_path}") + +class RulesGeneratorAdapter: + name = "cursor" + display_name = "Workspace Rules (Cursor/Cline/Windsurf)" + + def detect(self): + # Always available for rules generation in current directory + return True + + def install(self, args): + rule_content = """# Agent Memory Rules + +This workspace is integrated with long-term semantic memory via `agentmemory-python`. +You must act as your own memory manager by calling the memory MCP tools at critical boundaries. + +## Rules & Workflow + +1. **Initial Search (Prefetch Context)**: + At the start of every session or new task, immediately call `memory_smart_search` with terms related to the current objective. This retrieves past architecture patterns, preferences, bug fixes, or lessons. + - Example: `memory_smart_search(query="jwt token rotation logic")` + +2. **Lessons & Insights Capture**: + When you successfully debug a complex error, discover an undocumented requirement, or establish a convention, persist it: + - Call `memory_lesson_save` to record lessons that improve your coding capabilities. Duplicate saves strengthen confidence scores. + - Call `memory_save` to save long-term structural facts. Always extract 2-5 specific lowercased tags (e.g. `auth-flow`, `refresh-token`) as concepts. + +3. **Checklist Before Ending**: + Before stating a task is complete: + - Reflect on whether any lessons learned should be saved. + - Call `memory_reflect` to automatically distribute observations into slots if needed. +""" + cwd = os.getcwd() + + # Write to .cursorrules + cursorrules = os.path.join(cwd, ".cursorrules") + clineskills = os.path.join(cwd, ".clineskills") + windsurfrules = os.path.join(cwd, ".windsurfrules") + + if args.dry_run: + print(f"[dry-run] Would write rules templates to {cwd}") + else: + with open(cursorrules, "w", encoding="utf-8") as f: + f.write(rule_content) + with open(clineskills, "w", encoding="utf-8") as f: + f.write(rule_content) + with open(windsurfrules, "w", encoding="utf-8") as f: + f.write(rule_content) + print(f"[OK] Generated rule templates in current workspace:") + print(f" - {cursorrules}") + print(f" - {clineskills}") + print(f" - {windsurfrules}") + +ADAPTERS = [ + ClaudeCodeAdapter(), + CodexAdapter(), + HermesAdapter(), + AntigravityAdapter(), + KiroAdapter(), + RulesGeneratorAdapter() +] + +def main(): + parser = argparse.ArgumentParser(description="Wired agentmemory MCP and Hooks into client agents.") + parser.add_argument("agent", nargs="?", choices=[a.name for a in ADAPTERS], help="Specify target agent.") + parser.add_argument("--with-hooks", action="store_true", help="Install global workspace hook execution blocks (Claude/Codex).") + parser.add_argument("--dry-run", action="store_true", help="Log proposed configuration modifications without writing.") + parser.add_argument("--force", action="store_true", help="Overwrite existing configuration settings.") + parser.add_argument("--all", action="store_true", help="Attempt connection to all detected agents.") + + args = parser.parse_args() + + if not args.agent and not args.all: + parser.print_help() + print("\nAvailable agents:") + for a in ADAPTERS: + print(f" - {a.name:15} ({a.display_name})") + sys.exit(0) + + targets = [] + if args.all: + targets = [a for a in ADAPTERS if a.detect() and a.name != "cursor"] + else: + matched = [a for a in ADAPTERS if a.name == args.agent] + if matched: + targets = matched + + if not targets: + print("No agents detected or matched target.") + sys.exit(1) + + for target in targets: + if not target.detect() and not args.force: + print(f"[FAIL] {target.display_name} not detected on this system. (Use --force to install anyway)") + continue + + print(f"Wiring {target.display_name}...") + try: + target.install(args) + except Exception as e: + print(f"[FAIL] Failed to install {target.display_name}: {e}") + +if __name__ == "__main__": + main() diff --git a/src/functions.py b/src/functions.py index f1410e2e61f798d8c5ad3c08f746bf7cd7672f59..76097b82571f3f9cf84d6df9607921a4889af04d 100644 --- a/src/functions.py +++ b/src/functions.py @@ -1762,11 +1762,14 @@ def timeline(kv: StateKV, data: Dict[str, Any]) -> Dict[str, Any]: # Simple timeline query returning observations sorted by timestamp anchor = data.get("anchor") project = data.get("project") + session_id = data.get("sessionId") before = data.get("before") or 10 after = data.get("after") or 10 sessions = kv.list(KV.sessions) - if project: + if session_id: + sessions = [s for s in sessions if s.get("id") == session_id] + elif project: sessions = [s for s in sessions if s.get("project") == project] all_obs = [] @@ -1805,8 +1808,193 @@ def get_project_profile(kv: StateKV, project: str) -> Dict[str, Any]: "commonErrors": [], "updatedAt": datetime.datetime.utcnow().isoformat() + "Z" } + if not prof.get("topConcepts") and not prof.get("topFiles"): + prof = build_project_profile(kv, project) + return prof + +def build_project_profile(kv: StateKV, project: str) -> Dict[str, Any]: + prof = kv.get(KV.profiles, project) + if not prof: + prof = { + "project": project, + "topConcepts": [], + "topFiles": [], + "conventions": [], + "commonErrors": [], + "updatedAt": datetime.datetime.utcnow().isoformat() + "Z" + } + + # Stored profile may lack topConcepts/topFiles — compute from observations + memories if empty + if not prof.get("topConcepts") and not prof.get("topFiles"): + import re as _re, json as _j, os.path as _osp + from collections import Counter + sessions = kv.list(KV.sessions) + project_sessions = [s for s in sessions if s.get("project") == project] + concept_counts = Counter() + file_counts = Counter() + + def _harvest_file(path, fc, cc): + if not isinstance(path, str) or not path: + return + fc[path] += 1 + parts = _re.split(r'[\\/]', path) + fname = parts[-1] if parts else "" + skip = {"tmp", "temp", "claude", "appdata", "local", "users", "windows"} + for part in parts[:-1]: + p = part.lower().strip() + if p and len(p) > 2 and p not in skip and not _re.match(r'^[a-z]:|^\.|^--', p): + cc[p] += 1 + stem = _osp.splitext(fname)[0] + if stem and len(stem) > 2: + cc[stem.lower()] += 1 + ext = _osp.splitext(fname)[1].lstrip(".") + if ext in ("py", "ts", "js", "jsx", "tsx", "go", "rs", "java", "cs", "cpp"): + cc[ext] += 1 + + for s in project_sessions: + sid = s.get("id", "") + if not sid: + continue + for o in kv.list(KV.observations(sid)): + for c in (o.get("concepts") or []): + if isinstance(c, str) and c: + concept_counts[c] += 1 + for f in (o.get("files") or []): + _harvest_file(f, file_counts, concept_counts) + tn = o.get("toolName") + if tn: + concept_counts[tn] += 1 + ti = o.get("toolInput") + if isinstance(ti, str): + try: ti = _j.loads(ti) + except Exception: ti = {} + if isinstance(ti, dict): + for fk in ("path", "file_path", "file", "filename"): + _harvest_file(ti.get(fk, ""), file_counts, concept_counts) + narr = o.get("narrative") or o.get("raw") or "" + if isinstance(narr, str) and narr.startswith("{"): + try: + nd = _j.loads(narr) + if isinstance(nd, dict): + tn2 = nd.get("toolName") or nd.get("tool_name") + if tn2: concept_counts[tn2] += 1 + for fk in ("path", "file_path", "file", "filename"): + _harvest_file(nd.get(fk, ""), file_counts, concept_counts) + except Exception: + pass + + # memories for this project + for m in kv.list(KV.memories): + if m.get("project") == project: + for c in (m.get("concepts") or []): + if c: concept_counts[c] += 1 + for f in (m.get("files") or []): + _harvest_file(f, file_counts, concept_counts) + + prof["topConcepts"] = [{"concept": c, "frequency": n} for c, n in concept_counts.most_common(20)] + prof["topFiles"] = [{"file": f, "frequency": n} for f, n in file_counts.most_common(20)] + prof["sessionCount"] = len(project_sessions) + return prof +def export_data(kv: StateKV, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + if data is None: + data = {} + raw_max = data.get("maxSessions") + max_sessions = None + if raw_max is not None: + try: + max_sessions = min(max(int(raw_max), 1), 1000) + except Exception: + pass + + raw_offset = data.get("offset") + offset = 0 + if raw_offset is not None: + try: + offset = max(int(raw_offset), 0) + except Exception: + pass + + all_sessions = kv.list(KV.sessions) + all_sessions.sort(key=lambda s: s.get("startedAt", ""), reverse=True) + + if max_sessions is not None: + paginated_sessions = all_sessions[offset:offset + max_sessions] + else: + paginated_sessions = all_sessions + + memories = kv.list(KV.memories) + summaries = kv.list(KV.summaries) + + observations = {} + for s in paginated_sessions: + sid = s.get("id") + if sid: + obs = kv.list(KV.observations(sid)) + if obs: + observations[sid] = obs + + profiles = [] + unique_projects = list(set(s.get("project") for s in paginated_sessions if s.get("project"))) + for proj in unique_projects: + p = kv.get(KV.profiles, proj) + if p: + profiles.append(p) + + graph_nodes = kv.list(KV.graphNodes) + graph_edges = kv.list(KV.graphEdges) + semantic_memories = kv.list(KV.semantic) + procedural_memories = kv.list(KV.procedural) + actions = kv.list(KV.actions) + action_edges = kv.list(KV.actionEdges) + sentinels = kv.list(KV.sentinels) + sketches = kv.list(KV.sketches) + crystals = kv.list(KV.crystals) + facets = kv.list(KV.facets) + lessons = kv.list(KV.lessons) + insights = kv.list(KV.insights) + routines = kv.list(KV.routines) + signals = kv.list(KV.signals) + checkpoints = kv.list(KV.checkpoints) + access_logs = kv.list(KV.accessLog) + + res = { + "version": "0.9.21", + "exportedAt": datetime.datetime.utcnow().isoformat() + "Z", + "sessions": paginated_sessions, + "observations": observations, + "memories": memories, + "summaries": summaries + } + if profiles: res["profiles"] = profiles + if graph_nodes: res["graphNodes"] = graph_nodes + if graph_edges: res["graphEdges"] = graph_edges + if semantic_memories: res["semanticMemories"] = semantic_memories + if procedural_memories: res["proceduralMemories"] = procedural_memories + if actions: res["actions"] = actions + if action_edges: res["actionEdges"] = action_edges + if sentinels: res["sentinels"] = sentinels + if sketches: res["sketches"] = sketches + if crystals: res["crystals"] = crystals + if facets: res["facets"] = facets + if lessons: res["lessons"] = lessons + if insights: res["insights"] = insights + if routines: res["routines"] = routines + if signals: res["signals"] = signals + if checkpoints: res["checkpoints"] = checkpoints + if access_logs: res["accessLogs"] = access_logs + + if max_sessions is not None: + res["pagination"] = { + "offset": offset, + "limit": max_sessions, + "total": len(all_sessions), + "hasMore": offset + max_sessions < len(all_sessions) + } + return res + + def set_project_profile(kv: StateKV, project: str, profile: Dict[str, Any]) -> Dict[str, Any]: profile["updatedAt"] = datetime.datetime.utcnow().isoformat() + "Z" kv.set(KV.profiles, project, profile) diff --git a/src/viewer/index.html b/src/viewer/index.html index 9445b63b38f197791859d084a5e4d85e7fb7e753..6c1c365a408a70381425671c461b8fa1d248ad71 100644 --- a/src/viewer/index.html +++ b/src/viewer/index.html @@ -1868,6 +1868,7 @@ sessions.forEach(function(s) { var path = s.project ? String(s.project).trim() : ''; if (!path) return; + if (!path.includes('/') && !path.includes('\\')) return; if (!folderMap[path]) { folderMap[path] = { id: path, @@ -1889,6 +1890,7 @@ memories.forEach(function(m) { var path = m.project ? String(m.project).trim() : ''; if (!path) return; + if (!path.includes('/') && !path.includes('\\')) return; if (!folderMap[path]) { // If the folder is not in sessions, create it folderMap[path] = {