{"owner":"rohitg00","repo":"agentmemory","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["AGENTS.md"],"files":{"AGENTS.md":"# agentmemory — Agent Instructions\n\n## Architecture\n\nagentmemory is a persistent memory system for AI coding agents, built on iii-engine's three primitives (Worker/Function/Trigger). Everything goes through `registerFunction`/`registerTrigger`/`sdk.trigger()` — never bypass iii-engine with standalone SQLite or in-process alternatives.\n\n- **Engine**: iii-sdk (WebSocket to iii-engine on port 49134)\n- **State**: File-based SQLite via iii-engine's StateModule (`./data/state_store.db`)\n- **Build**: TypeScript → ESM via tsdown, output to `dist/`\n- **Test**: vitest (`npm test` excludes integration tests)\n\n## Consistency Rules\n\n**When adding or removing MCP tools, you MUST update ALL of the following:**\n1. `src/mcp/tools-registry.ts` — tool definition + `getAllTools()` array\n2. `src/mcp/server.ts` — handler case in the `mcp::tools::call` switch\n3. `src/triggers/api.ts` — REST endpoint registration\n4. `src/index.ts` — function registration + endpoint count in the log line\n5. `test/mcp-standalone.test.ts` — tool count assertion\n6. `README.md` — tool counts (search for \"MCP tools\")\n7. `plugin/.claude-plugin/plugin.json` — tool count in description\n8. `plugin/plugin.json` and `plugin/.mcp.copilot.json` (when present) — tool count or MCP exposure\n\n**When adding REST endpoints, you MUST update:**\n1. `src/triggers/api.ts` — endpoint registration\n2. `src/index.ts` — endpoint count in the log line\n3. `README.md` — endpoint count (search for \"REST endpoints\" and \"endpoints on port\")\n\n**When bumping version, you MUST update ALL of the following:**\n1. `package.json` — version field\n2. `src/version.ts` — VERSION constant and type union\n3. `src/types.ts` — ExportData version union\n4. `src/functions/export-import.ts` — supportedVersions set\n5. `test/export-import.test.ts` — version assertion\n6. `plugin/.claude-plugin/plugin.json` — version field\n7. `plugin/plugin.json` (when present) — version field\n\n**When adding new KV scopes:**\n1. `src/state/schema.ts` — add to the KV object\n2. `src/types.ts` — add the corresponding interface\n\n**When adding new audit operations:**\n1. `src/types.ts` — add to AuditEntry.operation union type\n\n## Code Patterns\n\n### Function Registration\n```typescript\nsdk.registerFunction(\n  \"mem::your-function\",\n  async (data: { ... }) => {\n    // validate inputs\n    // do work via kv.get/kv.set/kv.list\n    // record audit via recordAudit()\n    return { success: true, ... };\n  },\n);\n```\n\n### REST Endpoint Registration\n```typescript\nsdk.registerFunction(\"api::your-endpoint\", async (req: ApiRequest) => {\n  const denied = checkAuth(req, secret);\n  if (denied) return denied;\n  const body = req.body as Record<string, unknown>;\n  // validate + whitelist fields (never pass raw body to sdk.trigger)\n  const result = await sdk.trigger({\n    function_id: \"mem::your-function\",\n    payload: { ... },\n  });\n  return { status_code: 200, body: result };\n});\nsdk.registerTrigger({\n  type: \"http\",\n  function_id: \"api::your-endpoint\",\n  config: { api_path: \"/agentmemory/your-path\", http_method: \"POST\" },\n});\n```\n\n### MCP Tool Handler\n```typescript\ncase \"memory_your_tool\": {\n  // validate args with typeof checks\n  // parse CSV args: args.field.split(\",\").map(t => t.trim()).filter(Boolean)\n  const result = await sdk.trigger({\n    function_id: \"mem::your-function\",\n    payload: { ... },\n  });\n  return { status_code: 200, body: { content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }] } };\n}\n```\n\n### Hook Scripts\nHook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). They read JSON from stdin, make HTTP calls to the REST API, and exit. There are two patterns depending on whether Claude Code consumes the script's stdout:\n\n- **Context-injecting hooks** (`pre-tool-use`, `pre-compact`, `session-start`) write recalled context to stdout for Claude Code to inject. These MUST use `try/catch` with `await fetch(..., { signal: AbortSignal.timeout(N) })` — the script has to wait for the response before exiting, and the timeout is the only bound on hang time.\n- **Telemetry-only hooks** (`notification`, `post-tool-failure`, `post-tool-use`, `prompt-submit`, `stop`, `session-end`, `subagent-start`, `subagent-stop`, `task-completed`) write nothing to stdout. These MUST use fire-and-forget `fetch(..., { signal: AbortSignal.timeout(N) }).catch(() => {})` paired with `setTimeout(() => process.exit(0), 500).unref()`. The unawaited fetch dispatches the request; the unref'd `setTimeout` force-exits the process after the request has been flushed to the local daemon's socket buffer (~500ms is enough for single-request hooks; use 1500ms for multi-request hooks like `stop` and `session-end` so all fetches have time to start, especially when `AGENTMEMORY_URL` points to a remote daemon). Without the `setTimeout` Node keeps the event loop alive waiting for any in-flight fetch to settle, which means the hook still blocks Claude Code's next-prompt boundary for up to the AbortSignal duration — exactly the bug fire-and-forget is meant to fix.\n\n## Coding Standards\n\n- TypeScript, ESM only (`\"type\": \"module\"`)\n- No code comments explaining WHAT — use clear naming instead\n- Use `fingerprintId()` for content-addressable dedup, `generateId()` for unique IDs\n- Parallel operations where possible (`Promise.all` for independent kv writes/reads)\n- Input validation at system boundaries (MCP handlers, REST endpoints)\n- REST endpoints must whitelist fields — never pass raw request body to `sdk.trigger()`\n- Use `recordAudit()` for state-changing operations\n- Timestamps: capture once with `new Date().toISOString()` and reuse\n\n## Testing\n\n- All tests must pass before PR: `npm test` (1,596+ tests)\n- Mock pattern: `vi.mock(\"iii-sdk\")` with mock `sdk.trigger`, `kv.get/set/list`\n- Test files go in `test/` with `.test.ts` extension\n- Follow existing patterns in `test/crystallize.test.ts` for function tests\n\n## Current Stats (v0.9.29)\n\n- 54 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all)\n- 130 REST endpoints\n- 6 MCP resources, 3 MCP prompts\n- 12 hooks, 15 skills\n- 260+ iii functions\n- 1,596+ tests\n"}}