mirror of
https://github.com/rohitg00/agentmemory.git
synced 2026-09-14 20:16:33 +08:00
249d8ff032
* 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 <n> / 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.
* 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:<sha>` and `session:<sessionId>` 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.
* 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.
4.5 KiB
4.5 KiB
agentmemory — Agent Instructions
Architecture
agentmemory 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.
- Engine: iii-sdk (WebSocket to iii-engine on port 49134)
- State: File-based SQLite via iii-engine's StateModule (
./data/state_store.db) - Build: TypeScript → ESM via tsdown, output to
dist/ - Test: vitest (
npm testexcludes integration tests)
Consistency Rules
When adding or removing MCP tools, you MUST update ALL of the following:
src/mcp/tools-registry.ts— tool definition +getAllTools()arraysrc/mcp/server.ts— handler case in themcp::tools::callswitchsrc/triggers/api.ts— REST endpoint registrationsrc/index.ts— function registration + endpoint count in the log linetest/mcp-standalone.test.ts— tool count assertionREADME.md— tool counts (search for "MCP tools")plugin/.claude-plugin/plugin.json— tool count in description
When adding REST endpoints, you MUST update:
src/triggers/api.ts— endpoint registrationsrc/index.ts— endpoint count in the log lineREADME.md— endpoint count (search for "REST endpoints" and "endpoints on port")
When bumping version, you MUST update ALL of the following:
package.json— version fieldsrc/version.ts— VERSION constant and type unionsrc/types.ts— ExportData version unionsrc/functions/export-import.ts— supportedVersions settest/export-import.test.ts— version assertionplugin/.claude-plugin/plugin.json— version field
When adding new KV scopes:
src/state/schema.ts— add to the KV objectsrc/types.ts— add the corresponding interface
When adding new audit operations:
src/types.ts— add to AuditEntry.operation union type
Code Patterns
Function Registration
sdk.registerFunction(
"mem::your-function",
async (data: { ... }) => {
// validate inputs
// do work via kv.get/kv.set/kv.list
// record audit via recordAudit()
return { success: true, ... };
},
);
REST Endpoint Registration
sdk.registerFunction("api::your-endpoint", async (req: ApiRequest) => {
const denied = checkAuth(req, secret);
if (denied) return denied;
const body = req.body as Record<string, unknown>;
// validate + whitelist fields (never pass raw body to sdk.trigger)
const result = await sdk.trigger({
function_id: "mem::your-function",
payload: { ... },
});
return { status_code: 200, body: result };
});
sdk.registerTrigger({
type: "http",
function_id: "api::your-endpoint",
config: { api_path: "/agentmemory/your-path", http_method: "POST" },
});
MCP Tool Handler
case "memory_your_tool": {
// validate args with typeof checks
// parse CSV args: args.field.split(",").map(t => t.trim()).filter(Boolean)
const result = await sdk.trigger({
function_id: "mem::your-function",
payload: { ... },
});
return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };
}
Hook Scripts
Hook 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. Always use try/catch with AbortSignal.timeout() for best-effort calls.
Coding Standards
- TypeScript, ESM only (
"type": "module") - No code comments explaining WHAT — use clear naming instead
- Use
fingerprintId()for content-addressable dedup,generateId()for unique IDs - Parallel operations where possible (
Promise.allfor independent kv writes/reads) - Input validation at system boundaries (MCP handlers, REST endpoints)
- REST endpoints must whitelist fields — never pass raw request body to
sdk.trigger() - Use
recordAudit()for state-changing operations - Timestamps: capture once with
new Date().toISOString()and reuse
Testing
- All tests must pass before PR:
npm test(950+ tests) - Mock pattern:
vi.mock("iii-sdk")with mocksdk.trigger,kv.get/set/list - Test files go in
test/with.test.tsextension - Follow existing patterns in
test/crystallize.test.tsfor function tests
Current Stats (v0.9.16)
- 53 MCP tools (8 visible by default,
AGENTMEMORY_TOOLS=allfor all) - 124 REST endpoints
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 4 skills
- 50+ iii functions
- 950+ tests