Skip to content

feat(commits): link agent sessions to git commits - #498

Merged
rohitg00 merged 3 commits into
mainfrom
feat/commit-link-v2
May 18, 2026
Merged

feat(commits): link agent sessions to git commits#498
rohitg00 merged 3 commits into
mainfrom
feat/commit-link-v2

Conversation

@rohitg00

@rohitg00 rohitg00 commented May 18, 2026

Copy link
Copy Markdown
Owner

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.

  • Storage: new KV.commits namespace holds CommitLink records keyed by full SHA. Session.commitShas[] provides the forward back-reference.
  • REST:
    • 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= returns { commit, sessions } with the linked sessions hydrated.
    • GET /agentmemory/commits?branch=&repo=&limit= lists recent links, filtered and sorted desc by linkedAt, limit clamp 1..500 (default 100).
  • Hook: src/hooks/post-commit.ts shells git rev-parse / log / diff-tree, then POSTs to /agentmemory/session/commit. Honors AGENTMEMORY_URL, AGENTMEMORY_SECRET, AGENTMEMORY_CWD, AGENTMEMORY_SESSION_ID, AGENTMEMORY_COMMIT_SHA. Best-effort, 1500 ms timeout. Bundles to dist/hooks/ and plugin/scripts/ via the existing tsdown hook-entries list.
  • MCP: two new tools — memory_commit_lookup, memory_commits — registered in the standalone MCP server and the tools registry.
  • Skills (user-invocable Claude Code 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 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; parses last <n> / today / this week.

No new dependencies. Schema migration is purely additive (commitShas? is optional; the commits namespace 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-commit

The hook needs AGENTMEMORY_URL reachable (default http://localhost:3111). If the agent set AGENTMEMORY_SESSION_ID in 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 with sessionId supplied.

Test plan

  • pnpm build produces dist/hooks/post-commit.mjs and plugin/scripts/post-commit.mjs.
  • POST /agentmemory/session/commit with a fresh sha returns { commit } and writes to KV.commits.
  • Re-posting the same sha with a different sessionId merges into sessionIds[] and keeps the original linkedAt.
  • GET /agentmemory/session/by-commit?sha=<sha> returns { commit, sessions } with sessions hydrated.
  • GET /agentmemory/commits?limit=10 returns most-recent-first, capped to 10.
  • MCP memory_commit_lookup returns the same payload shape as the REST call.
  • MCP memory_commits filters by branch and repo correctly.
  • Installing the post-commit symlink in a sample repo and running git commit --allow-empty -m test writes a record.
  • Each plugin skill resolves on first invocation against an instance with data; no skill mentions a product name other than agentmemory.
  • No regression in existing /agentmemory/session/start and /agentmemory/session/end flows.

Summary by CodeRabbit

  • New Features

    • Added four user-invocable skills: commit-history, commit-context, handoff, and recap to list, trace, resume, and summarize agent sessions.
    • Surface linked commit/session details and important observations when available.
  • Chores

    • Enabled automatic post-commit capture and commit↔session linking with new API/tools to store and query links.
    • Updated tests, build entries, and documentation counts to reflect additions.

Review Change Stack

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.
@vercel

vercel Bot commented May 18, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
agentmemory Ready Ready Preview, Comment May 18, 2026 10:15am

Request Review

@coderabbitai

coderabbitai Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a6d1204a-c720-4e9b-9907-2247df4f9730

📥 Commits

Reviewing files that changed from the base of the PR and between cf614ab and 7f73c08.

📒 Files selected for processing (3)
  • AGENTS.md
  • README.md
  • src/index.ts
✅ Files skipped from review due to trivial changes (3)
  • AGENTS.md
  • src/index.ts
  • README.md

📝 Walkthrough

Walkthrough

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

Changes

Commit tracking and session linkage

Layer / File(s) Summary
Data model and storage schema
src/types.ts, src/state/schema.ts
CommitLink interface added; Session.commitShas?: string[] added; KV.commits namespace introduced.
Post-commit hook capture and bundling
src/hooks/post-commit.ts, tsdown.config.ts
Node.js post-commit hook collects git metadata (sha, branch, author, timestamp, files), posts to /agentmemory/session/commit with optional Bearer auth; hook entry added to build config.
HTTP API endpoints and MCP tool infrastructure
src/triggers/api.ts, src/mcp/tools-registry.ts, src/mcp/server.ts, test/mcp-standalone.test.ts
Adds POST /agentmemory/session/commit to upsert commit links and merge into sessions; GET /agentmemory/session/by-commit to fetch commit + sessions; GET /agentmemory/commits to list/filter commits; registers MCP tools memory_commit_lookup and memory_commits; updates CORE_TOOLS test expectation.
User-invocable skills for commit context
plugin/skills/commit-context/SKILL.md, plugin/skills/commit-history/SKILL.md, plugin/skills/handoff/SKILL.md, plugin/skills/recap/SKILL.md
Adds four skill specs describing argument parsing, MCP-tool-first flows with HTTP fallbacks, and formatted outputs: commit-context, commit-history, handoff, and recap.
Documentation and startup counts
AGENTS.md, README.md, src/index.ts
Updates documented MCP tool and REST endpoint counts and the runtime "Ready" log to reflect added routes/tools.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 A hook now watches commits bloom and grow,
Linking code to sessions, row after row,
Four new skills let curious devs explore,
Tracing the steps of work they did before.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(commits): link agent sessions to git commits' directly and accurately describes the primary change: adding commit-link functionality to tie agent sessions to git commits.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/commit-link-v2

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9061da5 and c85b331.

📒 Files selected for processing (11)
  • plugin/skills/commit-context/SKILL.md
  • plugin/skills/commit-history/SKILL.md
  • plugin/skills/handoff/SKILL.md
  • plugin/skills/recap/SKILL.md
  • src/hooks/post-commit.ts
  • src/mcp/server.ts
  • src/mcp/tools-registry.ts
  • src/state/schema.ts
  • src/triggers/api.ts
  • src/types.ts
  • tsdown.config.ts

Comment thread plugin/skills/commit-history/SKILL.md Outdated
Comment thread plugin/skills/handoff/SKILL.md Outdated
Comment thread src/mcp/server.ts Outdated
Comment thread src/triggers/api.ts Outdated
- 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.
@rohitg00
rohitg00 merged commit 249d8ff into main May 18, 2026
5 checks passed
@rohitg00
rohitg00 deleted the feat/commit-link-v2 branch May 18, 2026 10:19
rohitg00 added a commit that referenced this pull request May 18, 2026
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.
rohitg00 added a commit to cl0ckt0wer/agentmemory that referenced this pull request May 18, 2026
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.
healdigital pushed a commit to healdigital/agentmemory that referenced this pull request Jul 27, 2026
* 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.
healdigital pushed a commit to healdigital/agentmemory that referenced this pull request Jul 27, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant