From c85b3312bc0604d10acd1195a2d35735b2011570 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Mon, 18 May 2026 10:12:36 +0100 Subject: [PATCH 1/3] feat(commits): link agent sessions to git commits Adds a commit-link layer so memories captured during an agent session can be traced back to the git commit they produced, and vice versa. What ships: - KV.commits namespace storing CommitLink records keyed by full SHA. - Session.commitShas[] back-reference for fast forward lookup. - POST /agentmemory/session/commit upserts a link (sha, branch, repo, message, author, authoredAt, files, sessionId); merges sessionIds on re-link and preserves linkedAt. - GET /agentmemory/session/by-commit?sha= hydrates the link plus its sessions. - GET /agentmemory/commits?branch=&repo=&limit= lists recent links, filtered and sorted desc by linkedAt, limit clamp 1..500 (default 100). - src/hooks/post-commit.ts shells git rev-parse/log/diff-tree and POSTs to /agentmemory/session/commit. Honors AGENTMEMORY_URL, AGENTMEMORY_SECRET, AGENTMEMORY_CWD, AGENTMEMORY_SESSION_ID, AGENTMEMORY_COMMIT_SHA. Best-effort, 1500 ms timeout. Wired into tsdown hookEntries so it bundles to dist/hooks/ and plugin/scripts/. - Two MCP tools: memory_commit_lookup, memory_commits. - Four user-invocable plugin skills: - commit-context: traces a file/function/line via git blame plus memory_commit_lookup plus memory_recall. - commit-history: lists agent-linked commits; parses branch=/repo=/ limit= from $ARGUMENTS. - handoff: resumes the most recent session for cwd; surfaces an unanswered user-facing question before the brief. - recap: summarizes the last N sessions for cwd, grouped by date; parses last / today / this week. Wire-up to capture from a real repo: ln -sf "$(realpath node_modules/agentmemory/dist/hooks/post-commit.mjs)" .git/hooks/post-commit chmod +x .git/hooks/post-commit No new dependencies. Additive only. --- plugin/skills/commit-context/SKILL.md | 19 ++++ plugin/skills/commit-history/SKILL.md | 20 ++++ plugin/skills/handoff/SKILL.md | 21 +++++ plugin/skills/recap/SKILL.md | 25 +++++ src/hooks/post-commit.ts | 98 +++++++++++++++++++ src/mcp/server.ts | 38 ++++++++ src/mcp/tools-registry.ts | 25 +++++ src/state/schema.ts | 1 + src/triggers/api.ts | 130 +++++++++++++++++++++++++- src/types.ts | 14 +++ tsdown.config.ts | 1 + 11 files changed, 390 insertions(+), 2 deletions(-) create mode 100644 plugin/skills/commit-context/SKILL.md create mode 100644 plugin/skills/commit-history/SKILL.md create mode 100644 plugin/skills/handoff/SKILL.md create mode 100644 plugin/skills/recap/SKILL.md create mode 100644 src/hooks/post-commit.ts diff --git a/plugin/skills/commit-context/SKILL.md b/plugin/skills/commit-context/SKILL.md new file mode 100644 index 0000000000..9ec0dae3bd --- /dev/null +++ b/plugin/skills/commit-context/SKILL.md @@ -0,0 +1,19 @@ +--- +name: commit-context +description: Trace a file, function, or line back to the agent session that produced its current commit. Use when the user asks "why is this code here", "what was the agent doing when this changed", 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 + +Run `git blame` (or `git log -L`) on the target file, function, or line in $ARGUMENTS to extract the most recent commit SHA that touched it. Use `git blame -L , ` when a line range is given, `git log -L ::` when a function name is given, and `git log -n 1 -- ` when only a path is given. + +With the SHA in hand, look up the linked agent session via the `memory_commit_lookup` MCP tool with `sha: ""`. If the MCP tool is unavailable, fall back to HTTP: `GET $AGENTMEMORY_URL/agentmemory/session/by-commit?sha=` with `Authorization: Bearer $AGENTMEMORY_SECRET` when the secret is set. + +Present the result as: +- The commit SHA, short SHA, branch, author, message +- The linked session(s): id, project, started/ended timestamps, observation count, summary if any +- A short list of the most important observations from that session (importance >= 7) when available via `memory_recall` + +Do not fabricate intent. If the commit has no linked session, say so plainly and surface only what `git show` reveals. If `memory_commit_lookup` returns an empty `commit: null` body, that means the commit predates session linking — do not invent a session. diff --git a/plugin/skills/commit-history/SKILL.md b/plugin/skills/commit-history/SKILL.md new file mode 100644 index 0000000000..094d4007c1 --- /dev/null +++ b/plugin/skills/commit-history/SKILL.md @@ -0,0 +1,20 @@ +--- +name: commit-history +description: List recent git commits that are linked to agent sessions, optionally filtered by branch or repo. Use when the user asks "show agent commits", "what has the agent shipped", or wants a list of 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 + +Parse `$ARGUMENTS` for optional `branch=`, `repo=`, and `limit=` tokens. A bare numeric token becomes the limit. Defaults: no branch filter, no repo filter, limit 100, max 500. + +Call the `memory_commits` MCP tool with the parsed filters. If the MCP tool is unavailable, fall back to HTTP: `GET $AGENTMEMORY_URL/agentmemory/commits?branch=<>&repo=<>&limit=<>` with `Authorization: Bearer $AGENTMEMORY_SECRET` when set. + +Render the result as a reverse-chronological list: +- Short SHA, branch, authored timestamp +- Commit message first line +- Linked session id(s) (first 8 chars each) and observation counts where present +- File count when `files` is provided + +If the result is empty, tell the user the filter matched no commits and suggest dropping the branch/repo filter. Do not invent commits. diff --git a/plugin/skills/handoff/SKILL.md b/plugin/skills/handoff/SKILL.md new file mode 100644 index 0000000000..e57ecba819 --- /dev/null +++ b/plugin/skills/handoff/SKILL.md @@ -0,0 +1,21 @@ +--- +name: handoff +description: Resume the most recent agent session for the current working directory. 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 + +Determine the current project path: use `$ARGUMENTS` if it looks like an absolute path, otherwise the current working directory. + +Call the `memory_sessions` MCP tool. From the result, pick the most recent session whose `cwd` matches the project path (or its prefix), preferring sessions with status `completed` over `abandoned`. If nothing matches, fall back to the single most recent session overall. + +Once a session is selected: +1. If the session ended on an unanswered user-facing question, surface that question FIRST as the lead. Look for it in `summary` or in the last few observations (type `conversation` with `narrative` ending in `?`). +2. Then summarize the session: title/summary, key files touched, key decisions or errors. Use `memory_recall` with a query derived from the session's top concepts to fetch supporting observations, limit 10. +3. End with a short "next step?" pointer the user can act on. + +If neither MCP tool is available, fall back to HTTP: `GET $AGENTMEMORY_URL/agentmemory/sessions` and `POST $AGENTMEMORY_URL/agentmemory/recall` with `Authorization: Bearer $AGENTMEMORY_SECRET` when set. + +Do not invent observations. If the most recent session has zero observations, say so and offer to start fresh. diff --git a/plugin/skills/recap/SKILL.md b/plugin/skills/recap/SKILL.md new file mode 100644 index 0000000000..eec5acc4ed --- /dev/null +++ b/plugin/skills/recap/SKILL.md @@ -0,0 +1,25 @@ +--- +name: recap +description: Summarize the last N agent sessions for the current project, grouped by date. Use when the user asks "recap", "what have we been doing", "this week", "today", 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 + +Parse `$ARGUMENTS` to determine the window: +- `today` -> sessions started on the current local date +- `this week` -> sessions started in the last 7 days +- `last ` -> the most recent N sessions +- bare numeric -> treat as `last ` +- empty -> default to `last 10` + +Call the `memory_sessions` MCP tool, then filter to the current project (match by `cwd` against the working directory). Apply the time window. Sort by `startedAt` descending. + +Group the surviving sessions by their local calendar date (YYYY-MM-DD). For each date: +- List each session: id (first 8 chars), title or first prompt, observation count, status +- Indent two or three highlight observations per session (importance >= 7) drawn from `memory_recall` with a per-session query, limit 3 + +End with a one-line total: "N sessions across M days, K observations." + +If MCP tools are unavailable, fall back to HTTP: `GET $AGENTMEMORY_URL/agentmemory/sessions` and `POST $AGENTMEMORY_URL/agentmemory/recall` with `Authorization: Bearer $AGENTMEMORY_SECRET` when set. Do not invent sessions; if the window is empty, say so. diff --git a/src/hooks/post-commit.ts b/src/hooks/post-commit.ts new file mode 100644 index 0000000000..30c54a9aca --- /dev/null +++ b/src/hooks/post-commit.ts @@ -0,0 +1,98 @@ +#!/usr/bin/env node + +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; + +const exec = promisify(execFile); + +function isSdkChildContext(payload: unknown): boolean { + if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; + if (!payload || typeof payload !== "object") return false; + return (payload as { entrypoint?: unknown }).entrypoint === "sdk-ts"; +} + +const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111"; +const SECRET = process.env["AGENTMEMORY_SECRET"] || ""; +const TIMEOUT_MS = 1500; + +function authHeaders(): Record { + const h: Record = { "Content-Type": "application/json" }; + if (SECRET) h["Authorization"] = `Bearer ${SECRET}`; + return h; +} + +async function git(args: string[], cwd: string): Promise { + try { + const { stdout } = await exec("git", args, { cwd, timeout: 1500 }); + return stdout.trim(); + } catch { + return null; + } +} + +async function main() { + let input = ""; + for await (const chunk of process.stdin) { + input += chunk; + } + + let data: Record = {}; + if (input.trim()) { + try { + data = JSON.parse(input); + } catch { + // Direct invocation from .git/hooks/post-commit may pass no stdin. + } + } + + if (isSdkChildContext(data)) return; + + const cwd = + (data.cwd as string) || + process.env["AGENTMEMORY_CWD"] || + process.cwd(); + const sessionId = + (data.session_id as string) || + process.env["AGENTMEMORY_SESSION_ID"] || + undefined; + + const sha = + process.env["AGENTMEMORY_COMMIT_SHA"] || + (await git(["rev-parse", "HEAD"], cwd)); + if (!sha) return; + + const branch = await git(["rev-parse", "--abbrev-ref", "HEAD"], cwd); + const repo = await git(["config", "--get", "remote.origin.url"], cwd); + const message = await git(["log", "-1", "--pretty=%B", sha], cwd); + const author = await git(["log", "-1", "--pretty=%an <%ae>", sha], cwd); + const authoredAt = await git(["log", "-1", "--pretty=%aI", sha], cwd); + const filesRaw = await git( + ["diff-tree", "--no-commit-id", "--name-only", "-r", sha], + cwd, + ); + const files = filesRaw ? filesRaw.split("\n").filter(Boolean) : undefined; + + const body = { + sessionId, + sha, + branch: branch || undefined, + repo: repo || undefined, + message: message || undefined, + author: author || undefined, + authoredAt: authoredAt || undefined, + files, + }; + + try { + await fetch(`${REST_URL}/agentmemory/session/commit`, { + method: "POST", + headers: authHeaders(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + } catch { + // best-effort + } +} + +main(); diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 21c2069a9e..d3bed39366 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -1204,6 +1204,44 @@ export function registerMcpEndpoints( }; } + case "memory_commit_lookup": { + const sha = asNonEmptyString(args.sha); + if (!sha) return { status_code: 400, body: { error: "sha required" } }; + const link = await kv.get(KV.commits, sha); + if (!link) { + return { + status_code: 200, + body: { content: [{ type: "text", text: JSON.stringify({ commit: null, sessions: [] }, null, 2) }] }, + }; + } + const linkRecord = link as { sessionIds?: string[] }; + const sessions = []; + for (const sid of linkRecord.sessionIds ?? []) { + const s = await kv.get(KV.sessions, sid); + if (s) sessions.push(s); + } + return { + status_code: 200, + body: { content: [{ type: "text", text: JSON.stringify({ commit: link, sessions }, null, 2) }] }, + }; + } + + case "memory_commits": { + const branch = typeof args.branch === "string" ? args.branch : undefined; + const repo = typeof args.repo === "string" ? args.repo : undefined; + const limit = Math.max(1, Math.min(500, asNumber(args.limit, 100) ?? 100)); + const all = await kv.list(KV.commits); + const filtered = (all as Array<{ branch?: string; repo?: string; linkedAt?: string }>) + .filter((c) => !branch || c.branch === branch) + .filter((c) => !repo || c.repo === repo) + .sort((a, b) => ((a.linkedAt ?? "") < (b.linkedAt ?? "") ? 1 : -1)) + .slice(0, limit); + return { + status_code: 200, + body: { content: [{ type: "text", text: JSON.stringify({ commits: filtered }, null, 2) }] }, + }; + } + default: return { status_code: 400, diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts index 82d7e7ce0c..3001cae75d 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -206,6 +206,31 @@ export const CORE_TOOLS: McpToolDef[] = [ required: ["memoryId"], }, }, + { + name: "memory_commit_lookup", + description: + "Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.", + inputSchema: { + type: "object", + properties: { + sha: { type: "string", description: "Full git commit SHA" }, + }, + required: ["sha"], + }, + }, + { + name: "memory_commits", + description: + "List recent commits linked to agent sessions, optionally filtered by branch or repo.", + inputSchema: { + type: "object", + properties: { + branch: { type: "string", description: "Filter by branch name" }, + repo: { type: "string", description: "Filter by remote URL" }, + limit: { type: "number", description: "Max results (default 100, max 500)" }, + }, + }, + }, ]; export const V040_TOOLS: McpToolDef[] = [ diff --git a/src/state/schema.ts b/src/state/schema.ts index 27f1958d50..8d0d90f043 100644 --- a/src/state/schema.ts +++ b/src/state/schema.ts @@ -46,6 +46,7 @@ export const KV = { slots: "mem:slots", globalSlots: "mem:slots:global", state: "mem:state", + commits: "mem:commits", } as const; export const STREAM = { diff --git a/src/triggers/api.ts b/src/triggers/api.ts index 6a65f23394..a93d34ebad 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -1,5 +1,5 @@ import type { ISdk, ApiRequest } from "iii-sdk"; -import type { Session, CompressedObservation, HookPayload } from "../types.js"; +import type { Session, CompressedObservation, HookPayload, CommitLink } from "../types.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; import { getLatestHealth } from "../health/monitor.js"; @@ -609,7 +609,133 @@ export function registerApiTriggers( }, }); - sdk.registerFunction("api::sessions", + sdk.registerFunction("api::session::commit", + async (req: ApiRequest): Promise => { + const body = (req.body ?? {}) as Record; + const sha = asNonEmptyString(body.sha); + if (!sha) { + return { + status_code: 400, + body: { error: "sha is required and must be a non-empty string" }, + }; + } + const sessionId = asNonEmptyString(body.sessionId) ?? undefined; + const branch = asNonEmptyString(body.branch) ?? undefined; + const repo = asNonEmptyString(body.repo) ?? undefined; + const message = asNonEmptyString(body.message) ?? undefined; + const author = asNonEmptyString(body.author) ?? undefined; + const authoredAt = asNonEmptyString(body.authoredAt) ?? undefined; + const files = Array.isArray(body.files) + ? (body.files as unknown[]).filter( + (f): f is string => typeof f === "string" && f.length > 0, + ) + : undefined; + + const existing = await kv.get(KV.commits, sha); + const sessionSet = new Set(existing?.sessionIds ?? []); + if (sessionId) sessionSet.add(sessionId); + + const link: CommitLink = { + sha, + shortSha: existing?.shortSha ?? sha.slice(0, 7), + branch: branch ?? existing?.branch, + repo: repo ?? existing?.repo, + message: message ?? existing?.message, + author: author ?? existing?.author, + authoredAt: authoredAt ?? existing?.authoredAt, + files: files ?? existing?.files, + sessionIds: Array.from(sessionSet), + linkedAt: existing?.linkedAt ?? new Date().toISOString(), + }; + await kv.set(KV.commits, sha, link); + + if (sessionId) { + const session = await kv.get(KV.sessions, sessionId); + if (session) { + const shaSet = new Set(session.commitShas ?? []); + shaSet.add(sha); + session.commitShas = Array.from(shaSet); + await kv.set(KV.sessions, sessionId, session); + } + } + + return { status_code: 200, body: { commit: link } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::commit", + config: { + api_path: "/agentmemory/session/commit", + http_method: "POST", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::session::by-commit", + async (req: ApiRequest): Promise => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const sha = asNonEmptyString(req.query_params?.["sha"]); + if (!sha) { + return { + status_code: 400, + body: { error: "sha is required and must be a non-empty string" }, + }; + } + const link = await kv.get(KV.commits, sha); + if (!link) { + return { + status_code: 404, + body: { error: "no sessions linked to this commit" }, + }; + } + const sessions: Session[] = []; + for (const sid of link.sessionIds ?? []) { + const s = await kv.get(KV.sessions, sid); + if (s) sessions.push(s); + } + return { status_code: 200, body: { commit: link, sessions } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::session::by-commit", + config: { + api_path: "/agentmemory/session/by-commit", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::commits", + async (req: ApiRequest): Promise => { + const authErr = checkAuth(req, secret); + if (authErr) return authErr; + const branch = asNonEmptyString(req.query_params?.["branch"]); + const repo = asNonEmptyString(req.query_params?.["repo"]); + const rawLimit = parseOptionalInt(req.query_params?.["limit"]); + const limit = Math.max(1, Math.min(500, rawLimit ?? 100)); + const all = await kv.list(KV.commits); + const filtered = all + .filter((c) => !branch || c.branch === branch) + .filter((c) => !repo || c.repo === repo) + .sort((a, b) => ((a.linkedAt ?? "") < (b.linkedAt ?? "") ? 1 : -1)) + .slice(0, limit); + return { status_code: 200, body: { commits: filtered } }; + }, + ); + sdk.registerTrigger({ + type: "http", + function_id: "api::commits", + config: { + api_path: "/agentmemory/commits", + http_method: "GET", + middleware_function_ids: ["middleware::api-auth"], + }, + }); + + sdk.registerFunction("api::sessions", async (req: ApiRequest): Promise => { const authErr = checkAuth(req, secret); if (authErr) return authErr; diff --git a/src/types.ts b/src/types.ts index ca1bcefb76..eb01feceef 100644 --- a/src/types.ts +++ b/src/types.ts @@ -10,6 +10,20 @@ export interface Session { tags?: string[]; firstPrompt?: string; summary?: string; + commitShas?: string[]; +} + +export interface CommitLink { + sha: string; + shortSha: string; + branch?: string; + repo?: string; + message?: string; + author?: string; + authoredAt?: string; + files?: string[]; + sessionIds: string[]; + linkedAt: string; } export interface RawObservation { diff --git a/tsdown.config.ts b/tsdown.config.ts index 2c30a48b37..4475609a42 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -13,6 +13,7 @@ const hookEntries = [ "src/hooks/task-completed.ts", "src/hooks/stop.ts", "src/hooks/session-end.ts", + "src/hooks/post-commit.ts", ]; const shared = { From cf614ab17616aa06925122c1eb196122f404182b Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Mon, 18 May 2026 11:07:15 +0100 Subject: [PATCH 2/3] fix(commits): address CI + review findings on commit-link feature - Update mcp-standalone.test.ts to expect 14 CORE_TOOLS (was 12) now that memory_commit_lookup and memory_commits are registered. Restores CI on Node 20 and 22. - Wrap CommitLink upsert and session.commitShas mutation in withKeyedLock to prevent lost updates when concurrent post-commit hooks race against each other or against api::session::commit callers. Locks keyed by `commit:` and `session:` so unrelated writers do not serialize. - Parallelize hydration of linked sessions via Promise.all in both api::session::by-commit and the memory_commit_lookup MCP handler; serial kv.get loops dragged response time for commits with many sessions. - Sharpen handoff SKILL.md project-path matching: resolve relative $ARGUMENTS to an absolute normalized path and require directory- boundary equality, not raw string prefix, so sibling repos sharing a prefix do not collide. - Sharpen commit-history SKILL.md HTTP fallback: build the /agentmemory/commits URL with URL-encoded query values so branch and repo values containing `?`, `&`, or `#` cannot corrupt the request. --- plugin/skills/commit-history/SKILL.md | 2 +- plugin/skills/handoff/SKILL.md | 4 +- src/mcp/server.ts | 9 ++--- src/triggers/api.ts | 53 ++++++++++++++------------- test/mcp-standalone.test.ts | 4 +- 5 files changed, 37 insertions(+), 35 deletions(-) diff --git a/plugin/skills/commit-history/SKILL.md b/plugin/skills/commit-history/SKILL.md index 094d4007c1..599c32206f 100644 --- a/plugin/skills/commit-history/SKILL.md +++ b/plugin/skills/commit-history/SKILL.md @@ -9,7 +9,7 @@ The user wants a list of agent-linked commits. Filter args: $ARGUMENTS Parse `$ARGUMENTS` for optional `branch=`, `repo=`, and `limit=` tokens. A bare numeric token becomes the limit. Defaults: no branch filter, no repo filter, limit 100, max 500. -Call the `memory_commits` MCP tool with the parsed filters. If the MCP tool is unavailable, fall back to HTTP: `GET $AGENTMEMORY_URL/agentmemory/commits?branch=<>&repo=<>&limit=<>` with `Authorization: Bearer $AGENTMEMORY_SECRET` when set. +Call the `memory_commits` MCP tool with the parsed filters. If the MCP tool is unavailable, fall back to HTTP: build `GET $AGENTMEMORY_URL/agentmemory/commits` and append each filter as a URL-encoded query parameter (use `URLSearchParams` or `encodeURIComponent` on `branch`, `repo`, and `limit`) so values containing `?`, `&`, or `#` cannot corrupt the request. Include `Authorization: Bearer $AGENTMEMORY_SECRET` when set. Render the result as a reverse-chronological list: - Short SHA, branch, authored timestamp diff --git a/plugin/skills/handoff/SKILL.md b/plugin/skills/handoff/SKILL.md index e57ecba819..6343700195 100644 --- a/plugin/skills/handoff/SKILL.md +++ b/plugin/skills/handoff/SKILL.md @@ -7,9 +7,9 @@ user-invocable: true The user wants to resume work. Optional cwd override: $ARGUMENTS -Determine the current project path: use `$ARGUMENTS` if it looks like an absolute path, otherwise the current working directory. +Determine the current project path: if `$ARGUMENTS` is provided, resolve it to an absolute, normalized path (accept relative inputs, e.g. `path.resolve(process.cwd(), $ARGUMENTS)`); otherwise use the current working directory. -Call the `memory_sessions` MCP tool. From the result, pick the most recent session whose `cwd` matches the project path (or its prefix), preferring sessions with status `completed` over `abandoned`. If nothing matches, fall back to the single most recent session overall. +Call the `memory_sessions` MCP tool. From the result, pick the most recent session whose normalized `cwd` matches the project path with a directory-boundary check — equality OR `session.cwd.startsWith(projectPath + path.sep)` OR `projectPath.startsWith(session.cwd + path.sep)`. Do NOT use a raw string prefix match: it produces false positives across unrelated repos that share a path prefix (e.g. `/repo-a` vs `/repo-a-staging`). Prefer sessions with status `completed` over `abandoned`. If nothing matches, fall back to the single most recent session overall. Once a session is selected: 1. If the session ended on an unanswered user-facing question, surface that question FIRST as the lead. Look for it in `summary` or in the last few observations (type `conversation` with `narrative` ending in `?`). diff --git a/src/mcp/server.ts b/src/mcp/server.ts index d3bed39366..b3b0585d4a 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -1215,11 +1215,10 @@ export function registerMcpEndpoints( }; } const linkRecord = link as { sessionIds?: string[] }; - const sessions = []; - for (const sid of linkRecord.sessionIds ?? []) { - const s = await kv.get(KV.sessions, sid); - if (s) sessions.push(s); - } + const fetched = await Promise.all( + (linkRecord.sessionIds ?? []).map((sid) => kv.get(KV.sessions, sid)), + ); + const sessions = fetched.filter((s) => s !== null); return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify({ commit: link, sessions }, null, 2) }] }, diff --git a/src/triggers/api.ts b/src/triggers/api.ts index a93d34ebad..c57b52aabb 100644 --- a/src/triggers/api.ts +++ b/src/triggers/api.ts @@ -1,5 +1,6 @@ import type { ISdk, ApiRequest } from "iii-sdk"; import type { Session, CompressedObservation, HookPayload, CommitLink } from "../types.js"; +import { withKeyedLock } from "../state/keyed-mutex.js"; import { KV } from "../state/schema.js"; import { StateKV } from "../state/kv.js"; import { getLatestHealth } from "../health/monitor.js"; @@ -631,32 +632,35 @@ export function registerApiTriggers( ) : undefined; - const existing = await kv.get(KV.commits, sha); - const sessionSet = new Set(existing?.sessionIds ?? []); - if (sessionId) sessionSet.add(sessionId); - - const link: CommitLink = { - sha, - shortSha: existing?.shortSha ?? sha.slice(0, 7), - branch: branch ?? existing?.branch, - repo: repo ?? existing?.repo, - message: message ?? existing?.message, - author: author ?? existing?.author, - authoredAt: authoredAt ?? existing?.authoredAt, - files: files ?? existing?.files, - sessionIds: Array.from(sessionSet), - linkedAt: existing?.linkedAt ?? new Date().toISOString(), - }; - await kv.set(KV.commits, sha, link); + const link = await withKeyedLock(`commit:${sha}`, async () => { + const existing = await kv.get(KV.commits, sha); + const sessionSet = new Set(existing?.sessionIds ?? []); + if (sessionId) sessionSet.add(sessionId); + const merged: CommitLink = { + sha, + shortSha: existing?.shortSha ?? sha.slice(0, 7), + branch: branch ?? existing?.branch, + repo: repo ?? existing?.repo, + message: message ?? existing?.message, + author: author ?? existing?.author, + authoredAt: authoredAt ?? existing?.authoredAt, + files: files ?? existing?.files, + sessionIds: Array.from(sessionSet), + linkedAt: existing?.linkedAt ?? new Date().toISOString(), + }; + await kv.set(KV.commits, sha, merged); + return merged; + }); if (sessionId) { - const session = await kv.get(KV.sessions, sessionId); - if (session) { + await withKeyedLock(`session:${sessionId}`, async () => { + const session = await kv.get(KV.sessions, sessionId); + if (!session) return; const shaSet = new Set(session.commitShas ?? []); shaSet.add(sha); session.commitShas = Array.from(shaSet); await kv.set(KV.sessions, sessionId, session); - } + }); } return { status_code: 200, body: { commit: link } }; @@ -690,11 +694,10 @@ export function registerApiTriggers( body: { error: "no sessions linked to this commit" }, }; } - const sessions: Session[] = []; - for (const sid of link.sessionIds ?? []) { - const s = await kv.get(KV.sessions, sid); - if (s) sessions.push(s); - } + const fetched = await Promise.all( + (link.sessionIds ?? []).map((sid) => kv.get(KV.sessions, sid)), + ); + const sessions = fetched.filter((s): s is Session => s !== null); return { status_code: 200, body: { commit: link, sessions } }; }, ); diff --git a/test/mcp-standalone.test.ts b/test/mcp-standalone.test.ts index e5670ec646..b48eade966 100644 --- a/test/mcp-standalone.test.ts +++ b/test/mcp-standalone.test.ts @@ -68,8 +68,8 @@ describe("Tools Registry", () => { } }); - it("CORE_TOOLS has 12 items", () => { - expect(CORE_TOOLS.length).toBe(12); + it("CORE_TOOLS has 14 items", () => { + expect(CORE_TOOLS.length).toBe(14); }); it("V040_TOOLS has 8 items", () => { From 7f73c088fe00a7944ab6d0246da2dcdc5212b3db Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Mon, 18 May 2026 11:15:33 +0100 Subject: [PATCH 3/3] chore(consistency): bump documented tool and endpoint counts Bring README.md, AGENTS.md, and the boot log in src/index.ts in line with the live tool registry (53 MCP tools, +2 from this branch) and the live REST registration (124 endpoints, +3 from this branch). The Consistency test in test/consistency.test.ts derives both counts from source and asserts the markdown matches; this commit only updates the literal numbers, no behavior change. --- AGENTS.md | 4 ++-- README.md | 8 ++++---- src/index.ts | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b5d156b284..ebcf35844b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,8 +111,8 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import). ## Current Stats (v0.9.16) -- 51 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all) -- 121 REST endpoints +- 53 MCP tools (8 visible by default, `AGENTMEMORY_TOOLS=all` for all) +- 124 REST endpoints - 6 MCP resources, 3 MCP prompts - 12 hooks, 4 skills - 50+ iii functions diff --git a/README.md b/README.md index 841842231e..abfbb6e012 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@

95.2% retrieval R@5 92% fewer tokens - 51 MCP tools + 53 MCP tools 12 auto hooks 0 external DBs 950+ tests passing @@ -396,7 +396,7 @@ Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cl ### Claude Code (one block, paste it) ``` -Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 51 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. +Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 53 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113. ``` ### Codex CLI (Codex plugin platform) @@ -773,7 +773,7 @@ npm install @xenova/transformers

MCP Server

-51 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent. +53 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent. > **MCP shim vs full server:** the published `@agentmemory/mcp` package is a thin shim. It exposes the full 51-tool surface **only when it can reach a running agentmemory server** via `AGENTMEMORY_URL` (proxy mode). With no server reachable, the shim falls back to a 7-tool local set (`memory_save`, `memory_recall`, `memory_smart_search`, `memory_sessions`, `memory_export`, `memory_audit`, `memory_governance_delete`). The `AGENTMEMORY_TOOLS=core|all` env var is a *server-side* flag — setting it in the shim's `env` block has no effect. If you see only 7 tools in Cursor / OpenCode / Gemini CLI, start `npx @agentmemory/agentmemory` (or the Docker stack) and set `AGENTMEMORY_URL=http://localhost:3111`. @@ -1163,7 +1163,7 @@ Create `~/.agentmemory/.env`:

API

-121 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer ` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers. +124 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer ` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.
Key endpoints diff --git a/src/index.ts b/src/index.ts index 904e08febb..b9b9e84dcb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -473,7 +473,7 @@ async function main() { `Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`, ); bootLog( - `REST API: 121 endpoints at http://localhost:${config.restPort}/agentmemory/*`, + `REST API: 124 endpoints at http://localhost:${config.restPort}/agentmemory/*`, ); bootLog( `MCP surface (opt-in via \`npx @agentmemory/mcp\`): ${getAllTools().length} tools · 6 resources · 3 prompts`,