Skip to content

fix: scope git worktrees to shared project id#935

Closed
wbugitlab1 wants to merge 2 commits into
rohitg00:mainfrom
wbugitlab1:fix/worktree-project-scope-wbu
Closed

fix: scope git worktrees to shared project id#935
wbugitlab1 wants to merge 2 commits into
rohitg00:mainfrom
wbugitlab1:fix/worktree-project-scope-wbu

Conversation

@wbugitlab1

@wbugitlab1 wbugitlab1 commented Jun 14, 2026

Copy link
Copy Markdown

Summary

  • resolve project scope through a canonical git project id instead of raw cwd path
  • make linked worktrees for the same repository share the same git:<hash> project scope
  • preserve explicit AGENTMEMORY_PROJECT_ID / AGENTMEMORY_PROJECT_NAME overrides and non-git basename fallback
  • expose optional project arguments through MCP/REST memory operations

Verification

  • npm test -- test/hook-project.test.ts test/pre-tool-use-project.test.ts test/worktree-project-scope.test.ts test/api-memories-project.test.ts test/mcp-project-scope.test.ts test/mcp-standalone.test.ts test/mcp-standalone-proxy.test.ts test/remember-project-scope.test.ts test/context-injection.test.ts test/copilot-plugin.test.ts passed: 10 files, 97 tests
  • npm run build passed
  • npm run skills:check passed
  • gitleaks detect --source . --log-opts origin/main..HEAD --redact passed: 2 commits scanned, no leaks
  • semgrep scan --config p/default --error --metrics=off $(git diff --name-only origin/main..HEAD) passed: 39 files, 0 findings

Notes

  • This branch rebuilds the same code changes with consistent DCO metadata on both commits.
  • Full npm test previously failed only unrelated test/fs-watcher.test.ts tests outside this PR scope.
  • Vercel may report "Authorization required to deploy"; that is deployment authorization, not a code failure.

Summary by CodeRabbit

Release Notes

  • New Features
    • Added project-scoped memory filtering via a new optional project parameter across tools and APIs.
    • Added AGENTMEMORY_PROJECT_ID / AGENTMEMORY_PROJECT_NAME environment variables for explicit project selection.
    • Added token_budget to memory_recall.
  • Improvements
    • Project IDs and cwd are now normalized consistently across hooks/observations, using deterministic Git-based hashing for stability across worktrees.
  • Documentation
    • Updated configuration and MCP/tool reference documentation for the new options.
  • Tests
    • Added coverage for project scoping, worktrees, and API filtering (including unscoped legacy memories).

Signed-off-by: wbu <wbu@live.de>
@vercel

vercel Bot commented Jun 14, 2026

Copy link
Copy Markdown

@wbugitlab1 is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 426e414a-bc6e-4c9d-9f7a-3a4ec94d2fc6

📥 Commits

Reviewing files that changed from the base of the PR and between eda7537 and 7f460bb.

📒 Files selected for processing (23)
  • plugin/scripts/notification.mjs
  • plugin/scripts/post-tool-failure.mjs
  • plugin/scripts/post-tool-use.mjs
  • plugin/scripts/pre-compact.mjs
  • plugin/scripts/pre-tool-use.mjs
  • plugin/scripts/prompt-submit.mjs
  • plugin/scripts/session-start.mjs
  • plugin/scripts/subagent-start.mjs
  • plugin/scripts/subagent-stop.mjs
  • plugin/scripts/task-completed.mjs
  • src/hooks/_project.ts
  • src/hooks/notification.ts
  • src/hooks/post-tool-failure.ts
  • src/hooks/post-tool-use.ts
  • src/hooks/pre-compact.ts
  • src/hooks/pre-tool-use.ts
  • src/hooks/prompt-submit.ts
  • src/hooks/session-start.ts
  • src/hooks/subagent-start.ts
  • src/hooks/subagent-stop.ts
  • src/hooks/task-completed.ts
  • test/hook-project.test.ts
  • test/pre-tool-use-project.test.ts
