Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
<p align="center">
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-recall.svg"><img src="assets/tags/stat-recall.svg" alt="95.2% retrieval R@5" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tokens.svg"><img src="assets/tags/stat-tokens.svg" alt="92% fewer tokens" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tools.svg"><img src="assets/tags/stat-tools.svg" alt="51 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tools.svg"><img src="assets/tags/stat-tools.svg" alt="53 MCP tools" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-hooks.svg"><img src="assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-deps.svg"><img src="assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture>
<picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tests.svg"><img src="assets/tags/stat-tests.svg" alt="950+ tests passing" height="38" /></picture>
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -773,7 +773,7 @@ npm install @xenova/transformers

<h2 id="mcp-server"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-mcp.svg"><img src="assets/tags/section-mcp.svg" alt="MCP Server" height="32" /></picture></h2>

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`.

Expand Down Expand Up @@ -1163,7 +1163,7 @@ Create `~/.agentmemory/.env`:

<h2 id="api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-api.svg"><img src="assets/tags/section-api.svg" alt="API" height="32" /></picture></h2>

121 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer <secret>` 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 <secret>` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.

<details>
<summary>Key endpoints</summary>
Expand Down
19 changes: 19 additions & 0 deletions plugin/skills/commit-context/SKILL.md
Original file line number Diff line number Diff line change
@@ -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 <start>,<end> <file>` when a line range is given, `git log -L :<function>:<file>` when a function name is given, and `git log -n 1 -- <file>` 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: "<full-sha>"`. If the MCP tool is unavailable, fall back to HTTP: `GET $AGENTMEMORY_URL/agentmemory/session/by-commit?sha=<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.
20 changes: 20 additions & 0 deletions plugin/skills/commit-history/SKILL.md
Original file line number Diff line number Diff line change
@@ -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=<name>`, `repo=<url-or-fragment>`, and `limit=<n>` 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: 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
- 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.
21 changes: 21 additions & 0 deletions plugin/skills/handoff/SKILL.md
Original file line number Diff line number Diff line change
@@ -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: 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 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 `?`).
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.
25 changes: 25 additions & 0 deletions plugin/skills/recap/SKILL.md
Original file line number Diff line number Diff line change
@@ -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 <n>` -> the most recent N sessions
- bare numeric -> treat as `last <n>`
- 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.
98 changes: 98 additions & 0 deletions src/hooks/post-commit.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> {
const h: Record<string, string> = { "Content-Type": "application/json" };
if (SECRET) h["Authorization"] = `Bearer ${SECRET}`;
return h;
}

async function git(args: string[], cwd: string): Promise<string | null> {
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<string, unknown> = {};
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();
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
37 changes: 37 additions & 0 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1204,6 +1204,43 @@ 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 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) }] },
};
}

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,
Expand Down
25 changes: 25 additions & 0 deletions src/mcp/tools-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] = [
Expand Down
1 change: 1 addition & 0 deletions src/state/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
Loading