Spaces:
Configuration error
feat: add Python plugin system, multi-agent connect CLI, and MCP tool expansions
Browse files- plugin/scripts/: Python-native hook scripts replacing Node.js .mjs hooks
(session_start, prompt_submit, pre/post_tool_use, stop, session_end, etc.)
- plugin/hooks/: hook manifests for Claude Code and Codex
- src/connect.py: CLI to wire MCP + hooks into Claude, Codex, Hermes, Antigravity, Kiro
- src/app.py: add /enrich, /crystals/auto, /claude-bridge/sync endpoints;
new MCP tools (memory_observations, memory_lessons, memory_reflect, memory_diagnose,
memory_forget, memory_export, memory_consolidate, memory_lesson_search);
fix agent_observe/agent_remember to not require agentId; parse_mcp_list_arg for
concepts/files accepting both string and array; enrich_search_results on all search paths
- src/functions.py: extract build_project_profile(); add export_data(); timeline sessionId filter
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Files changed (50)
- plugin/.claude-plugin/plugin.jsonAdded+13
- plugin/.codex-plugin/plugin.jsonAdded+15
- plugin/.mcp.copilot.jsonAdded+15
- plugin/.mcp.jsonAdded+13
- plugin/hooks/hooks.codex.jsonAdded+67
- plugin/hooks/hooks.copilot.jsonAdded+72
- plugin/hooks/hooks.jsonAdded+125
- plugin/plugin.jsonAdded+15
- plugin/scripts/hook_utils.pyAdded+91
- plugin/scripts/mcp_stdio.pyAdded+99
- plugin/scripts/notification.pyAdded+43
- plugin/scripts/post_tool_failure.pyAdded+50
- plugin/scripts/post_tool_use.pyAdded+98
- plugin/scripts/pre_compact.pyAdded+30
- plugin/scripts/pre_tool_use.pyAdded+67
- plugin/scripts/prompt_submit.pyAdded+41
- plugin/scripts/session_end.pyAdded+34
- plugin/scripts/session_start.pyAdded+47
- plugin/scripts/stop.pyAdded+28
- plugin/scripts/subagent_start.pyAdded+40
- plugin/scripts/subagent_stop.pyAdded+47
- plugin/scripts/task_completed.pyAdded+46
- plugin/skills/_shared/TROUBLESHOOTING.mdAdded+38
- plugin/skills/agentmemory-agents/REFERENCE.mdAdded+27
- plugin/skills/agentmemory-agents/SKILL.mdAdded+34
- plugin/skills/agentmemory-architecture/SKILL.mdAdded+33
- plugin/skills/agentmemory-config/REFERENCE.mdAdded+42
- plugin/skills/agentmemory-config/SKILL.mdAdded+37
- plugin/skills/agentmemory-hooks/REFERENCE.mdAdded+20
- plugin/skills/agentmemory-hooks/SKILL.mdAdded+39
- plugin/skills/agentmemory-mcp-tools/REFERENCE.mdAdded+65
- plugin/skills/agentmemory-mcp-tools/SKILL.mdAdded+39
- plugin/skills/agentmemory-rest-api/REFERENCE.mdAdded+129
- plugin/skills/agentmemory-rest-api/SKILL.mdAdded+43
- plugin/skills/commit-context/EXAMPLES.mdAdded+71
- plugin/skills/commit-context/SKILL.mdAdded+64
- plugin/skills/commit-history/EXAMPLES.mdAdded+71
- plugin/skills/commit-history/SKILL.mdAdded+62
- plugin/skills/forget/EXAMPLES.mdAdded+75
- plugin/skills/forget/SKILL.mdAdded+66
- plugin/skills/handoff/EXAMPLES.mdAdded+56
- plugin/skills/handoff/SKILL.mdAdded+68
- plugin/skills/recall/EXAMPLES.mdAdded+74
- plugin/skills/recall/SKILL.mdAdded+60
- plugin/skills/recap/EXAMPLES.mdAdded+60
- plugin/skills/recap/SKILL.mdAdded+63
- plugin/skills/remember/EXAMPLES.mdAdded+67
- plugin/skills/remember/SKILL.mdAdded+61
- plugin/skills/session-history/EXAMPLES.mdAdded+59
- plugin/skills/session-history/SKILL.mdAdded+61
12345678910111213{ "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/"]}123456789101112131415{ "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"}123456789101112131415{ "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": ["*"] } }}12345678910111213{ "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}" } } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667{ "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\"" } ] } ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "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\"" } ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125{ "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\"" } ] } ] }}123456789101112131415{ "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"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import osimport sysimport jsonimport urllib.requestimport urllib.errorimport subprocessimport threadingfrom 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 utilityload_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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899#!/usr/bin/env python3"""stdio MCP wrapper — bridges Claude Code's MCP stdio protocol to theagentmemory Flask HTTP API running on localhost.
Usage: python mcp_stdio.py"""import sysimport jsonimport 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()12345678910111213141516171819202122232425262728293031323334353637383940414243#!/usr/bin/env pythonimport sysimport jsonimport timefrom datetime import datetimefrom 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/usr/bin/env pythonimport sysimport jsonimport timefrom datetime import datetimefrom 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798#!/usr/bin/env pythonimport sysimport jsonimport timefrom datetime import datetimefrom 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()123456789101112131415161718192021222324252627282930#!/usr/bin/env pythonimport sysimport osimport jsonfrom 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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#!/usr/bin/env pythonimport sysimport osimport jsonfrom 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()1234567891011121314151617181920212223242526272829303132333435363738394041#!/usr/bin/env pythonimport sysimport jsonimport timefrom datetime import datetimefrom 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()12345678910111213141516171819202122232425262728293031323334#!/usr/bin/env pythonimport sysimport osimport jsonimport timefrom 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#!/usr/bin/env pythonimport sysimport jsonimport timefrom 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()12345678910111213141516171819202122232425262728#!/usr/bin/env pythonimport sysimport jsonimport timefrom 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()12345678910111213141516171819202122232425262728293031323334353637383940#!/usr/bin/env pythonimport sysimport jsonimport timefrom datetime import datetimefrom 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()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#!/usr/bin/env pythonimport sysimport jsonimport timefrom datetime import datetimefrom 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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546#!/usr/bin/env pythonimport sysimport jsonimport timefrom datetime import datetimefrom 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()1234567891011121314151617181920212223242526272829303132333435363738# Troubleshooting agentmemory skills
Shared recovery steps for all user-invocable agentmemory skills. Each skill'sTroubleshooting 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 RESTAPI 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=<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 arestart before either transport sees it.123456789101112131415161718192021222324252627# 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.
<!-- AUTOGEN:agents START - generated by scripts/skills/generate.ts, do not edit by hand -->`agentmemory connect <agent>` 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). |<!-- AUTOGEN:agents END -->12345678910111213141516171819202122232425262728293031323334---name: agentmemory-agentsdescription: 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 <agent>` 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
```bashagentmemory 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 <name>` 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/`.123456789101112131415161718192021222324252627282930313233---name: agentmemory-architecturedescription: 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.123456789101112131415161718192021222324252627282930313233343536373839404142# 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.
<!-- AUTOGEN:env START - generated by scripts/skills/generate.ts, do not edit by hand -->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`<!-- AUTOGEN:env END -->12345678910111213141516171819202122232425262728293031323334353637---name: agentmemory-configdescription: 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`:
```envANTHROPIC_API_KEY=sk-ant-...AGENTMEMORY_AUTO_COMPRESS=trueAGENTMEMORY_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 <N>` or `--instance <N>`.
## 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/`.1234567891011121314151617181920# 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.
<!-- AUTOGEN:hooks START - generated by scripts/skills/generate.ts, do not edit by hand -->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`<!-- AUTOGEN:hooks END -->123456789101112131415161718192021222324252627282930313233343536373839---name: agentmemory-hooksdescription: 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`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# 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.
<!-- AUTOGEN:tools START - generated by scripts/skills/generate.ts, do not edit by hand -->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.<!-- AUTOGEN:tools END -->123456789101112131415161718192021222324252627282930313233343536373839---name: agentmemory-mcp-toolsdescription: 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129# 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.
<!-- AUTOGEN:rest START - generated by scripts/skills/generate.ts, do not edit by hand -->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` |<!-- AUTOGEN:rest END -->12345678910111213141516171819202122232425262728293031323334353637383940414243---name: agentmemory-rest-apidescription: 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# livenesscurl -fsS http://localhost:3111/agentmemory/livez
# savecurl -X POST http://localhost:3111/agentmemory/remember \ -H "Content-Type: application/json" \ -d '{"content":"chose JWT refresh rotation","concepts":["jwt-refresh-rotation"]}'
# recallcurl -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`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# 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:
```bashgit blame -L 40,52 src/auth/refresh.ts# 9a1b2c3d (dev 2026-06-07) ... retry on revoked token```
Look it up:
```jsonmemory_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?"
```bashgit log -L :validateScope:src/auth/scope.ts -n 1# 1122aabb ...```
```jsonmemory_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."
```bashgit log -n 1 -- src/middleware/limit.ts```
Take the SHA, run `memory_commit_lookup`, present commit plus linked session inthe same shape as example 1.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364---name: commit-contextdescription: 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
```bashgit blame -L 40,52 src/auth/refresh.ts # -> SHA 9a1b2c3d```
```jsonmemory_commit_lookup { "sha": "9a1b2c3d4e5f60718293a4b5c6d7e8f901234567" }```
Expected output:
```text9a1b2c3 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 <start>,<end> <file>` for a line range; `git log -L :<function>:<file>` for a function; `git log -n 1 -- <file>` for a bare path.2. Look it up: `memory_commit_lookup { "sha": "<full-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 wasrefactoring auth" from the diff alone.
RIGHT: "This commit predates session linking, so there is no recorded agentsession. 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.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# commit-history worked examples
## 1. Branch filter
User: "Show agent commits on main."
Invocation:
```jsonmemory_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:
```jsonmemory_commits { "limit": 5 }```
Render the five newest linked commits in the same format.
## 3. Empty result
User: "Show agent commits on release-2.0."
```jsonmemory_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:
```httpGET /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.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162---name: commit-historydescription: 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
```jsonmemory_commits { "branch": "main", "limit": 20 }```
Expected output:
```text9a1b2c3 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 meansthe filter matched nothing, not that work is missing.
## Workflow
1. Parse `$ARGUMENTS` for `branch=<name>`, `repo=<url-or-fragment>`, `limit=<n>`. 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` beforeappending 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# forget worked examples
## 1. Delete a leaked secret
User: "Forget that note where I pasted the API key."
Search:
```jsonmemory_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:
```jsonmemory_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:
```jsonmemory_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:
```jsonmemory_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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566---name: forgetdescription: 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
```jsonmemory_smart_search { "query": "old api key in config", "limit": 20 }```
Show the matches, get a yes, then:
```jsonmemory_governance_delete { "memoryIds": ["abc12345", "def67890"], "reason": "user privacy request" }```
Expected output:
```textFound 2 matching memories. Confirmed. Deleted 2 memories.```
## Why
This is destructive and irreversible. Show exactly what will be deleted and getan 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 afteran 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.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# handoff worked examples
## 1. Resume with an open question
User: "Where were we?"
Project cwd: `/Users/dev/app`. Invocation:
```jsonmemory_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:
```jsonmemory_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 startwith `/Users/dev/repo-a/`. Pick the real `repo-a` session instead, or fall backto 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?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768---name: handoffdescription: 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
```jsonmemory_sessions { "limit": 20 }```
Pick the most recent session whose `cwd` matches this project, then:`memory_recall { "query": "<session top concepts>", "limit": 10 }`.
Expected output:
```textResuming 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 nevergets 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 theproject 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.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# recall worked examples
## 1. Hit on a past decision
User: "Did we ever decide how to cache sessions?"
Invocation:
```jsonmemory_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:
```jsonmemory_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:
```jsonmemory_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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960---name: recalldescription: 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
```jsonmemory_smart_search { "query": "jwt refresh token rotation", "limit": 10 }```
Expected output:
```text2 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 sessionid, 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 lastweek" 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# recap worked examples
## 1. This week
User: "Recap this week."
Window: last 7 days. Invocation:
```jsonmemory_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:
```jsonmemory_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?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263---name: recapdescription: 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
```jsonmemory_sessions { "limit": 30 }```
Then per surviving session: `memory_recall { "query": "<top concepts>", "limit": 3 }`.
Expected output:
```text2026-06-07 7f3a9c2 · "Auth refresh rework" · 14 obs · completed - [8] Rotate refresh tokens on every use3 sessions across 2 days, 41 observations.```
## Why
Only summarize sessions and observations the tools returned. An empty window isa real answer, not a prompt to invent activity.
## Workflow
1. Parse `$ARGUMENTS`: `today` = current local date; `this week` = last 7 days; `last <n>` 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" frommemory 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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# 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:
```jsonmemory_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:
```jsonmemory_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:
```jsonmemory_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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061---name: rememberdescription: 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
```jsonmemory_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:
```textSaved 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 specificconcepts 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.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# session-history worked examples
## 1. Standard timeline
User: "Show me the session history."
Invocation:
```jsonmemory_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?"
```jsonmemory_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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061---name: session-historydescription: 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
```jsonmemory_sessions { "limit": 20 }```
Expected output:
```text7f3a9c2 · app · 2026-06-07 09:00 · completed · 14 obs - decision: Rotate refresh tokens on every useb21d004 · 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 areal 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 steadyprogress" and add ones you remember from the conversation.
RIGHT: show exactly the two sessions returned, each with its real id, status, andobservation 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.