🚧 Files skipped from review as they are similar to previous changes (20)
  • src/hooks/prompt-submit.ts
  • src/hooks/subagent-stop.ts
  • src/hooks/post-tool-failure.ts
  • src/hooks/pre-compact.ts
  • plugin/scripts/pre-tool-use.mjs
  • plugin/scripts/prompt-submit.mjs
  • plugin/scripts/post-tool-failure.mjs
  • src/hooks/task-completed.ts
  • src/hooks/session-start.ts
  • src/hooks/pre-tool-use.ts
  • plugin/scripts/pre-compact.mjs
  • plugin/scripts/task-completed.mjs
  • src/hooks/_project.ts
  • test/pre-tool-use-project.test.ts
  • plugin/scripts/notification.mjs
  • plugin/scripts/subagent-stop.mjs
  • plugin/scripts/post-tool-use.mjs
  • plugin/scripts/subagent-start.mjs
  • plugin/scripts/session-start.mjs
  • test/hook-project.test.ts

📝 Walkthrough

Walkthrough

The PR replaces basename-based project identification with a stable SHA-256-hashed Git common-directory identifier across all hook scripts and plugin .mjs files. It adds AGENTMEMORY_PROJECT_ID/AGENTMEMORY_PROJECT_NAME environment override support, introduces resolveCwd for normalized cwd handling, extends memory_recall MCP tool with a project parameter, adds project-scoped filtering to the memories REST API, and covers all changes with new and updated tests.

Changes

Canonical Git-based project scoping across hooks, MCP tools, and API

Layer / File(s) Summary
Core resolveProject and resolveCwd helpers
src/hooks/_project.ts
Rewrites internal Git helpers to use --git-common-dir + realpath + SHA-256; adds exported resolveCwd; updates resolveProject param to unknown with new resolution order: AGENTMEMORY_PROJECT_IDAGENTMEMORY_PROJECT_NAMEgit:<hash>basename.
TypeScript hook callsites
src/hooks/notification.ts, src/hooks/post-tool-failure.ts, src/hooks/post-tool-use.ts, src/hooks/pre-compact.ts, src/hooks/pre-tool-use.ts, src/hooks/prompt-submit.ts, src/hooks/session-start.ts, src/hooks/subagent-start.ts, src/hooks/subagent-stop.ts, src/hooks/task-completed.ts
All TypeScript hooks import resolveCwd and replace data.cwd type casts and process.cwd() fallbacks with resolveProject(data.cwd) and resolveCwd(data.cwd) in observe/enrich payloads.
Plugin scripts: inline resolveProject and ESM exports
plugin/scripts/notification.mjs, plugin/scripts/post-tool-failure.mjs, plugin/scripts/post-tool-use.mjs, plugin/scripts/pre-compact.mjs, plugin/scripts/pre-tool-use.mjs, plugin/scripts/prompt-submit.mjs, plugin/scripts/session-start.mjs, plugin/scripts/subagent-start.mjs, plugin/scripts/subagent-stop.mjs, plugin/scripts/task-completed.mjs, plugin/scripts/post-commit.mjs, plugin/scripts/session-end.mjs, plugin/scripts/stop.mjs
Inline-copies the new resolveProject/resolveCwd helpers into every plugin script, updates cwd payload fields, and normalizes ESM footer exports from export { }; to export {};.
MCP tool project parameter
src/mcp/tools-registry.ts, src/mcp/server.ts, src/mcp/standalone.ts
Adds optional project field to memory_recall input schema; threads args.project through server.ts into mem::search; extends standalone.ts to validate, proxy, and locally filter memory_save/memory_recall/memory_smart_search by project.
API project filtering and remember logging
src/triggers/api.ts, src/functions/remember.ts
Parses project query param and adds includeUnscoped=true flag to api::memories GET endpoint for project-scoped filtering; changes remember logs from project: value to hasProject: boolean.
Reference documentation
plugin/skills/agentmemory-config/REFERENCE.md, plugin/skills/agentmemory-mcp-tools/REFERENCE.md
Adds AGENTMEMORY_PROJECT_ID to the config reference (count 34→35); documents token_budget parameter in memory_recall tool reference.
Tests: hook-project and worktree scoping
test/hook-project.test.ts, test/worktree-project-scope.test.ts
Rewrites hook-project.test.ts with git-backed helpers and asserts canonical git:<hash> IDs, env-override precedence, and edge cases; adds worktree-project-scope.test.ts covering linked worktrees sharing scope, same-basename repos differing, and AGENTMEMORY_PROJECT_NAME override behavior.
Tests: pre-tool-use child process and MCP/API validation
test/pre-tool-use-project.test.ts, test/mcp-project-scope.test.ts, test/mcp-standalone-proxy.test.ts, test/mcp-standalone.test.ts, test/api-memories-project.test.ts, test/remember-project-scope.test.ts
Spawns pre-tool-use hook as child process to validate project resolution; adds MCP project forwarding and standalone local/proxy filtering tests; covers api::memories project filter, pagination, count, and unscoped-inclusion behavior; asserts hasProject log redaction.

