feat(commits): link agent sessions to git commits - #498
Conversation
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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
✅ Files skipped from review due to trivial changes (3)
📝 WalkthroughWalkthroughThis PR adds commit capture via a post-commit hook, persisted commit/session linkage in KV, MCP tools and HTTP endpoints for lookup/listing, four user-invocable skills for commit/session workflows, and documentation/startup-count updates. ChangesCommit tracking and session linkage
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
ESLint skipped: no ESLint configuration detected in root package.json. To enable, add Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@plugin/skills/commit-history/SKILL.md`:
- Line 12: The fallback HTTP URL builder for the memory_commits MCP should
URL-encode query params before interpolation: when constructing the GET to
$AGENTMEMORY_URL/agentmemory/commits use a safe encoder (e.g.,
encodeURIComponent or URLSearchParams) for branch and repo (and any string
filters) so values containing ?, &, # do not corrupt the query; keep
Authorization: Bearer $AGENTMEMORY_SECRET unchanged. Update the fallback
construction referenced in the memory_commits fallback logic and the SKILL.md
example so the docs and implementation consistently show encoded query
parameters.
In `@plugin/skills/handoff/SKILL.md`:
- Around line 10-13: Resolve $ARGUMENTS into an absolute projectPath (accepting
relative inputs) by normalizing and resolving against the current working
directory (e.g., path.resolve(process.cwd(), ARGUMENTS || ".")), then call the
memory_sessions MCP tool and filter sessions by comparing normalized session.cwd
to projectPath using directory-boundary checks (require session.cwd ===
projectPath OR session.cwd.startsWith(projectPath + path.sep) to avoid false
matches on shared prefixes); prefer sessions with status "completed" over
"abandoned" and pick the most recent among matches, and if no match remains,
fall back to the single most recent session overall.
In `@src/mcp/server.ts`:
- Around line 1219-1222: The current serial loop over linkRecord.sessionIds
calls kv.get repeatedly and should be converted to parallel reads: map
linkRecord.sessionIds (or empty array) to an array of kv.get(KV.sessions, sid)
promises, await Promise.all on that array, then filter out falsy results and
push them into the sessions array (or assign sessions to the filtered result).
Update the code around linkRecord.sessionIds, kv.get, KV.sessions and the
sessions variable to use Promise.all so independent session reads run
concurrently.
In `@src/triggers/api.ts`:
- Around line 634-659: The read-modify-write on CommitLink (variables existing,
link) and Session (variable session) is non-atomic and can lose concurrent
updates; replace these with atomic upsert/update operations (or a KV
transaction) that merge sessionIds and commitShas instead of overwriting them.
Specifically, use the KV store's atomic update/transaction API to
fetch-and-update KV.commits for sha by merging existing.sessionIds with the new
sessionId (deduplicated) and preserving other fields (shortSha, branch, repo,
message, author, authoredAt, files, linkedAt), and in the same atomic operation
update KV.sessions for sessionId by merging existing.commitShas with sha
(deduplicated); ensure both merges are done via the KV atomic updater (or a
single transaction) so concurrent requests cannot drop entries.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: fd0c483e-86d7-4a6a-9529-5096ca6c43c1
📒 Files selected for processing (11)
plugin/skills/commit-context/SKILL.mdplugin/skills/commit-history/SKILL.mdplugin/skills/handoff/SKILL.mdplugin/skills/recap/SKILL.mdsrc/hooks/post-commit.tssrc/mcp/server.tssrc/mcp/tools-registry.tssrc/state/schema.tssrc/triggers/api.tssrc/types.tstsdown.config.ts
- 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.
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.
Six verbatim quotes pulled from the Product Hunt launch discussion, each linked back to the source comment for verification. Quotes cover the spectrum: concrete use cases (Peter Neyra on product-pivot tracking, Pranav Prakash on two weeks of production use), framing endorsements (Alper Tayfur, Mia Taylor on agentmemory's intent versus storage-only tools), and onboarding feel (Zoe Alexandra). Section header: "BUILDERS USING AGENTMEMORY" with the title "IN THE WILD." in the gold accent. 3-column grid above 980px, 2-column at tablet, single-column on mobile. Cards are clickable and route to the original PH comment thread. Slotted between Compare and Agents — social proof after the comparison table, before the agent-list grid. Matches the existing FeaturedIn aesthetic (charcoal border + iron fill + gold hover) so the section feels native, not bolted on. website/lib/generated-meta.json also picked up the v0.9.20 bump + the two new MCP tools shipped via #498 (memory_commit_lookup, memory_commits) — clean by-product of `npm run build`. - website/components/Testimonials.tsx: 6 verbatim quotes + attribution - website/components/Testimonials.module.css: 3/2/1 grid + card chrome - website/app/page.tsx: wired between Compare and Agents - website/lib/generated-meta.json: regenerated against v0.9.20 Site builds clean.
Brings 10 days of main into the OpenCode plugin branch so the PR no longer conflicts on README + carries the new surfaces that shipped between v0.9.2 (when the branch opened) and v0.9.20: - v0.9.19 commit linking (rohitg00#498): KV.commits + Session.commitShas + memory_commit_lookup/memory_commits MCP tools (53 total now, plugin badge bumped from 51) - v0.9.19 Azure OpenAI v1 URL pattern (rohitg00#462) + Dijkstra graph retrieval (rohitg00#463) - v0.9.19 env passthrough on MCP server entries (rohitg00#460): ${VAR} expansion for AGENTMEMORY_URL / AGENTMEMORY_SECRET so one wired entry covers local + remote - v0.9.20 Codex Stop revert (rohitg00#501) README conflict resolution kept main's richer "Other agents" table shape (env-passthrough block + per-host config-file column + programmatic-access section) and re-added the OpenCode entry as two rows: "OpenCode (MCP only)" for the bare MCP wiring + "OpenCode (full plugin)" pointing at this plugin's 22-hook capture surface. src/triggers/api.ts auto-merged: PR's 3-line title->summary/firstPrompt addition (lines 535, 543, 544) survived alongside main's other api.ts churn since. plugin/opencode/plugin.json bumped 0.9.4 -> 0.9.20 to match the canonical version everything else ships on. plugin/opencode/README.md MCP-tool badge bumped 51 -> 53.
* 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.
Six verbatim quotes pulled from the Product Hunt launch discussion, each linked back to the source comment for verification. Quotes cover the spectrum: concrete use cases (Peter Neyra on product-pivot tracking, Pranav Prakash on two weeks of production use), framing endorsements (Alper Tayfur, Mia Taylor on agentmemory's intent versus storage-only tools), and onboarding feel (Zoe Alexandra). Section header: "BUILDERS USING AGENTMEMORY" with the title "IN THE WILD." in the gold accent. 3-column grid above 980px, 2-column at tablet, single-column on mobile. Cards are clickable and route to the original PH comment thread. Slotted between Compare and Agents — social proof after the comparison table, before the agent-list grid. Matches the existing FeaturedIn aesthetic (charcoal border + iron fill + gold hover) so the section feels native, not bolted on. website/lib/generated-meta.json also picked up the v0.9.20 bump + the two new MCP tools shipped via rohitg00#498 (memory_commit_lookup, memory_commits) — clean by-product of `npm run build`. - website/components/Testimonials.tsx: 6 verbatim quotes + attribution - website/components/Testimonials.module.css: 3/2/1 grid + card chrome - website/app/page.tsx: wired between Compare and Agents - website/lib/generated-meta.json: regenerated against v0.9.20 Site builds clean.
Summary
Adds a commit-link layer that ties captured agent sessions to the git commits they produced. You can ask "what session wrote this code" and "what commits did this session ship", in either direction, without leaving agentmemory.
KV.commitsnamespace holdsCommitLinkrecords keyed by full SHA.Session.commitShas[]provides the forward back-reference.POST /agentmemory/session/commitupserts a link (sha, branch, repo, message, author, authoredAt, files, sessionId). Merges sessionIds on re-link and preserveslinkedAt.GET /agentmemory/session/by-commit?sha=returns{ commit, sessions }with the linked sessions hydrated.GET /agentmemory/commits?branch=&repo=&limit=lists recent links, filtered and sorted desc bylinkedAt, limit clamp 1..500 (default 100).src/hooks/post-commit.tsshellsgit rev-parse / log / diff-tree, then POSTs to/agentmemory/session/commit. HonorsAGENTMEMORY_URL,AGENTMEMORY_SECRET,AGENTMEMORY_CWD,AGENTMEMORY_SESSION_ID,AGENTMEMORY_COMMIT_SHA. Best-effort, 1500 ms timeout. Bundles todist/hooks/andplugin/scripts/via the existing tsdown hook-entries list.memory_commit_lookup,memory_commits— registered in the standalone MCP server and the tools registry.commit-context— traces a file/function/line viagit blameplusmemory_commit_lookupplusmemory_recall.commit-history— lists agent-linked commits; parsesbranch=/repo=/limit=from$ARGUMENTS.handoff— resumes the most recent session in the current cwd; surfaces an unanswered user-facing question before the brief.recap— summarizes the last N sessions for the current cwd, grouped by date; parseslast <n>/today/this week.No new dependencies. Schema migration is purely additive (
commitShas?is optional; thecommitsnamespace is created on first write).Wire-up
In any repo where you want commits to be linked automatically:
ln -sf "$(realpath node_modules/agentmemory/dist/hooks/post-commit.mjs)" .git/hooks/post-commit chmod +x .git/hooks/post-commitThe hook needs
AGENTMEMORY_URLreachable (defaulthttp://localhost:3111). If the agent setAGENTMEMORY_SESSION_IDin the shell env during its session, that's what the link will reference; otherwise the commit is captured without a session id and can be linked later via the same endpoint withsessionIdsupplied.Test plan
pnpm buildproducesdist/hooks/post-commit.mjsandplugin/scripts/post-commit.mjs.POST /agentmemory/session/commitwith a fresh sha returns{ commit }and writes toKV.commits.sessionIdmerges intosessionIds[]and keeps the originallinkedAt.GET /agentmemory/session/by-commit?sha=<sha>returns{ commit, sessions }with sessions hydrated.GET /agentmemory/commits?limit=10returns most-recent-first, capped to 10.memory_commit_lookupreturns the same payload shape as the REST call.memory_commitsfilters by branch and repo correctly.git commit --allow-empty -m testwrites a record./agentmemory/session/startand/agentmemory/session/endflows.Summary by CodeRabbit
New Features
Chores