diff --git a/AGENTS.md b/AGENTS.md
index 6c88f558e2..c53122c1e1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -101,7 +101,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
## Testing
-- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (4,000+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests.
+- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (4,100+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests.
- Before any npm publish: `npm run release:gate` must pass. It installs the packed tarballs into a clean home and runs capture, recovery, restart, export/import, MCP and status checks against the installed CLI (see CONTRIBUTING.md, Release process)
- Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list`
- Test files go in `test/` with `.test.ts` extension
@@ -114,4 +114,4 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 17 skills
- 322+ iii functions
-- 4,000+ tests
+- 4,100+ tests
diff --git a/README.md b/README.md
index b57b5c8fbb..cd625f3762 100644
--- a/README.md
+++ b/README.md
@@ -71,7 +71,7 @@
-
+
@@ -1326,6 +1326,23 @@ Per-call override at the SDK / REST layer: every mutating endpoint (`/session/st
When `AGENT_ID` is unset, memory remains unscoped (legacy behavior, no tags, no filters).
+### Repository-relative paths (`AGENTMEMORY_RELATIVE_PATHS`)
+
+When several machines share one server, each clone records its files under its own absolute path (`/Users/me/dev/app/src/a.ts`, `/home/me/dev/app/src/a.ts`), and so does each worktree. File history then does not carry from one to the other. With `AGENTMEMORY_RELATIVE_PATHS=true`, the hooks send every path under the current repository, or under any of its worktrees, relative to that worktree's root (`src/a.ts`), and look up file history with those relative paths in the current project.
+
+- Set it where the hooks run, on every machine. For Claude Code, that is the `env` block of `~/.claude/settings.json`. The hooks do not read it from `~/.agentmemory/.env`.
+- The project is the repository's directory name. If the clones have different directory names, or two different repositories have the same name, set `AGENTMEMORY_PROJECT_NAME` on each machine as well.
+- It applies to the Claude Code plugin hooks and to the integrations that run them. Anything that posts to `/agentmemory/observe` itself (OpenCode, Pi, OMP, Hermes, OpenClaw, the filesystem watcher, `agentmemory capture`) still sends absolute paths.
+- A path a tool was given relative to a subdirectory (a Grep `path` of `src` run from `packages/x`) is stored as it was given.
+- Paths already stored stay absolute. A relative lookup still finds one when it is that file under its session's repository root, the nearest directory at or above the session's `cwd` named after the project.
+- `cwd` is still sent as it is.
+
+Known limits:
+
+- Windows is best effort and has no CI. A path field is converted in full, and free text up to the next space or list separator. A root written with mixed `\` and `/`, or relative paths that differ only in case, are not matched.
+- An older absolute entry from a worktree in a sibling directory (`repo-feature/` next to `repo/`) is not found by a relative lookup, because its session's repository root cannot be worked out from its `cwd`. New captures are relative and are found.
+- The project name comes from `git rev-parse` output, which cannot represent a newline in a repository path.
+
### Ports
The API and viewer bind to loopback by default.
@@ -1485,7 +1502,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ar-SA.md b/READMEs/README.ar-SA.md
index c353c0337e..643f3860f3 100644
--- a/READMEs/README.ar-SA.md
+++ b/READMEs/README.ar-SA.md
@@ -73,7 +73,7 @@
-
+
@@ -1451,7 +1451,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.bn-BD.md b/READMEs/README.bn-BD.md
index 4346dd2b65..05afd96282 100644
--- a/READMEs/README.bn-BD.md
+++ b/READMEs/README.bn-BD.md
@@ -71,7 +71,7 @@
-
+
@@ -1464,7 +1464,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.cs-CZ.md b/READMEs/README.cs-CZ.md
index 2442c41ff4..208db2b198 100644
--- a/READMEs/README.cs-CZ.md
+++ b/READMEs/README.cs-CZ.md
@@ -71,7 +71,7 @@
-
+
@@ -1450,7 +1450,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.da-DK.md b/READMEs/README.da-DK.md
index 13dced179d..93a9ccb695 100644
--- a/READMEs/README.da-DK.md
+++ b/READMEs/README.da-DK.md
@@ -71,7 +71,7 @@
-
+
@@ -1458,7 +1458,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md
index 1641333254..051995b442 100644
--- a/READMEs/README.de-DE.md
+++ b/READMEs/README.de-DE.md
@@ -71,7 +71,7 @@
-
+
@@ -1456,7 +1456,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.el-GR.md b/READMEs/README.el-GR.md
index fa2254a851..42de49307f 100644
--- a/READMEs/README.el-GR.md
+++ b/READMEs/README.el-GR.md
@@ -71,7 +71,7 @@
-
+
@@ -1450,7 +1450,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md
index a18cec0e78..3bfc9a16c5 100644
--- a/READMEs/README.es-ES.md
+++ b/READMEs/README.es-ES.md
@@ -71,7 +71,7 @@
-
+
@@ -1452,7 +1452,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.fi-FI.md b/READMEs/README.fi-FI.md
index 02dab56fdb..fcbfea1491 100644
--- a/READMEs/README.fi-FI.md
+++ b/READMEs/README.fi-FI.md
@@ -71,7 +71,7 @@
-
+
@@ -1450,7 +1450,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md
index c0ef2f9df1..06a0ba9d9c 100644
--- a/READMEs/README.fr-FR.md
+++ b/READMEs/README.fr-FR.md
@@ -71,7 +71,7 @@
-
+
@@ -1459,7 +1459,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.he-IL.md b/READMEs/README.he-IL.md
index 4eb23cb2d5..0161097bc2 100644
--- a/READMEs/README.he-IL.md
+++ b/READMEs/README.he-IL.md
@@ -73,7 +73,7 @@
-
+
@@ -1451,7 +1451,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md
index 5963fa93f8..f66200c328 100644
--- a/READMEs/README.hi-IN.md
+++ b/READMEs/README.hi-IN.md
@@ -71,7 +71,7 @@
-
+
@@ -1465,7 +1465,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.hu-HU.md b/READMEs/README.hu-HU.md
index fc2ae76681..6df78e85f6 100644
--- a/READMEs/README.hu-HU.md
+++ b/READMEs/README.hu-HU.md
@@ -71,7 +71,7 @@
-
+
@@ -1448,7 +1448,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.id-ID.md b/READMEs/README.id-ID.md
index 1de7ed8084..0c27c65995 100644
--- a/READMEs/README.id-ID.md
+++ b/READMEs/README.id-ID.md
@@ -71,7 +71,7 @@
-
+
@@ -1465,7 +1465,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.it-IT.md b/READMEs/README.it-IT.md
index 3e3fa649d4..5c6a55ca3b 100644
--- a/READMEs/README.it-IT.md
+++ b/READMEs/README.it-IT.md
@@ -71,7 +71,7 @@
-
+
@@ -1458,7 +1458,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md
index 12b8352cf2..a10506bb06 100644
--- a/READMEs/README.ja-JP.md
+++ b/READMEs/README.ja-JP.md
@@ -71,7 +71,7 @@
-
+
@@ -1464,7 +1464,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md
index 37e27d890b..c8c8176509 100644
--- a/READMEs/README.ko-KR.md
+++ b/READMEs/README.ko-KR.md
@@ -71,7 +71,7 @@
-
+
@@ -1463,7 +1463,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.nb-NO.md b/READMEs/README.nb-NO.md
index b8bc28c547..f62c583da1 100644
--- a/READMEs/README.nb-NO.md
+++ b/READMEs/README.nb-NO.md
@@ -71,7 +71,7 @@
-
+
@@ -1456,7 +1456,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.nl-NL.md b/READMEs/README.nl-NL.md
index 864d483c54..eae8f52725 100644
--- a/READMEs/README.nl-NL.md
+++ b/READMEs/README.nl-NL.md
@@ -71,7 +71,7 @@
-
+
@@ -1452,7 +1452,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pl-PL.md b/READMEs/README.pl-PL.md
index 5bc508604d..ba32976b4e 100644
--- a/READMEs/README.pl-PL.md
+++ b/READMEs/README.pl-PL.md
@@ -71,7 +71,7 @@
-
+
@@ -1448,7 +1448,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md
index 864862b69d..259c44a89d 100644
--- a/READMEs/README.pt-BR.md
+++ b/READMEs/README.pt-BR.md
@@ -71,7 +71,7 @@
-
+
@@ -1456,7 +1456,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pt-PT.md b/READMEs/README.pt-PT.md
index 1c280bcc21..d35fe99ac5 100644
--- a/READMEs/README.pt-PT.md
+++ b/READMEs/README.pt-PT.md
@@ -71,7 +71,7 @@
-
+
@@ -1452,7 +1452,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ro-RO.md b/READMEs/README.ro-RO.md
index b2401fe6b1..de8fb4070a 100644
--- a/READMEs/README.ro-RO.md
+++ b/READMEs/README.ro-RO.md
@@ -71,7 +71,7 @@
-
+
@@ -1444,7 +1444,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md
index 83bbaf21e2..f4dfd718ca 100644
--- a/READMEs/README.ru-RU.md
+++ b/READMEs/README.ru-RU.md
@@ -71,7 +71,7 @@
-
+
@@ -1450,7 +1450,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.sv-SE.md b/READMEs/README.sv-SE.md
index 3aa899882f..4a648657fa 100644
--- a/READMEs/README.sv-SE.md
+++ b/READMEs/README.sv-SE.md
@@ -71,7 +71,7 @@
-
+
@@ -1458,7 +1458,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.th-TH.md b/READMEs/README.th-TH.md
index 93b2dde01c..e20cdedf98 100644
--- a/READMEs/README.th-TH.md
+++ b/READMEs/README.th-TH.md
@@ -71,7 +71,7 @@
-
+
@@ -1449,7 +1449,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.tl-PH.md b/READMEs/README.tl-PH.md
index 4c8e282573..d6341fdaf9 100644
--- a/READMEs/README.tl-PH.md
+++ b/READMEs/README.tl-PH.md
@@ -71,7 +71,7 @@
-
+
@@ -1460,7 +1460,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md
index 014dd3f7ea..45cea7ce2b 100644
--- a/READMEs/README.tr-TR.md
+++ b/READMEs/README.tr-TR.md
@@ -71,7 +71,7 @@
-
+
@@ -1450,7 +1450,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.uk-UA.md b/READMEs/README.uk-UA.md
index 1f142d4858..82c83d53c6 100644
--- a/READMEs/README.uk-UA.md
+++ b/READMEs/README.uk-UA.md
@@ -71,7 +71,7 @@
-
+
@@ -1451,7 +1451,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ur-PK.md b/READMEs/README.ur-PK.md
index 9ea6efafdc..7e98701139 100644
--- a/READMEs/README.ur-PK.md
+++ b/READMEs/README.ur-PK.md
@@ -73,7 +73,7 @@
-
+
@@ -1455,7 +1455,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.vi-VN.md b/READMEs/README.vi-VN.md
index 06aea9a278..1ee5099359 100644
--- a/READMEs/README.vi-VN.md
+++ b/READMEs/README.vi-VN.md
@@ -71,7 +71,7 @@
-
+
@@ -1460,7 +1460,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md
index 0941ab0d5d..341e8ab5b0 100644
--- a/READMEs/README.zh-CN.md
+++ b/READMEs/README.zh-CN.md
@@ -71,7 +71,7 @@
-
+
@@ -1461,7 +1461,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md
index 5a1c902966..ea30c5d3aa 100644
--- a/READMEs/README.zh-TW.md
+++ b/READMEs/README.zh-TW.md
@@ -71,7 +71,7 @@
-
+
@@ -1453,7 +1453,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/assets/tags/light/stat-tests.svg b/assets/tags/light/stat-tests.svg
index 915e1bab9d..7248bfad00 100644
--- a/assets/tags/light/stat-tests.svg
+++ b/assets/tags/light/stat-tests.svg
@@ -1,5 +1,5 @@
-
+
- 4000+
+ 4100+
TESTS PASSING
diff --git a/assets/tags/stat-tests.svg b/assets/tags/stat-tests.svg
index 99b680533e..e51099c87f 100644
--- a/assets/tags/stat-tests.svg
+++ b/assets/tags/stat-tests.svg
@@ -1,5 +1,5 @@
-
+
- 4000+
+ 4100+
TESTS PASSING
diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs
index eb568a2403..9ecc18fa53 100644
--- a/plugin/scripts/_capture.mjs
+++ b/plugin/scripts/_capture.mjs
@@ -1,5 +1,5 @@
-import { spawn } from "node:child_process";
-import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs";
+import { execFileSync, spawn } from "node:child_process";
+import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs";
import { createHash } from "node:crypto";
import { homedir, platform } from "node:os";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -828,6 +828,150 @@ async function drainSpool(url, send, options = {}) {
}
}
//#endregion
+//#region src/hooks/_project.ts
+function relativePathsEnabled() {
+ return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true";
+}
+//#endregion
+//#region src/hooks/_relative-paths.ts
+function gitWorktreeListing(cwd) {
+ const run = (args) => execFileSync("git", [
+ "worktree",
+ "list",
+ "--porcelain",
+ ...args
+ ], {
+ cwd,
+ env: {
+ ...process.env,
+ LC_ALL: "C"
+ },
+ stdio: [
+ "ignore",
+ "pipe",
+ "pipe"
+ ],
+ timeout: 500
+ }).toString();
+ try {
+ return run(["-z"]).split("\0");
+ } catch (err) {
+ const stderr = String(err.stderr ?? "");
+ if (!/unknown switch|usage:/i.test(stderr)) return [];
+ }
+ try {
+ return run([]).split(/\r?\n/);
+ } catch {
+ return [];
+ }
+}
+function tryRealpath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return;
+ }
+}
+function slashed(path) {
+ return path.replace(/\\/g, "/");
+}
+function isInsideRoot(root, path) {
+ return slashed(path) === slashed(root) || slashed(path).startsWith(`${slashed(root)}/`);
+}
+function cwdAliases(rawCwd, roots) {
+ const cwd = rawCwd.replace(/(.)[\\/]+$/, "$1");
+ const physical = tryRealpath(cwd);
+ if (!physical || physical === cwd) return [];
+ const root = roots.find((candidate) => isInsideRoot(candidate, physical));
+ if (root === void 0) return [];
+ const inside = slashed(physical.slice(root.length));
+ const prefix = inside && slashed(cwd).endsWith(inside) ? cwd.slice(0, cwd.length - inside.length) : void 0;
+ const prefixPhysical = prefix ? tryRealpath(prefix) : void 0;
+ if (prefix && prefixPhysical && slashed(prefixPhysical) === slashed(root)) return [{
+ from: prefix,
+ to: ""
+ }];
+ return [{
+ from: cwd,
+ to: relative(root, physical).replace(/\\/g, "/")
+ }];
+}
+function repositoryRoots(cwd) {
+ const recorded = gitWorktreeListing(cwd).filter((line) => line.startsWith("worktree ")).map((line) => line.slice(9)).filter(Boolean);
+ const roots = /* @__PURE__ */ new Set();
+ for (const root of recorded) {
+ roots.add(root);
+ const physical = tryRealpath(root);
+ if (physical) roots.add(physical);
+ }
+ const longestFirst = [...roots].sort((a, b) => b.length - a.length);
+ const aliases = longestFirst.map((from) => ({
+ from,
+ to: ""
+ }));
+ aliases.push(...cwdAliases(cwd, longestFirst));
+ if (process.platform === "win32") for (const alias of [...aliases]) aliases.push({
+ ...alias,
+ from: alias.from.replace(/\//g, "\\")
+ });
+ return aliases.sort((a, b) => b.from.length - a.from.length);
+}
+function escapeRegExp(text) {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+const PATH_END = `$|[\\s"'\`:;,)\\]}>|&]`;
+const WINDOWS_TAIL = `[^\\s"'\`,;|&<>]*`;
+const PATH_KEYS = new Set([
+ "file_path",
+ "filePath",
+ "filepath",
+ "notebook_path",
+ "path",
+ "file"
+]);
+const SKIPPED_KEYS = new Set(["image_data", "imageData"]);
+function ignoresCase(path) {
+ const swapped = path.replace(/[a-z]/gi, (c) => c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase());
+ if (swapped === path) return false;
+ try {
+ const original = statSync(path);
+ const other = statSync(swapped);
+ return original.ino === other.ino && original.dev === other.dev;
+ } catch {
+ return false;
+ }
+}
+function aliasPattern(aliases, platform, caseInsensitive) {
+ if (aliases.length === 0) return null;
+ const anyCase = (text) => text.replace(/[a-z]/gi, (c) => `[${c.toLowerCase()}${c.toUpperCase()}]`);
+ const alternatives = aliases.map((alias) => {
+ const escaped = escapeRegExp(alias.from);
+ return `(${caseInsensitive(alias.from) ? anyCase(escaped) : escaped})`;
+ }).join("|");
+ return new RegExp(`(? platform === "win32" || platform === "darwin" && ignoresCase(root)) {
+ const pattern = aliasPattern(aliases, platform, typeof caseInsensitive === "function" ? caseInsensitive : () => caseInsensitive);
+ if (!pattern) return value;
+ const windows = platform === "win32";
+ const rewrite = (_match, ...groups) => {
+ const to = aliases[groups.findIndex((group) => typeof group === "string")]?.to ?? "";
+ if (typeof groups[aliases.length] !== "string") return to || ".";
+ const tail = String(groups[aliases.length + 1] ?? "").replace(/\\/g, "/");
+ return to ? `${to}/${tail}` : tail;
+ };
+ const walk = (node, key) => {
+ if (typeof node === "string") {
+ const rewritten = node.replace(pattern, rewrite);
+ return windows && rewritten !== node && key !== void 0 && PATH_KEYS.has(key) ? rewritten.replace(/\\/g, "/") : rewritten;
+ }
+ if (Array.isArray(node)) return node.map((child) => walk(child, key));
+ if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) return Object.fromEntries(Object.entries(node).map(([k, child]) => [k, SKIPPED_KEYS.has(k) ? child : walk(child, k)]));
+ return node;
+ };
+ return walk(value);
+}
+//#endregion
//#region src/hooks/_capture.ts
const REST_URL = process.env["AGENTMEMORY_URL"] || "http://localhost:3111";
const SECRET = resolveClientSecret(REST_URL);
@@ -904,8 +1048,10 @@ function startDrainChild() {
}
async function captureObservation(body, timeoutMs) {
const eventId = body.eventId ?? deriveEventId(body.hookType, body.sessionId, null, body.data);
+ const data = relativePathsEnabled() ? relativizePaths(body.data, repositoryRoots(body.cwd)) : body.data;
const payload = {
...body,
+ data,
eventId
};
let reason;
diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs
index 2761d007a2..c867122121 100755
--- a/plugin/scripts/pre-tool-use.mjs
+++ b/plugin/scripts/pre-tool-use.mjs
@@ -1,7 +1,8 @@
#!/usr/bin/env node
-import { readFileSync } from "node:fs";
+import { readFileSync, realpathSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { basename, dirname, join, relative, resolve } from "node:path";
+import { execFileSync, execSync } from "node:child_process";
//#region src/secret-store.ts
const SECRET_KEY = "AGENTMEMORY_SECRET";
function agentmemoryHomeDir() {
@@ -89,6 +90,188 @@ function canonicalSecretPath() {
return join(homedir(), ".agentmemory", "secret");
}
//#endregion
+//#region src/hooks/_project.ts
+function relativePathsEnabled() {
+ return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true";
+}
+function resolveProject(cwd) {
+ const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
+ if (explicit && explicit.trim()) return explicit.trim();
+ const dir = cwd && cwd.trim() ? cwd : process.cwd();
+ try {
+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {
+ cwd: dir,
+ stdio: [
+ "ignore",
+ "pipe",
+ "ignore"
+ ],
+ timeout: 500
+ }).toString().trim().split(/\r?\n/);
+ if (top) return basename(repositoryRoot(dir, top, gitDir, commonDir));
+ } catch {}
+ return basename(dir);
+}
+function repositoryRoot(dir, top, gitDir, commonDir) {
+ if (!gitDir || !commonDir) return top;
+ const physical = realpathSync(dir);
+ const common = resolve(physical, commonDir);
+ if (resolve(physical, gitDir) === common || basename(common) !== ".git") return top;
+ return dirname(common);
+}
+function hookCwd(data) {
+ if (!data || typeof data !== "object") return void 0;
+ if (typeof data.cwd === "string" && data.cwd.trim()) return data.cwd;
+ const roots = data.workspace_roots;
+ if (Array.isArray(roots)) {
+ for (const root of roots) if (typeof root === "string" && root.trim()) return root;
+ }
+ const projectDir = process.env["DEVIN_PROJECT_DIR"] || process.env["CLAUDE_PROJECT_DIR"];
+ if (projectDir && projectDir.trim()) return projectDir;
+}
+//#endregion
+//#region src/hooks/_relative-paths.ts
+function gitWorktreeListing(cwd) {
+ const run = (args) => execFileSync("git", [
+ "worktree",
+ "list",
+ "--porcelain",
+ ...args
+ ], {
+ cwd,
+ env: {
+ ...process.env,
+ LC_ALL: "C"
+ },
+ stdio: [
+ "ignore",
+ "pipe",
+ "pipe"
+ ],
+ timeout: 500
+ }).toString();
+ try {
+ return run(["-z"]).split("\0");
+ } catch (err) {
+ const stderr = String(err.stderr ?? "");
+ if (!/unknown switch|usage:/i.test(stderr)) return [];
+ }
+ try {
+ return run([]).split(/\r?\n/);
+ } catch {
+ return [];
+ }
+}
+function tryRealpath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return;
+ }
+}
+function slashed(path) {
+ return path.replace(/\\/g, "/");
+}
+function isInsideRoot(root, path) {
+ return slashed(path) === slashed(root) || slashed(path).startsWith(`${slashed(root)}/`);
+}
+function cwdAliases(rawCwd, roots) {
+ const cwd = rawCwd.replace(/(.)[\\/]+$/, "$1");
+ const physical = tryRealpath(cwd);
+ if (!physical || physical === cwd) return [];
+ const root = roots.find((candidate) => isInsideRoot(candidate, physical));
+ if (root === void 0) return [];
+ const inside = slashed(physical.slice(root.length));
+ const prefix = inside && slashed(cwd).endsWith(inside) ? cwd.slice(0, cwd.length - inside.length) : void 0;
+ const prefixPhysical = prefix ? tryRealpath(prefix) : void 0;
+ if (prefix && prefixPhysical && slashed(prefixPhysical) === slashed(root)) return [{
+ from: prefix,
+ to: ""
+ }];
+ return [{
+ from: cwd,
+ to: relative(root, physical).replace(/\\/g, "/")
+ }];
+}
+function repositoryRoots(cwd) {
+ const recorded = gitWorktreeListing(cwd).filter((line) => line.startsWith("worktree ")).map((line) => line.slice(9)).filter(Boolean);
+ const roots = /* @__PURE__ */ new Set();
+ for (const root of recorded) {
+ roots.add(root);
+ const physical = tryRealpath(root);
+ if (physical) roots.add(physical);
+ }
+ const longestFirst = [...roots].sort((a, b) => b.length - a.length);
+ const aliases = longestFirst.map((from) => ({
+ from,
+ to: ""
+ }));
+ aliases.push(...cwdAliases(cwd, longestFirst));
+ if (process.platform === "win32") for (const alias of [...aliases]) aliases.push({
+ ...alias,
+ from: alias.from.replace(/\//g, "\\")
+ });
+ return aliases.sort((a, b) => b.from.length - a.from.length);
+}
+function escapeRegExp(text) {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+const PATH_END = `$|[\\s"'\`:;,)\\]}>|&]`;
+const WINDOWS_TAIL = `[^\\s"'\`,;|&<>]*`;
+const PATH_KEYS = new Set([
+ "file_path",
+ "filePath",
+ "filepath",
+ "notebook_path",
+ "path",
+ "file"
+]);
+const SKIPPED_KEYS = new Set(["image_data", "imageData"]);
+function ignoresCase(path) {
+ const swapped = path.replace(/[a-z]/gi, (c) => c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase());
+ if (swapped === path) return false;
+ try {
+ const original = statSync(path);
+ const other = statSync(swapped);
+ return original.ino === other.ino && original.dev === other.dev;
+ } catch {
+ return false;
+ }
+}
+function aliasPattern(aliases, platform, caseInsensitive) {
+ if (aliases.length === 0) return null;
+ const anyCase = (text) => text.replace(/[a-z]/gi, (c) => `[${c.toLowerCase()}${c.toUpperCase()}]`);
+ const alternatives = aliases.map((alias) => {
+ const escaped = escapeRegExp(alias.from);
+ return `(${caseInsensitive(alias.from) ? anyCase(escaped) : escaped})`;
+ }).join("|");
+ return new RegExp(`(? platform === "win32" || platform === "darwin" && ignoresCase(root)) {
+ const pattern = aliasPattern(aliases, platform, typeof caseInsensitive === "function" ? caseInsensitive : () => caseInsensitive);
+ if (!pattern) return value;
+ const windows = platform === "win32";
+ const rewrite = (_match, ...groups) => {
+ const to = aliases[groups.findIndex((group) => typeof group === "string")]?.to ?? "";
+ if (typeof groups[aliases.length] !== "string") return to || ".";
+ const tail = String(groups[aliases.length + 1] ?? "").replace(/\\/g, "/");
+ return to ? `${to}/${tail}` : tail;
+ };
+ const walk = (node, key) => {
+ if (typeof node === "string") {
+ const rewritten = node.replace(pattern, rewrite);
+ return windows && rewritten !== node && key !== void 0 && PATH_KEYS.has(key) ? rewritten.replace(/\\/g, "/") : rewritten;
+ }
+ if (Array.isArray(node)) return node.map((child) => walk(child, key));
+ if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) return Object.fromEntries(Object.entries(node).map(([k, child]) => [k, SKIPPED_KEYS.has(k) ? child : walk(child, k)]));
+ return node;
+ };
+ return walk(value);
+}
+function relativizeFilePath(file, aliases, platform = process.platform) {
+ return relativizePaths({ file_path: file }, aliases, platform).file_path;
+}
+//#endregion
//#region src/hooks/pre-tool-use.ts
function isSdkChildContext(payload) {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -148,17 +331,22 @@ async function main() {
}
const rawSessionId = data.session_id || data.sessionId || data.conversation_id;
const sessionId = typeof rawSessionId === "string" && rawSessionId.length > 0 ? rawSessionId : "unknown";
- const project = typeof data.project === "string" && data.project.trim().length > 0 ? data.project.trim() : void 0;
+ const relativeFiles = relativePathsEnabled();
+ const cwd = hookCwd(data) || process.cwd();
+ const project = typeof data.project === "string" && data.project.trim().length > 0 ? data.project.trim() : relativeFiles ? resolveProject(cwd) || void 0 : void 0;
+ const aliases = relativeFiles ? repositoryRoots(cwd) : [];
+ const queryFiles = relativeFiles ? files.map((file) => relativizeFilePath(file, aliases)) : files;
try {
const res = await fetch(`${REST_URL}/agentmemory/enrich`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({
sessionId,
- files,
+ files: queryFiles,
terms,
toolName,
- ...project !== void 0 && { project }
+ ...project !== void 0 && { project },
+ ...relativeFiles && { relativeFiles: true }
}),
signal: AbortSignal.timeout(2e3)
});
diff --git a/plugin/skills/agentmemory-config/REFERENCE.md b/plugin/skills/agentmemory-config/REFERENCE.md
index 7d58384e26..4fec9c5960 100644
--- a/plugin/skills/agentmemory-config/REFERENCE.md
+++ b/plugin/skills/agentmemory-config/REFERENCE.md
@@ -3,7 +3,7 @@
Generated by scanning `src/` for `AGENTMEMORY_*` usage. Do not edit the block below by hand; run `npm run skills:gen` after adding or removing a variable. Internal markers ending in two underscores are excluded.
-Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 75 recognized variables:
+Configuration is read from the environment and from `~/.agentmemory/.env` (no `export` prefix). 76 recognized variables:
- `AGENTMEMORY_AGENT_SCOPE`
- `AGENTMEMORY_ALLOW_AGENT_SDK`
@@ -60,6 +60,7 @@ Configuration is read from the environment and from `~/.agentmemory/.env` (no `e
- `AGENTMEMORY_READY_TIMEOUT_MS`
- `AGENTMEMORY_REDIS_URL`
- `AGENTMEMORY_REFLECT`
+- `AGENTMEMORY_RELATIVE_PATHS`
- `AGENTMEMORY_RUNTIME_DIR`
- `AGENTMEMORY_SDK_CHILD`
- `AGENTMEMORY_SECRET`
diff --git a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
index 68fe3debe9..f28c56f821 100644
--- a/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
+++ b/plugin/skills/agentmemory-mcp-tools/REFERENCE.md
@@ -21,7 +21,7 @@ agentmemory exposes 54 MCP tools. 8 are in the lean core set (`--tools core` or
| `memory_export` | | `maxSessions`: number, `offset`: number, `collectionLimit`: number, `collectionOffset`: number, `collections`: string | Export memory data as JSON. Past the transport size limit the export is refused, so use the paging arguments on a large store. |
| `memory_facet_query` | | `matchAll`: string, `matchAny`: string, `targetType`: string | Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend. |
| `memory_facet_tag` | | `targetId`*: string, `targetType`*: string, `dimension`*: string, `value`*: string | Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization. |
-| `memory_file_history` | | `files`*: string, `sessionId`: string | Get past observations about specific files. |
+| `memory_file_history` | | `files`*: string, `sessionId`: string, `project`: string | Get past observations about specific files. |
| `memory_frontier` | | `project`: string, `agentId`: string, `limit`: number | Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies. |
| `memory_governance_delete` | | `memoryIds`*: string, `reason`: string | Delete specific memories with audit trail. |
| `memory_graph_query` | | `startNodeId`: string, `nodeType`: string, `maxDepth`: number, `query`: string | Query the knowledge graph for entities and relationships. |
diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json
index 0538665c6a..bf7cab5337 100644
--- a/scripts/docs-sync.state.json
+++ b/scripts/docs-sync.state.json
@@ -20,13 +20,13 @@
"12"
],
"tests": [
- "4000+"
+ "4100+"
],
"functions": [
"322"
],
"sourceFiles": [
- "254"
+ "255"
],
"loc": [
"58000"
diff --git a/src/functions/enrich.ts b/src/functions/enrich.ts
index 05f62acb9d..ab13a9937f 100644
--- a/src/functions/enrich.ts
+++ b/src/functions/enrich.ts
@@ -4,6 +4,7 @@ import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { logger } from "../logger.js";
import { escapeXml } from "../prompts/xml.js";
+import { bugFileMatches } from "./file-index.js";
const MAX_CONTEXT_LENGTH = 4000;
@@ -16,6 +17,7 @@ export function registerEnrichFunction(sdk: IIIClient, kv: StateKV): void {
terms?: string[];
toolName?: string;
project?: string;
+ relativeFiles?: boolean;
}) => {
const project =
typeof data.project === "string" && data.project.trim().length > 0
@@ -25,11 +27,15 @@ export function registerEnrichFunction(sdk: IIIClient, kv: StateKV): void {
const parts: string[] = [];
const fileContextPromise = sdk
- .trigger<{ sessionId: string; files: string[] }, { context: string }>({
+ .trigger<
+ { sessionId: string; files: string[]; project?: string; relativeFiles?: boolean },
+ { context: string }
+ >({
function_id: "mem::file-context",
payload: {
sessionId: data.sessionId,
files: data.files,
+ ...(data.relativeFiles === true && { relativeFiles: true, ...(project !== undefined && { project }) }),
},
})
.catch(() => ({ context: "" }));
@@ -67,7 +73,9 @@ export function registerEnrichFunction(sdk: IIIClient, kv: StateKV): void {
// Guard only when both sides have an explicit project; unscoped memories pass through.
(!project || !m.project || m.project === project) &&
m.files.some((f) =>
- data.files.some((df) => f.includes(df) || df.includes(f)),
+ data.files.some((df) =>
+ data.relativeFiles === true ? bugFileMatches(f, df) : f.includes(df) || df.includes(f),
+ ),
),
)
.sort(
diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts
index a52bf0356f..ab5f940f17 100644
--- a/src/functions/file-index.ts
+++ b/src/functions/file-index.ts
@@ -19,10 +19,62 @@ interface FileHistory {
}>;
}
+function normalizePath(path: string): string {
+ const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "").replace(/(.)\/+$/, "$1");
+ return /^[A-Za-z]:\//.test(slashed) ? slashed.charAt(0).toLowerCase() + slashed.slice(1) : slashed;
+}
+
+function isAbsolutePath(path: string): boolean {
+ const slashed = normalizePath(path);
+ return slashed.startsWith("/") || /^[a-z]:\//.test(slashed);
+}
+
+// Windows file systems ignore case, so a path with a drive letter or a UNC prefix compares in any case.
+function foldWindowsCase(a: string, b: string): [string, string] {
+ const windows = (path: string) => /^[a-z]:\//.test(path) || path.startsWith("//");
+ return windows(a) || windows(b) ? [a.toLowerCase(), b.toLowerCase()] : [a, b];
+}
+
+function samePath(a: string, b: string): boolean {
+ const [left, right] = foldWindowsCase(a, b);
+ return left === right;
+}
+
+// The project is the repository's directory name, so a session's repository root is the nearest
+// directory at or above its cwd with that name; a renamed project falls back to the cwd.
+function sessionRoot(cwd: string, project: string): string {
+ const dir = normalizePath(cwd);
+ for (let candidate = dir; candidate.includes("/"); candidate = candidate.slice(0, candidate.lastIndexOf("/"))) {
+ if (samePath(candidate, `${candidate.slice(0, candidate.lastIndexOf("/") + 1)}${project}`)) return candidate;
+ }
+ return dir;
+}
+
+// A repository-relative query names one file exactly, so a bare `package.json` is the root one,
+// not every `package.json` below it. A relative entry must equal it; an absolute entry from before
+// relative capture must be that file under its session's repository root.
+function matchesRelativeQuery(query: string, stored: string, session: Session): boolean {
+ const entry = normalizePath(stored);
+ if (!isAbsolutePath(entry)) return entry === query;
+ return Boolean(session.cwd) && samePath(entry, `${sessionRoot(session.cwd, session.project)}/${query}`);
+}
+
+// A bug memory has no session to place an older absolute entry, so that entry matches by its ending
+// at a path boundary; two relative paths must be equal.
+export function bugFileMatches(stored: string, requested: string): boolean {
+ const entry = normalizePath(stored);
+ const query = normalizePath(requested);
+ if (!isAbsolutePath(entry) && !isAbsolutePath(query)) return entry === query;
+ const [left, right] = foldWindowsCase(entry, query);
+ return left === right || left.endsWith(`/${right}`) || right.endsWith(`/${left}`);
+}
+
export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void {
sdk.registerFunction("mem::file-context",
async (
- data: { sessionId?: string; files?: string[]; project?: string } | undefined,
+ data:
+ | { sessionId?: string; files?: string[]; project?: string; relativeFiles?: boolean }
+ | undefined,
) => {
const sessionId =
data && typeof data.sessionId === "string" ? data.sessionId.trim() : "";
@@ -69,18 +121,23 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void {
for (const file of files) {
const history: FileHistory = { file, observations: [] };
const normalizedFile = file.replace(/^\.\//, "");
+ const relativeQuery =
+ data?.relativeFiles === true && !isAbsolutePath(file)
+ ? normalizePath(normalizedFile)
+ : undefined;
for (const session of otherSessions) {
const observations = obsCache.get(session.id) || [];
for (const obs of observations) {
if (!obs.files || !obs.title) continue;
- const matches = obs.files.some(
- (f) =>
- f === file ||
- f === normalizedFile ||
- f.endsWith(`/${normalizedFile}`) ||
- normalizedFile.endsWith(`/${f}`),
+ const matches = obs.files.some((f) =>
+ relativeQuery !== undefined
+ ? matchesRelativeQuery(relativeQuery, f, session)
+ : f === file ||
+ f === normalizedFile ||
+ f.endsWith(`/${normalizedFile}`) ||
+ normalizedFile.endsWith(`/${f}`),
);
if (matches && obs.importance >= 4) {
history.observations.push({
diff --git a/src/hooks/_capture.ts b/src/hooks/_capture.ts
index 021c8bff7f..ba43053a28 100644
--- a/src/hooks/_capture.ts
+++ b/src/hooks/_capture.ts
@@ -13,6 +13,8 @@ import {
type SentMark,
type SpoolRecord,
} from "../capture/spool.js";
+import { relativePathsEnabled } from "./_project.js";
+import { relativizePaths, repositoryRoots } from "./_relative-paths.js";
export { stripPrivateData } from "../functions/privacy.js";
@@ -100,7 +102,8 @@ function startDrainChild(): void {
export async function captureObservation(body: ObserveBody, timeoutMs: number): Promise {
const eventId = body.eventId ?? deriveEventId(body.hookType, body.sessionId, null, body.data);
- const payload = { ...body, eventId } as unknown as Record;
+ const data = relativePathsEnabled() ? relativizePaths(body.data, repositoryRoots(body.cwd)) : body.data;
+ const payload = { ...body, data, eventId } as unknown as Record;
let reason: string;
try {
const { outcome, mark } = await post(payload, timeoutMs);
diff --git a/src/hooks/_project.ts b/src/hooks/_project.ts
index 552468dfb6..7fa8a7eccc 100644
--- a/src/hooks/_project.ts
+++ b/src/hooks/_project.ts
@@ -2,6 +2,10 @@ import { execSync } from "node:child_process";
import { realpathSync } from "node:fs";
import { basename, dirname, resolve } from "node:path";
+export function relativePathsEnabled(): boolean {
+ return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true";
+}
+
// Resolution order: AGENTMEMORY_PROJECT_NAME env → git repository basename → cwd basename.
export function resolveProject(cwd?: string): string {
const explicit = process.env["AGENTMEMORY_PROJECT_NAME"];
diff --git a/src/hooks/_relative-paths.ts b/src/hooks/_relative-paths.ts
new file mode 100644
index 0000000000..84e837b6ef
--- /dev/null
+++ b/src/hooks/_relative-paths.ts
@@ -0,0 +1,177 @@
+import { execFileSync } from "node:child_process";
+import { realpathSync, statSync } from "node:fs";
+import { relative } from "node:path";
+
+export interface PathAlias {
+ from: string;
+ to: string;
+}
+
+function gitWorktreeListing(cwd: string): string[] {
+ const run = (args: string[]) =>
+ execFileSync("git", ["worktree", "list", "--porcelain", ...args], {
+ cwd,
+ env: { ...process.env, LC_ALL: "C" },
+ stdio: ["ignore", "pipe", "pipe"],
+ timeout: 500,
+ }).toString();
+ try {
+ return run(["-z"]).split("\0");
+ } catch (err) {
+ const stderr = String((err as { stderr?: unknown }).stderr ?? "");
+ if (!/unknown switch|usage:/i.test(stderr)) return [];
+ }
+ try {
+ return run([]).split(/\r?\n/);
+ } catch {
+ return [];
+ }
+}
+
+function tryRealpath(path: string): string | undefined {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return undefined;
+ }
+}
+
+function slashed(path: string): string {
+ return path.replace(/\\/g, "/");
+}
+
+function isInsideRoot(root: string, path: string): boolean {
+ return slashed(path) === slashed(root) || slashed(path).startsWith(`${slashed(root)}/`);
+}
+
+// `roots` must be longest first, so a cwd inside a nested worktree maps onto that worktree.
+function cwdAliases(rawCwd: string, roots: readonly string[]): PathAlias[] {
+ const cwd = rawCwd.replace(/(.)[\\/]+$/, "$1");
+ const physical = tryRealpath(cwd);
+ if (!physical || physical === cwd) return [];
+ const root = roots.find((candidate) => isInsideRoot(candidate, physical));
+ if (root === undefined) return [];
+ const inside = slashed(physical.slice(root.length));
+ const prefix = inside && slashed(cwd).endsWith(inside) ? cwd.slice(0, cwd.length - inside.length) : undefined;
+ const prefixPhysical = prefix ? tryRealpath(prefix) : undefined;
+ if (prefix && prefixPhysical && slashed(prefixPhysical) === slashed(root)) return [{ from: prefix, to: "" }];
+ return [{ from: cwd, to: relative(root, physical).replace(/\\/g, "/") }];
+}
+
+// Longest first: a worktree nested inside the main checkout must be stripped before it.
+export function repositoryRoots(cwd: string): PathAlias[] {
+ const recorded = gitWorktreeListing(cwd)
+ .filter((line) => line.startsWith("worktree "))
+ .map((line) => line.slice("worktree ".length))
+ .filter(Boolean);
+ const roots = new Set();
+ for (const root of recorded) {
+ roots.add(root);
+ const physical = tryRealpath(root);
+ if (physical) roots.add(physical);
+ }
+ const longestFirst = [...roots].sort((a, b) => b.length - a.length);
+ const aliases = longestFirst.map((from) => ({ from, to: "" }));
+ aliases.push(...cwdAliases(cwd, longestFirst));
+ if (process.platform === "win32") {
+ for (const alias of [...aliases]) aliases.push({ ...alias, from: alias.from.replace(/\//g, "\\") });
+ }
+ return aliases.sort((a, b) => b.from.length - a.from.length);
+}
+
+function escapeRegExp(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+const PATH_END = `$|[\\s"'\`:;,)\\]}>|&]`;
+const WINDOWS_TAIL = `[^\\s"'\`,;|&<>]*`;
+const PATH_KEYS = new Set(["file_path", "filePath", "filepath", "notebook_path", "path", "file"]);
+const SKIPPED_KEYS = new Set(["image_data", "imageData"]);
+
+// Whether the file system holding `path` ignores case: the same path with its letters' case swapped
+// names the same file. macOS volumes usually do, but can be case-sensitive.
+export function ignoresCase(path: string): boolean {
+ const swapped = path.replace(/[a-z]/gi, (c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()));
+ if (swapped === path) return false;
+ try {
+ const original = statSync(path);
+ const other = statSync(swapped);
+ return original.ino === other.ino && original.dev === other.dev;
+ } catch {
+ return false;
+ }
+}
+
+// A root counts only where a path starts (not after a word character, `/`, `-`, `.`, `~` or a
+// `host:` prefix) and where it ends, so `/mnt/repo/x`, `repo-old/` and `build:/repo` stay as they
+// are. A root matches in any case on Windows, and on macOS when its own volume ignores case, so
+// each root decides for itself; Node 20 has no inline case flag, so its letters become `[aA]`.
+// Windows paths come out with forward slashes, like the file index: free text cannot say where a
+// path ends, so it is converted up to the next space or list separator, while a path field is one
+// path and is converted in full.
+function aliasPattern(
+ aliases: readonly PathAlias[],
+ platform: NodeJS.Platform,
+ caseInsensitive: (root: string) => boolean,
+): RegExp | null {
+ if (aliases.length === 0) return null;
+ const anyCase = (text: string) => text.replace(/[a-z]/gi, (c) => `[${c.toLowerCase()}${c.toUpperCase()}]`);
+ const alternatives = aliases
+ .map((alias) => {
+ const escaped = escapeRegExp(alias.from);
+ return `(${caseInsensitive(alias.from) ? anyCase(escaped) : escaped})`;
+ })
+ .join("|");
+ const tail = platform === "win32" ? WINDOWS_TAIL : "";
+ return new RegExp(
+ `(? boolean) = (root) =>
+ platform === "win32" || (platform === "darwin" && ignoresCase(root)),
+): unknown {
+ const pattern = aliasPattern(
+ aliases,
+ platform,
+ typeof caseInsensitive === "function" ? caseInsensitive : () => caseInsensitive,
+ );
+ if (!pattern) return value;
+ const windows = platform === "win32";
+ const rewrite = (_match: string, ...groups: unknown[]): string => {
+ const to = aliases[groups.findIndex((group) => typeof group === "string")]?.to ?? "";
+ if (typeof groups[aliases.length] !== "string") return to || ".";
+ const tail = String(groups[aliases.length + 1] ?? "").replace(/\\/g, "/");
+ return to ? `${to}/${tail}` : tail;
+ };
+ const walk = (node: unknown, key?: string): unknown => {
+ if (typeof node === "string") {
+ const rewritten = node.replace(pattern, rewrite);
+ return windows && rewritten !== node && key !== undefined && PATH_KEYS.has(key)
+ ? rewritten.replace(/\\/g, "/")
+ : rewritten;
+ }
+ if (Array.isArray(node)) return node.map((child) => walk(child, key));
+ if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) {
+ return Object.fromEntries(
+ Object.entries(node).map(([k, child]) => [k, SKIPPED_KEYS.has(k) ? child : walk(child, k)]),
+ );
+ }
+ return node;
+ };
+ return walk(value);
+}
+
+export function relativizeFilePath(
+ file: string,
+ aliases: readonly PathAlias[],
+ platform: NodeJS.Platform = process.platform,
+): string {
+ const rewritten = relativizePaths({ file_path: file }, aliases, platform) as { file_path: string };
+ return rewritten.file_path;
+}
diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts
index 51024e86d7..163165335c 100644
--- a/src/hooks/pre-tool-use.ts
+++ b/src/hooks/pre-tool-use.ts
@@ -1,5 +1,7 @@
#!/usr/bin/env node
import { resolveClientSecret } from "../secret-store.js";
+import { hookCwd, relativePathsEnabled, resolveProject } from "./_project.js";
+import { relativizeFilePath, repositoryRoots } from "./_relative-paths.js";
function isSdkChildContext(payload: unknown): boolean {
if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true;
@@ -81,10 +83,16 @@ async function main() {
typeof rawSessionId === "string" && rawSessionId.length > 0
? rawSessionId
: "unknown";
+ const relativeFiles = relativePathsEnabled();
+ const cwd = hookCwd(data) || process.cwd();
const project =
typeof data.project === "string" && data.project.trim().length > 0
? data.project.trim()
- : undefined;
+ : relativeFiles
+ ? resolveProject(cwd) || undefined
+ : undefined;
+ const aliases = relativeFiles ? repositoryRoots(cwd) : [];
+ const queryFiles = relativeFiles ? files.map((file) => relativizeFilePath(file, aliases)) : files;
try {
const res = await fetch(`${REST_URL}/agentmemory/enrich`, {
@@ -92,10 +100,11 @@ async function main() {
headers: authHeaders(),
body: JSON.stringify({
sessionId,
- files,
+ files: queryFiles,
terms,
toolName,
...(project !== undefined && { project }),
+ ...(relativeFiles && { relativeFiles: true }),
}),
signal: AbortSignal.timeout(2000),
});
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index fa526182d0..ed8334870f 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -213,9 +213,11 @@ export function registerMcpEndpoints(
body: { error: "files must contain at least one valid path" },
};
}
- const payload: { sessionId?: string; files: string[] } = { files: fileList };
+ const payload: { sessionId?: string; files: string[]; project?: string } = { files: fileList };
const sessionId = asNonEmptyString(args.sessionId);
if (sessionId) payload.sessionId = sessionId;
+ const project = asNonEmptyString(args.project);
+ if (project) payload.project = project;
const result = await sdk.trigger({
function_id: "mem::file-context",
payload,
diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.ts
index 22ffa04715..0ba7ded9c8 100644
--- a/src/mcp/tools-registry.ts
+++ b/src/mcp/tools-registry.ts
@@ -112,6 +112,10 @@ export const CORE_TOOLS: McpToolDef[] = [
type: "string",
description: "Current session ID to exclude",
},
+ project: {
+ type: "string",
+ description: "Only search sessions of this project",
+ },
},
required: ["files"],
},
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index e7176ca9a4..873afe42a3 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1550,11 +1550,20 @@ export function registerApiTriggers(
sdk.registerFunction("api::file-context",
async (
- req: HttpRequest<{ sessionId: string; files: string[] }>,
+ req: HttpRequest<{ sessionId?: string; files: string[]; project?: string; relativeFiles?: boolean }>,
): Promise => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger({ function_id: "mem::file-context", payload: req.body });
+ const body = req.body ?? { files: [] };
+ const result = await sdk.trigger({
+ function_id: "mem::file-context",
+ payload: {
+ sessionId: body.sessionId,
+ files: body.files,
+ ...(typeof body.project === "string" && { project: body.project }),
+ ...(body.relativeFiles === true && { relativeFiles: true }),
+ },
+ });
return { status_code: 200, body: result };
},
);
@@ -1572,6 +1581,7 @@ export function registerApiTriggers(
terms?: string[];
toolName?: string;
project?: string;
+ relativeFiles?: boolean;
}>,
): Promise => {
const authErr = checkAuth(req, secret);
@@ -1617,6 +1627,7 @@ export function registerApiTriggers(
...(req.body.terms !== undefined && { terms: req.body.terms }),
...(req.body.toolName !== undefined && { toolName: req.body.toolName }),
...(req.body.project !== undefined && { project: req.body.project }),
+ ...(req.body.relativeFiles === true && { relativeFiles: true }),
},
});
return { status_code: 200, body: result };
diff --git a/test/file-context-relative-paths.test.ts b/test/file-context-relative-paths.test.ts
new file mode 100644
index 0000000000..d7ac8b24a2
--- /dev/null
+++ b/test/file-context-relative-paths.test.ts
@@ -0,0 +1,162 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { mockKV, mockSdk } from "./helpers/mocks.js";
+import { KV } from "../src/state/schema.js";
+import { registerFileIndexFunction } from "../src/functions/file-index.js";
+import { registerEnrichFunction } from "../src/functions/enrich.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock("../src/functions/audit.js", () => ({
+ recordAudit: vi.fn(),
+}));
+
+vi.mock("../src/functions/access-tracker.js", () => ({
+ recordAccessBatch: vi.fn(),
+}));
+
+const PROJECTS = ["repo-a", "repo-b", "repo-c", "repo-w"];
+
+async function seed(
+ kv: ReturnType,
+ sessionId: string,
+ project: string,
+ file: string,
+ label = file,
+ cwd = `/repos/${project}`,
+) {
+ const startedAt = new Date().toISOString();
+ await kv.set(KV.sessions, sessionId, { id: sessionId, project, cwd, startedAt, status: "completed", observationCount: 1 });
+ await kv.set(KV.observations(sessionId), `obs_${sessionId}`, {
+ id: `obs_${sessionId}`,
+ sessionId,
+ timestamp: startedAt,
+ type: "file_edit",
+ title: `edited ${label} in ${project}`,
+ narrative: "",
+ facts: [],
+ concepts: [],
+ files: [file],
+ importance: 6,
+ });
+}
+
+describe("mem::file-context", () => {
+ let sdk: ReturnType;
+ let kv: ReturnType;
+
+ const lookup = async (payload: Record) => {
+ const { context } = (await sdk.trigger("mem::file-context", payload)) as { context: string };
+ return context;
+ };
+ const projectsIn = (context: string) => PROJECTS.filter((project) => context.includes(`in ${project}`));
+
+ beforeEach(async () => {
+ sdk = mockSdk({ looseTrigger: true });
+ kv = mockKV();
+ registerFileIndexFunction(sdk as never, kv as never);
+ await seed(kv, "ses_a", "repo-a", "src/a.ts");
+ await seed(kv, "ses_b", "repo-b", "src/a.ts");
+ await seed(kv, "ses_abs", "repo-c", "/repos/repo-c/src/a.ts");
+ });
+
+ describe("without relativeFiles", () => {
+ it("matches as before: an absolute query also finds relative entries", async () => {
+ expect(projectsIn(await lookup({ files: ["/repos/repo-c/src/a.ts"] }))).toEqual(["repo-a", "repo-b", "repo-c"]);
+ });
+ });
+
+ describe("with relativeFiles", () => {
+ it("matches a relative entry of the scoped project exactly", async () => {
+ expect(projectsIn(await lookup({ files: ["src/a.ts"], project: "repo-a", relativeFiles: true }))).toEqual(["repo-a"]);
+ });
+
+ it("does not match a root-level entry to a nested file of the same name, or the reverse", async () => {
+ await seed(kv, "ses_root", "repo-a", "package.json", "root package.json");
+ await seed(kv, "ses_nested", "repo-a", "packages/x/package.json", "nested package.json");
+ const nested = await lookup({ files: ["packages/x/package.json"], project: "repo-a", relativeFiles: true });
+ const root = await lookup({ files: ["package.json"], project: "repo-a", relativeFiles: true });
+ expect([nested.includes("nested package.json"), nested.includes("root package.json")]).toEqual([true, false]);
+ expect([root.includes("root package.json"), root.includes("nested package.json")]).toEqual([true, false]);
+ });
+
+ it("matches an absolute entry from before relative capture by its path inside the repository", async () => {
+ expect(projectsIn(await lookup({ files: ["src/a.ts"], project: "repo-c", relativeFiles: true }))).toEqual(["repo-c"]);
+ expect(projectsIn(await lookup({ files: ["a.ts"], project: "repo-c", relativeFiles: true }))).toEqual([]);
+ });
+
+ it("finds an older absolute entry only under the session's repository root", async () => {
+ await seed(kv, "ses_sub", "repo-x", "/repos/repo-x/packages/x/package.json", "x package.json", "/repos/repo-x/packages/x");
+ await seed(kv, "ses_out", "repo-x", "/repos/src/b.ts", "outside b.ts", "/repos/repo-x");
+ await seed(kv, "ses_top", "repo-x", "/src/b.ts", "top b.ts", "/repos/repo-x");
+ const root = await lookup({ files: ["package.json"], project: "repo-x", relativeFiles: true });
+ const nested = await lookup({ files: ["packages/x/package.json"], project: "repo-x", relativeFiles: true });
+ const outside = await lookup({ files: ["src/b.ts"], project: "repo-x", relativeFiles: true });
+ expect([root.includes("x package.json"), nested.includes("x package.json")]).toEqual([false, true]);
+ expect([outside.includes("outside b.ts"), outside.includes("top b.ts")]).toEqual([false, false]);
+ });
+
+ it("compares Windows paths in any case", async () => {
+ await seed(kv, "ses_drive", "repo-w", "C:\\r\\repo-w\\src\\d.ts", "drive d.ts", "c:\\r\\repo-w");
+ await seed(kv, "ses_dirs", "repo-w", "c:\\r\\repo-w\\src\\e.ts", "dirs e.ts", "C:\\R\\Repo-W");
+ expect(await lookup({ files: ["src/d.ts"], project: "repo-w", relativeFiles: true })).toContain("drive d.ts");
+ expect(await lookup({ files: ["src/e.ts"], project: "repo-w", relativeFiles: true })).toContain("dirs e.ts");
+ });
+
+ it("matches a stored Windows entry", async () => {
+ await seed(kv, "ses_win", "repo-w", "src\\w.ts");
+ expect(projectsIn(await lookup({ files: ["src/w.ts"], project: "repo-w", relativeFiles: true }))).toEqual(["repo-w"]);
+ });
+
+ it("matches an absolute query as before", async () => {
+ expect(projectsIn(await lookup({ files: ["/repos/repo-c/src/a.ts"], relativeFiles: true }))).toEqual(["repo-a", "repo-b", "repo-c"]);
+ });
+ });
+});
+
+describe("mem::enrich", () => {
+ async function fileContextPayload(payload: Record) {
+ const sdk = mockSdk({ looseTrigger: true });
+ registerEnrichFunction(sdk as never, mockKV() as never);
+ const fileContext = vi.fn(async (_payload: unknown) => ({ context: "" }));
+ sdk.registerFunction("mem::file-context", fileContext);
+ sdk.registerFunction("mem::search", async () => ({ results: [] }));
+ await sdk.trigger("mem::enrich", { sessionId: "ses_now", files: ["src/a.ts"], ...payload });
+ return fileContext.mock.calls[0]?.[0];
+ }
+
+ it("passes its project and relativeFiles to mem::file-context for a relative request", async () => {
+ expect(await fileContextPayload({ project: "repo-a", relativeFiles: true })).toMatchObject({
+ project: "repo-a",
+ relativeFiles: true,
+ });
+ });
+
+ it("does not scope mem::file-context by project otherwise", async () => {
+ expect(await fileContextPayload({ project: "repo-a" })).not.toHaveProperty("project");
+ });
+
+ it("matches bug memories at path boundaries for a relative request, and as before otherwise", async () => {
+ const pastErrors = async (relativeFiles: boolean, memoryFile = "/x/data.ts", requested = "a.ts") => {
+ const sdk = mockSdk({ looseTrigger: true });
+ const kv = mockKV();
+ registerEnrichFunction(sdk as never, kv as never);
+ sdk.registerFunction("mem::file-context", async () => ({ context: "" }));
+ sdk.registerFunction("mem::search", async () => ({ results: [] }));
+ const now = new Date().toISOString();
+ await kv.set(KV.memories, "mem_bug", {
+ id: "mem_bug", type: "bug", isLatest: true, title: "data bug", content: "broke", files: [memoryFile],
+ createdAt: now, updatedAt: now,
+ });
+ const { context } = (await sdk.trigger("mem::enrich", { sessionId: "s", files: [requested], ...(relativeFiles && { relativeFiles }) })) as {
+ context: string;
+ };
+ return context.includes("data bug");
+ };
+ expect(await pastErrors(true)).toBe(false);
+ expect(await pastErrors(false)).toBe(true);
+ expect(await pastErrors(true, "bar.ts", "foo/bar.ts")).toBe(false);
+ expect(await pastErrors(true, "/x/foo/bar.ts", "foo/bar.ts")).toBe(true);
+ });
+});
diff --git a/test/hook-relative-paths.test.ts b/test/hook-relative-paths.test.ts
new file mode 100644
index 0000000000..329361a035
--- /dev/null
+++ b/test/hook-relative-paths.test.ts
@@ -0,0 +1,331 @@
+import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest";
+import { execFileSync, spawn } from "node:child_process";
+import { createServer } from "node:http";
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { ignoresCase, relativizeFilePath, relativizePaths, repositoryRoots } from "../src/hooks/_relative-paths.js";
+
+describe("relativizePaths", () => {
+ const roots = [
+ { from: "/work/app/.claude/worktrees/fix", to: "" },
+ { from: "/work/app", to: "" },
+ ];
+
+ it("strips the root from a file path", () => {
+ expect(relativizePaths({ file_path: "/work/app/src/a.ts" }, roots, "linux")).toEqual({ file_path: "src/a.ts" });
+ });
+
+ it("strips a nested worktree before the checkout that contains it", () => {
+ expect(relativizePaths("/work/app/.claude/worktrees/fix/src/a.ts", roots, "linux")).toBe("src/a.ts");
+ });
+
+ it("rewrites every occurrence inside free text", () => {
+ expect(relativizePaths("cd /work/app && cat /work/app/README.md", roots, "linux")).toBe("cd . && cat README.md");
+ });
+
+ it("leaves a sibling directory that shares the root as a prefix", () => {
+ expect(relativizePaths("/work/app-old/src/a.ts", roots, "linux")).toBe("/work/app-old/src/a.ts");
+ });
+
+ it("leaves a path that only contains the root further in", () => {
+ expect(relativizePaths("/mnt/work/app/src/a.ts", roots, "linux")).toBe("/mnt/work/app/src/a.ts");
+ });
+
+ it("walks arrays and nested objects and keeps other values", () => {
+ expect(
+ relativizePaths({ edits: [{ path: "/work/app/x.ts", line: 3 }], ok: true, none: null }, roots, "linux"),
+ ).toEqual({ edits: [{ path: "x.ts", line: 3 }], ok: true, none: null });
+ });
+
+ it("maps an alias onto its path inside the repository", () => {
+ const aliases = [{ from: "/links/sub", to: "packages/sub" }];
+ expect(relativizePaths("cat /links/sub/a.ts /links/sub", aliases, "linux")).toBe("cat packages/sub/a.ts packages/sub");
+ });
+
+ it("matches Windows roots in any case and writes forward slashes", () => {
+ const aliases = [{ from: "C:\\work\\app", to: "" }];
+ expect(relativizePaths("c:\\Work\\App\\src\\a.ts", aliases, "win32")).toBe("src/a.ts");
+ expect(relativizePaths("type C:\\work\\app\\x.ts", aliases, "win32")).toBe("type x.ts");
+ });
+
+ it("converts a Windows path field in full, spaces and punctuation included", () => {
+ const aliases = [{ from: "C:\\work\\app", to: "" }];
+ expect(relativizePaths({ file_path: "C:\\work\\app\\my dir\\lib(test)\\a.ts" }, aliases, "win32")).toEqual({
+ file_path: "my dir/lib(test)/a.ts",
+ });
+ });
+
+ it("converts Windows free text only up to the next space", () => {
+ const aliases = [{ from: "C:\\work\\app", to: "" }];
+ expect(relativizePaths("C:\\work\\app\\a.ts and docs\\guide.md", aliases, "win32")).toBe("a.ts and docs\\guide.md");
+ expect(relativizePaths("C:\\work\\app\\a.ts C:\\work\\app\\b.ts", aliases, "win32")).toBe("a.ts b.ts");
+ expect(relativizePaths("see C:\\work\\app\\src\\lib(test)\\x.ts", aliases, "win32")).toBe("see src/lib(test)/x.ts");
+ });
+
+ it("keeps a POSIX path's case and backslashes", () => {
+ expect(relativizePaths("/work/app/my\\ file.ts /Work/App/x", roots, "linux")).toBe("my\\ file.ts /Work/App/x");
+ });
+
+ it("writes a root with trailing or doubled slashes as `.` and collapses the slashes", () => {
+ expect(relativizePaths("ls /work/app/", roots, "linux")).toBe("ls .");
+ expect(relativizePaths({ path: "/work/app/" }, roots, "linux")).toEqual({ path: "." });
+ expect(relativizePaths("/work/app//double", roots, "linux")).toBe("double");
+ });
+
+ it("leaves a path after a `host:` prefix, and a bare root before a full stop", () => {
+ expect(relativizePaths("scp build:/work/app/a.ts .", roots, "linux")).toBe("scp build:/work/app/a.ts .");
+ expect(relativizePaths("Run in /work/app.", roots, "linux")).toBe("Run in /work/app.");
+ });
+
+ it("ends a root at shell operators", () => {
+ expect(relativizePaths("cd /work/app|ls && cd /work/app&&ls", roots, "linux")).toBe("cd .|ls && cd .&&ls");
+ });
+
+ it("stops Windows free text at a list separator", () => {
+ const aliases = [{ from: "C:\\work\\app", to: "" }];
+ expect(relativizePaths("C:\\work\\app\\a.ts,C:\\other\\b.ts", aliases, "win32")).toBe("a.ts,C:\\other\\b.ts");
+ expect(relativizePaths("type C:\\work\\app\\a.ts&C:\\other\\b.ts", aliases, "win32")).toBe("type a.ts&C:\\other\\b.ts");
+ });
+
+ it("matches roots in any case only when told the file system ignores case", () => {
+ expect(relativizePaths("/Work/App/x.ts", roots, "darwin", true)).toBe("x.ts");
+ expect(relativizePaths("/Work/App/x.ts", roots, "darwin", false)).toBe("/Work/App/x.ts");
+ expect(relativizePaths("/Work/App/x.ts", roots, "linux")).toBe("/Work/App/x.ts");
+ });
+
+ it("decides case for each root, so one case-sensitive worktree does not change the others", () => {
+ const aliases = [{ from: "/vol2/wt", to: "" }, { from: "/work/app", to: "" }];
+ const onlyApp = (root: string) => root === "/work/app";
+ expect(relativizePaths("/WORK/APP/x.ts /VOL2/WT/y.ts /vol2/wt/z.ts", aliases, "darwin", onlyApp)).toBe(
+ "x.ts /VOL2/WT/y.ts z.ts",
+ );
+ });
+
+ it("asks the file system whether a macOS root ignores case", () => {
+ const dir = join(realpathSync(mkdtempSync(join(tmpdir(), "amem-case-"))), "CaseRoot");
+ mkdirSync(dir);
+ try {
+ const insensitive = existsSync(join(dirname(dir), "caseroot"));
+ const lower = join(dirname(dir), "caseroot", "a.ts");
+ expect(ignoresCase(dir)).toBe(insensitive);
+ expect(relativizePaths(lower, [{ from: dir, to: "" }], "darwin")).toBe(insensitive ? "a.ts" : lower);
+ } finally {
+ rmSync(dirname(dir), { recursive: true, force: true });
+ }
+ });
+
+ it("returns the value untouched when there are no roots", () => {
+ const value = { file_path: "/work/app/src/a.ts" };
+ expect(relativizePaths(value, [], "linux")).toBe(value);
+ });
+
+ it("leaves image data alone", () => {
+ expect(relativizePaths({ image_data: "/work/app/x", other: "/work/app/x" }, roots, "linux")).toEqual({
+ image_data: "/work/app/x",
+ other: "x",
+ });
+ });
+
+ it("relativizes one file path as a path field", () => {
+ expect(relativizeFilePath("C:\\work\\app\\my dir\\a.ts", [{ from: "C:\\work\\app", to: "" }], "win32")).toBe("my dir/a.ts");
+ expect(relativizeFilePath("/elsewhere/a.ts", roots, "linux")).toBe("/elsewhere/a.ts");
+ });
+});
+
+describe("repositoryRoots", () => {
+ let tmpRoot: string;
+ let repoDir: string;
+ let worktreeDir: string;
+ let linkDir: string;
+ let subLinkDir: string;
+ let worktreeSrcLinkDir: string;
+ let outsideSubLinkDir: string;
+ let newlineWorktreeDir: string;
+ const froms = (cwd: string) => repositoryRoots(cwd).map((alias) => alias.from).filter((from) => from !== newlineWorktreeDir);
+
+ beforeAll(() => {
+ tmpRoot = realpathSync(mkdtempSync(join(tmpdir(), "amem-roots-")));
+ repoDir = join(tmpRoot, "repo");
+ worktreeDir = join(repoDir, ".claude", "worktrees", "fix");
+ linkDir = join(tmpRoot, "linked");
+ mkdirSync(repoDir, { recursive: true });
+ const git = (...args: string[]) => execFileSync("git", args, { cwd: repoDir, stdio: "ignore" });
+ git("init", "--quiet");
+ git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "--allow-empty", "-m", "init");
+ mkdirSync(dirname(worktreeDir), { recursive: true });
+ git("worktree", "add", "--quiet", "-b", "fix", worktreeDir);
+ symlinkSync(repoDir, linkDir);
+ mkdirSync(join(repoDir, "packages", "sub"), { recursive: true });
+ subLinkDir = join(tmpRoot, "sub-link");
+ symlinkSync(join(repoDir, "packages", "sub"), subLinkDir);
+ mkdirSync(join(worktreeDir, "src"), { recursive: true });
+ worktreeSrcLinkDir = join(tmpRoot, "worktree-src-link");
+ symlinkSync(join(worktreeDir, "src"), worktreeSrcLinkDir);
+ mkdirSync(join(tmpRoot, "elsewhere", "packages"), { recursive: true });
+ outsideSubLinkDir = join(tmpRoot, "elsewhere", "packages", "sub");
+ symlinkSync(join(repoDir, "packages", "sub"), outsideSubLinkDir);
+ newlineWorktreeDir = join(tmpRoot, "odd\nname");
+ git("worktree", "add", "--quiet", "-b", "odd", newlineWorktreeDir);
+ });
+
+ afterAll(() => {
+ rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ it("lists every worktree, longest first, from inside the main checkout", () => {
+ expect(froms(repoDir)).toEqual([worktreeDir, repoDir]);
+ });
+
+ it("lists the same roots from inside a worktree", () => {
+ expect(froms(worktreeDir)).toEqual([worktreeDir, repoDir]);
+ });
+
+ it("adds the symlinked spelling cwd was reached through", () => {
+ expect(repositoryRoots(linkDir)).toContainEqual({ from: linkDir, to: "" });
+ });
+
+ it("maps a symlink to a subdirectory onto that subdirectory", () => {
+ expect(repositoryRoots(subLinkDir)).toContainEqual({ from: subLinkDir, to: join("packages", "sub") });
+ });
+
+ it("ignores a trailing slash on a symlinked cwd", () => {
+ expect(repositoryRoots(`${subLinkDir}/`)).toContainEqual({ from: subLinkDir, to: join("packages", "sub") });
+ });
+
+ it("does not alias a symlink's parent that is not the repository", () => {
+ const aliases = repositoryRoots(outsideSubLinkDir);
+ expect(aliases).toContainEqual({ from: outsideSubLinkDir, to: join("packages", "sub") });
+ expect(aliases.map((alias) => alias.from)).not.toContain(join(tmpRoot, "elsewhere"));
+ });
+
+ it("maps a symlink into a nested worktree onto that worktree, not the main checkout", () => {
+ expect(repositoryRoots(worktreeSrcLinkDir)).toContainEqual({ from: worktreeSrcLinkDir, to: "src" });
+ });
+
+ it("reads a worktree path that contains a newline", () => {
+ expect(repositoryRoots(repoDir)).toContainEqual({ from: newlineWorktreeDir, to: "" });
+ });
+
+ it("returns nothing outside a repository", () => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "amem-noroots-")));
+ vi.stubEnv("GIT_CEILING_DIRECTORIES", dirname(dir));
+ try {
+ expect(repositoryRoots(dir)).toEqual([]);
+ } finally {
+ vi.unstubAllEnvs();
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("captureObservation with AGENTMEMORY_RELATIVE_PATHS", () => {
+ let tmpRoot: string;
+ let repoDir: string;
+
+ beforeAll(() => {
+ tmpRoot = realpathSync(mkdtempSync(join(tmpdir(), "amem-capture-rel-")));
+ repoDir = join(tmpRoot, "repo");
+ mkdirSync(repoDir, { recursive: true });
+ execFileSync("git", ["init", "--quiet"], { cwd: repoDir, stdio: "ignore" });
+ });
+
+ afterAll(() => {
+ rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ vi.resetModules();
+ });
+
+ async function sentBody(flag: string | undefined): Promise> {
+ vi.stubEnv("AGENTMEMORY_RELATIVE_PATHS", flag);
+ vi.stubEnv("AGENTMEMORY_CAPTURE_SPOOL_DIR", join(tmpRoot, "spool"));
+ const fetchMock = vi.fn(async () => new Response("{}", { status: 201 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const { captureObservation } = await import("../src/hooks/_capture.js");
+ await captureObservation(
+ {
+ hookType: "post_tool_use",
+ sessionId: "ses_rel",
+ project: "repo",
+ cwd: repoDir,
+ timestamp: new Date().toISOString(),
+ data: { tool_name: "Read", tool_input: { file_path: join(repoDir, "src", "a.ts") } },
+ },
+ 1000,
+ );
+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined;
+ return JSON.parse(String(init?.body));
+ }
+
+ it("sends repository-relative paths when enabled, and keeps cwd as it is", async () => {
+ const body = await sentBody("true");
+ expect(body.data).toEqual({ tool_name: "Read", tool_input: { file_path: "src/a.ts" } });
+ expect(body.cwd).toBe(repoDir);
+ });
+
+ it("sends absolute paths by default", async () => {
+ const body = await sentBody(undefined);
+ expect(body.data).toEqual({ tool_name: "Read", tool_input: { file_path: join(repoDir, "src", "a.ts") } });
+ });
+});
+
+describe("pre-tool-use with AGENTMEMORY_RELATIVE_PATHS", () => {
+ let tmpRoot: string;
+ let repoDir: string;
+
+ beforeAll(() => {
+ tmpRoot = realpathSync(mkdtempSync(join(tmpdir(), "amem-pretool-")));
+ repoDir = join(tmpRoot, "repo");
+ mkdirSync(repoDir, { recursive: true });
+ execFileSync("git", ["init", "--quiet"], { cwd: repoDir, stdio: "ignore" });
+ });
+
+ afterAll(() => {
+ rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ async function enrichBody(relative: string): Promise | undefined> {
+ const bodies: Array> = [];
+ const server = createServer((req, res) => {
+ let raw = "";
+ req.on("data", (chunk) => (raw += chunk));
+ req.on("end", () => {
+ bodies.push(JSON.parse(raw));
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end("{}");
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ const port = typeof address === "object" && address ? address.port : 0;
+ const child = spawn(process.execPath, [join(import.meta.dirname, "..", "plugin", "scripts", "pre-tool-use.mjs")], {
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ HOME: tmpRoot,
+ AGENTMEMORY_URL: `http://127.0.0.1:${port}`,
+ AGENTMEMORY_INJECT_CONTEXT: "true",
+ AGENTMEMORY_RELATIVE_PATHS: relative,
+ },
+ stdio: ["pipe", "ignore", "ignore"],
+ });
+ child.stdin.end(JSON.stringify({ session_id: "ses_pre", cwd: repoDir, tool_name: "Read", tool_input: { file_path: join(repoDir, "a.ts") } }));
+ await new Promise((resolve) => child.on("close", resolve));
+ server.close();
+ return bodies[0];
+ }
+
+ it("asks with repository-relative files, scoped to the repository's project", async () => {
+ expect(await enrichBody("true")).toMatchObject({ files: ["a.ts"], project: "repo", relativeFiles: true });
+ });
+
+ it("asks as before by default", async () => {
+ const body = await enrichBody("");
+ expect(body).toMatchObject({ files: [join(repoDir, "a.ts")] });
+ expect(body).not.toHaveProperty("project");
+ expect(body).not.toHaveProperty("relativeFiles");
+ });
+});
diff --git a/test/relative-paths-spec.test.ts b/test/relative-paths-spec.test.ts
new file mode 100644
index 0000000000..c1f798c85e
--- /dev/null
+++ b/test/relative-paths-spec.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect, vi } from "vitest";
+import { mockKV, mockSdk } from "./helpers/mocks.js";
+import { KV } from "../src/state/schema.js";
+import { registerFileIndexFunction } from "../src/functions/file-index.js";
+import { relativizeFilePath, relativizePaths, type PathAlias } from "../src/hooks/_relative-paths.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock("../src/functions/audit.js", () => ({
+ recordAudit: vi.fn(),
+}));
+
+vi.mock("../src/functions/access-tracker.js", () => ({
+ recordAccessBatch: vi.fn(),
+}));
+
+const posix: PathAlias[] = [
+ { from: "/repo/.claude/worktrees/wt", to: "" },
+ { from: "/repo", to: "" },
+];
+
+describe("capture: what a hook sends", () => {
+ it.each([
+ ["a file in the repository", "/repo/src/a.ts", "src/a.ts"],
+ ["a file in a nested worktree", "/repo/.claude/worktrees/wt/src/a.ts", "src/a.ts"],
+ ["the root", "/repo", "."],
+ ["the root with a trailing slash", "/repo/", "."],
+ ["a doubled slash", "/repo//src/a.ts", "src/a.ts"],
+ ["a quoted path", '"/repo/a.ts"', '"a.ts"'],
+ ["a path with a line suffix", "/repo/a.ts:12:3", "a.ts:12:3"],
+ ["a path before shell operators", "cd /repo&&ls|wc", "cd .&&ls|wc"],
+ ["a sibling directory", "/repo-old/a.ts", "/repo-old/a.ts"],
+ ["the root inside a longer path", "/mnt/repo/a.ts", "/mnt/repo/a.ts"],
+ ["a remote `host:` path", "scp host:/repo/a.ts .", "scp host:/repo/a.ts ."],
+ ["a URL path", "https://example.com/repo/a", "https://example.com/repo/a"],
+ ["another case on a case-sensitive volume", "/Repo/a.ts", "/Repo/a.ts"],
+ ])("Linux: %s", (_name, input, expected) => {
+ expect(relativizePaths(input, posix, "linux")).toBe(expected);
+ });
+
+ it.each([
+ ["another case on a case-insensitive volume", "/REPO/a.ts", true, "a.ts"],
+ ["another case on a case-sensitive volume", "/REPO/a.ts", false, "/REPO/a.ts"],
+ ])("macOS: %s", (_name, input, ignoresCase, expected) => {
+ expect(relativizePaths(input, posix, "darwin", ignoresCase)).toBe(expected);
+ });
+
+ it.each([
+ ["a path field, in full", { file_path: "C:\\Repo\\my dir\\a (1).ts" }, { file_path: "my dir/a (1).ts" }],
+ ["free text, up to the next space", "C:\\repo\\a.ts and docs\\b.md", "a.ts and docs\\b.md"],
+ ])("Windows: %s", (_name, input, expected) => {
+ expect(relativizePaths(input, [{ from: "C:\\repo", to: "" }], "win32")).toEqual(expected);
+ });
+});
+
+describe("round trip: capture on one machine, look up on another", () => {
+ const mac: PathAlias[] = [
+ { from: "/Users/me/Dev/app/.claude/worktrees/fix", to: "" },
+ { from: "/Users/me/Dev/app", to: "" },
+ ];
+ const laptop: PathAlias[] = [{ from: "/home/me/dev/app", to: "" }];
+
+ async function store() {
+ const sdk = mockSdk({ looseTrigger: true });
+ const kv = mockKV();
+ registerFileIndexFunction(sdk as never, kv as never);
+ const capture = async (id: string, project: string, cwd: string, absolute: string, aliases: PathAlias[]) => {
+ const startedAt = new Date().toISOString();
+ await kv.set(KV.sessions, id, { id, project, cwd, startedAt, status: "completed", observationCount: 1 });
+ await kv.set(KV.observations(id), `obs_${id}`, {
+ id: `obs_${id}`, sessionId: id, timestamp: startedAt, type: "file_edit", title: `seen ${id}`,
+ narrative: "", facts: [], concepts: [], importance: 6,
+ files: [relativizeFilePath(absolute, aliases, "darwin")],
+ });
+ };
+ await capture("mac_src", "app", "/Users/me/Dev/app", "/Users/me/Dev/app/src/a.ts", mac);
+ await capture("mac_wt", "app", "/Users/me/Dev/app/.claude/worktrees/fix", "/Users/me/Dev/app/.claude/worktrees/fix/lib/b.ts", mac);
+ await capture("mac_root", "app", "/Users/me/Dev/app", "/Users/me/Dev/app/package.json", mac);
+ await capture("mac_nested", "app", "/Users/me/Dev/app", "/Users/me/Dev/app/packages/x/package.json", mac);
+ await capture("other_src", "other", "/Users/me/Dev/other", "/Users/me/Dev/other/src/a.ts", [{ from: "/Users/me/Dev/other", to: "" }]);
+ const found = async (absolute: string, relativeFiles = true) => {
+ const query = relativeFiles ? relativizeFilePath(absolute, laptop, "linux") : absolute;
+ const { context } = (await sdk.trigger("mem::file-context", {
+ files: [query],
+ ...(relativeFiles && { project: "app", relativeFiles: true }),
+ })) as { context: string };
+ return ["mac_src", "mac_wt", "mac_root", "mac_nested", "other_src"].filter((id) => context.includes(`seen ${id}`));
+ };
+ return found;
+ }
+
+ it.each([
+ ["a file captured in the main checkout", "/home/me/dev/app/src/a.ts", ["mac_src"]],
+ ["a file captured in a worktree", "/home/me/dev/app/lib/b.ts", ["mac_wt"]],
+ ["the root package.json, not the nested one", "/home/me/dev/app/package.json", ["mac_root"]],
+ ["the nested package.json, not the root one", "/home/me/dev/app/packages/x/package.json", ["mac_nested"]],
+ ["a file nobody captured", "/home/me/dev/app/src/none.ts", []],
+ ])("finds %s", async (_name, query, expected) => {
+ const found = await store();
+ expect(await found(query)).toEqual(expected);
+ });
+
+ it("matches as on main when the request is not relative", async () => {
+ const found = await store();
+ expect(await found("/home/me/dev/app/src/a.ts", false)).toEqual(["mac_src", "other_src"]);
+ });
+});