Sequence Diagram(s)

sequenceDiagram
  participant Hook as Hook/Plugin Script
  participant ProjectTS as src/hooks/_project.ts
  participant Git as git rev-parse --git-common-dir
  participant REST as /agentmemory/observe or /enrich

  Hook->>ProjectTS: resolveProject(data.cwd)
  ProjectTS->>ProjectTS: resolveCwd(data.cwd) → normalized dir
  alt AGENTMEMORY_PROJECT_ID set
    ProjectTS-->>Hook: return trimmed PROJECT_ID
  else AGENTMEMORY_PROJECT_NAME set
    ProjectTS-->>Hook: return trimmed PROJECT_NAME
  else
    ProjectTS->>Git: execFileSync git rev-parse --git-common-dir
    Git-->>ProjectTS: common dir path
    ProjectTS->>ProjectTS: realpathSync → SHA-256 hash
    ProjectTS-->>Hook: return "git:<hash>"
  end
  Hook->>REST: POST {project: "git:<hash>", cwd: resolveCwd(data.cwd), ...}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • rohitg00/agentmemory#687: Both PRs update the same hook scripts to derive project via a shared resolveProject helper from src/hooks/_project.ts and send it in /agentmemory/observe payloads.
  • rohitg00/agentmemory#688: Modifies the same plugin script code paths (notification.mjs, post-tool-failure.mjs, post-tool-use.mjs, prompt-submit.mjs, etc.) that this PR also rewrites.

Suggested reviewers

  • rohitg00

Poem

🐰 Hoppity hop through the git common dir,
No more basename collisions, how perfectly clear!
A SHA-256 hash for each repo's true name,
Worktrees and siblings no longer the same.
resolveCwd trims the path nice and neat—
Project scoping complete, what a bunny-eared feat! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.79% 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 'fix: scope git worktrees to shared project id' accurately summarizes the main change, which is implementing canonical git project ID scoping for worktrees.
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 unit tests (beta)
  • Create PR with unit tests

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
test/hook-project.test.ts (1)

143-143: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use path.basename() for cross-platform fallback assertion

Line 143 hardcodes POSIX separators ("/"), so this assertion can fail on Windows paths. Use basename(dir) instead.

Proposed fix
-      expect(resolveProject(dir)).toBe(dir.split("/").pop());
+      expect(resolveProject(dir)).toBe(basename(dir));
🤖 Prompt for 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.

In `@test/hook-project.test.ts` at line 143, Replace the hardcoded POSIX path
separator in the assertion on line 143 of test/hook-project.test.ts. Instead of
using dir.split("/").pop(), use path.basename(dir) to ensure the test for the
resolveProject function works correctly across different operating systems
including Windows. This provides cross-platform compatibility for the test
assertion.
🧹 Nitpick comments (2)
test/worktree-project-scope.test.ts (1)

50-96: ⚡ Quick win

Align test doubles with repository mock pattern

This suite uses ad-hoc makeMockSdk/makeMockKV; repository test guidelines require the vi.mock("iii-sdk") pattern with sdk.trigger, kv.get, kv.set, and kv.list mocks for consistency with the rest of the suite.

As per coding guidelines, “test/**/*.test.ts: Mock pattern for tests: use vi.mock('iii-sdk') with mock implementations of sdk.trigger, kv.get, kv.set, kv.list; follow patterns in test/crystallize.test.ts.”

🤖 Prompt for 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.

In `@test/worktree-project-scope.test.ts` around lines 50 - 96, The test suite
uses custom ad-hoc mock factories makeMockKV and makeMockSdk instead of the
repository's standard mocking pattern. Replace these custom factory functions
with vi.mock('iii-sdk') that provides mock implementations for sdk.trigger,
kv.get, kv.set, and kv.list methods. Then update the registerMemorySearch
function to use the mocked sdk and kv modules directly instead of calling the
factory functions. Follow the mocking pattern demonstrated in
test/crystallize.test.ts for consistency with repository guidelines.

Source: Coding guidelines

src/hooks/_project.ts (1)

63-68: ⚡ Quick win

Remove WHAT-style resolution-order comment block.

This block explains implementation steps rather than intent; prefer self-documenting naming and keep only rationale comments when necessary.

As per coding guidelines, "In TypeScript source code, avoid code comments explaining WHAT — use clear naming instead."

🤖 Prompt for 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.

In `@src/hooks/_project.ts` around lines 63 - 68, Remove the entire multi-line
comment block that lists the resolution order steps (items 1 through 4) in
src/hooks/_project.ts. This comment explains WHAT the code does rather than WHY,
and should be replaced with self-documenting code and variable naming. If there
is important rationale about why this resolution order is necessary, condense it
into a brief single-line comment explaining the intent rather than the
implementation steps.

Source: Coding guidelines

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

Outside diff comments:
In `@test/hook-project.test.ts`:
- Line 143: Replace the hardcoded POSIX path separator in the assertion on line
143 of test/hook-project.test.ts. Instead of using dir.split("/").pop(), use
path.basename(dir) to ensure the test for the resolveProject function works
correctly across different operating systems including Windows. This provides
cross-platform compatibility for the test assertion.

---

Nitpick comments:
In `@src/hooks/_project.ts`:
- Around line 63-68: Remove the entire multi-line comment block that lists the
resolution order steps (items 1 through 4) in src/hooks/_project.ts. This
comment explains WHAT the code does rather than WHY, and should be replaced with
self-documenting code and variable naming. If there is important rationale about
why this resolution order is necessary, condense it into a brief single-line
comment explaining the intent rather than the implementation steps.

In `@test/worktree-project-scope.test.ts`:
- Around line 50-96: The test suite uses custom ad-hoc mock factories makeMockKV
and makeMockSdk instead of the repository's standard mocking pattern. Replace
these custom factory functions with vi.mock('iii-sdk') that provides mock
implementations for sdk.trigger, kv.get, kv.set, and kv.list methods. Then
update the registerMemorySearch function to use the mocked sdk and kv modules
directly instead of calling the factory functions. Follow the mocking pattern
demonstrated in test/crystallize.test.ts for consistency with repository
guidelines.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 92cf2504-fe6e-4c98-8b46-47f0449c8fb7

📥 Commits

Reviewing files that changed from the base of the PR and between f6f9e3c and eda7537.

📒 Files selected for processing (39)
  • plugin/scripts/notification.mjs
  • plugin/scripts/post-commit.mjs
  • plugin/scripts/post-tool-failure.mjs
  • plugin/scripts/post-tool-use.mjs
  • plugin/scripts/pre-compact.mjs
  • plugin/scripts/pre-tool-use.mjs
  • plugin/scripts/prompt-submit.mjs
  • plugin/scripts/session-end.mjs
  • plugin/scripts/session-start.mjs
  • plugin/scripts/stop.mjs
  • plugin/scripts/subagent-start.mjs
  • plugin/scripts/subagent-stop.mjs
  • plugin/scripts/task-completed.mjs
  • plugin/skills/agentmemory-config/REFERENCE.md
  • plugin/skills/agentmemory-mcp-tools/REFERENCE.md
  • src/functions/remember.ts
  • src/hooks/_project.ts
  • src/hooks/notification.ts
  • src/hooks/post-tool-failure.ts
  • src/hooks/post-tool-use.ts
  • src/hooks/pre-compact.ts
  • src/hooks/pre-tool-use.ts
  • src/hooks/prompt-submit.ts
  • src/hooks/session-start.ts
  • src/hooks/subagent-start.ts
  • src/hooks/subagent-stop.ts
  • src/hooks/task-completed.ts
  • src/mcp/server.ts
  • src/mcp/standalone.ts
  • src/mcp/tools-registry.ts
  • src/triggers/api.ts
  • test/api-memories-project.test.ts
  • test/hook-project.test.ts
  • test/mcp-project-scope.test.ts
  • test/mcp-standalone-proxy.test.ts
  • test/mcp-standalone.test.ts
  • test/pre-tool-use-project.test.ts
  • test/remember-project-scope.test.ts
  • test/worktree-project-scope.test.ts

Signed-off-by: wbu <wbu@live.de>
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