From 3c23620e137d1f6cad999798d41d49b6b2beb5d1 Mon Sep 17 00:00:00 2001
From: Spike Jourdain
Date: Tue, 27 Oct 2026 09:41:21 +1100
Subject: [PATCH 1/7] feat(hooks): send repository-relative paths with
AGENTMEMORY_RELATIVE_PATHS
Machines that clone one repository to different places, and worktrees of
one checkout, recorded the same file under different absolute paths, so a
shared daemon split its file nodes, file history and recall by machine.
With AGENTMEMORY_RELATIVE_PATHS=true, captureObservation rewrites every
path under the repository's worktrees (each spelling: as git records it,
resolved, and the symlinked path cwd was reached through) relative to that
worktree's root before it sends or spools the event. Longest root first,
so a nested worktree is stripped before its checkout. cwd is unchanged.
Off by default.
Co-Authored-By: Claude Opus 5.5
Signed-off-by: Spike Jourdain
---
CHANGELOG.md | 4 +
plugin/scripts/_capture.mjs | 78 +++++++++-
plugin/skills/agentmemory-config/REFERENCE.md | 3 +-
scripts/docs-sync.state.json | 2 +-
src/hooks/_capture.ts | 4 +-
src/hooks/_relative-paths.ts | 92 +++++++++++
test/hook-relative-paths.test.ts | 143 ++++++++++++++++++
7 files changed, 321 insertions(+), 5 deletions(-)
create mode 100644 src/hooks/_relative-paths.ts
create mode 100644 test/hook-relative-paths.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index abac402cbc..cc59a44a62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
+### Added
+
+- **Repository-relative paths in captures.** With `AGENTMEMORY_RELATIVE_PATHS=true` on the machine running the hooks, every path under the current repository, or under any of its worktrees, reaches the daemon relative to that worktree's root (`src/a.ts`, not `/Users/me/dev/app/src/a.ts`). Machines that clone the same repository to different places, and worktrees of one checkout, then share file nodes, file history and recall in one daemon. `cwd` is still sent as it is. Off by default.
+
## [0.9.31] — 2026-10-25
### Upgrade notes
diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs
index eb568a2403..4195a89da9 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,78 @@ async function drainSpool(url, send, options = {}) {
}
}
//#endregion
+//#region src/hooks/_relative-paths.ts
+function relativePathsEnabled() {
+ return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true";
+}
+function repositoryRoots(cwd) {
+ let listing;
+ try {
+ listing = execFileSync("git", [
+ "worktree",
+ "list",
+ "--porcelain"
+ ], {
+ cwd,
+ stdio: [
+ "ignore",
+ "pipe",
+ "ignore"
+ ],
+ timeout: 500
+ }).toString();
+ } catch {
+ return [];
+ }
+ const recorded = listing.split(/\r?\n/).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 logical = logicalRoot(cwd, [...roots]);
+ if (logical) roots.add(logical);
+ if (process.platform === "win32") for (const root of [...roots]) roots.add(root.replace(/\//g, "\\"));
+ return [...roots].sort((a, b) => b.length - a.length);
+}
+function tryRealpath(path) {
+ try {
+ return realpathSync(path);
+ } catch {
+ return;
+ }
+}
+function logicalRoot(cwd, roots) {
+ const physical = tryRealpath(cwd);
+ if (!physical || physical === cwd) return void 0;
+ for (const root of roots) {
+ if (physical === root) return cwd;
+ if (!physical.startsWith(`${root}/`)) continue;
+ const inside = physical.slice(root.length);
+ if (cwd.endsWith(inside)) return cwd.slice(0, cwd.length - inside.length);
+ }
+}
+function escapeRegExp(text) {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+function rootPattern(roots) {
+ if (roots.length === 0) return null;
+ const alternatives = roots.map(escapeRegExp).join("|");
+ return new RegExp(`(?]))`, "g");
+}
+function relativizePaths(value, roots) {
+ const pattern = rootPattern(roots);
+ if (!pattern) return value;
+ const walk = (node) => {
+ if (typeof node === "string") return node.replace(pattern, (match) => /[\\/]$/.test(match) ? "" : ".");
+ if (Array.isArray(node)) return node.map(walk);
+ if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) return Object.fromEntries(Object.entries(node).map(([key, child]) => [key, walk(child)]));
+ 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 +976,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/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/scripts/docs-sync.state.json b/scripts/docs-sync.state.json
index 0538665c6a..377ea77be8 100644
--- a/scripts/docs-sync.state.json
+++ b/scripts/docs-sync.state.json
@@ -26,7 +26,7 @@
"322"
],
"sourceFiles": [
- "254"
+ "255"
],
"loc": [
"58000"
diff --git a/src/hooks/_capture.ts b/src/hooks/_capture.ts
index 021c8bff7f..72f0c93ca8 100644
--- a/src/hooks/_capture.ts
+++ b/src/hooks/_capture.ts
@@ -13,6 +13,7 @@ import {
type SentMark,
type SpoolRecord,
} from "../capture/spool.js";
+import { relativePathsEnabled, relativizePaths, repositoryRoots } from "./_relative-paths.js";
export { stripPrivateData } from "../functions/privacy.js";
@@ -100,7 +101,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/_relative-paths.ts b/src/hooks/_relative-paths.ts
new file mode 100644
index 0000000000..5a510832ca
--- /dev/null
+++ b/src/hooks/_relative-paths.ts
@@ -0,0 +1,92 @@
+import { execFileSync } from "node:child_process";
+import { realpathSync } from "node:fs";
+
+export function relativePathsEnabled(): boolean {
+ return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true";
+}
+
+// Every worktree of the repository that holds cwd, under each spelling a hook can see:
+// the path git recorded, its resolved form, and the path cwd was reached through when
+// that goes through a symlink. Longest first, so a worktree nested inside the main
+// checkout is stripped before the checkout itself.
+export function repositoryRoots(cwd: string): string[] {
+ let listing: string;
+ try {
+ listing = execFileSync("git", ["worktree", "list", "--porcelain"], {
+ cwd,
+ stdio: ["ignore", "pipe", "ignore"],
+ timeout: 500,
+ }).toString();
+ } catch {
+ return [];
+ }
+ const recorded = listing
+ .split(/\r?\n/)
+ .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 logical = logicalRoot(cwd, [...roots]);
+ if (logical) roots.add(logical);
+ if (process.platform === "win32") {
+ for (const root of [...roots]) roots.add(root.replace(/\//g, "\\"));
+ }
+ return [...roots].sort((a, b) => b.length - a.length);
+}
+
+function tryRealpath(path: string): string | undefined {
+ try {
+ return realpathSync(path);
+ } catch {
+ return undefined;
+ }
+}
+
+function logicalRoot(cwd: string, roots: string[]): string | undefined {
+ const physical = tryRealpath(cwd);
+ if (!physical || physical === cwd) return undefined;
+ for (const root of roots) {
+ if (physical === root) return cwd;
+ if (!physical.startsWith(`${root}/`)) continue;
+ const inside = physical.slice(root.length);
+ if (cwd.endsWith(inside)) return cwd.slice(0, cwd.length - inside.length);
+ }
+ return undefined;
+}
+
+function escapeRegExp(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+// A root counts only where a path starts (not inside a longer path) and only where it
+// ends (not as the prefix of a sibling such as `repo-old`). `root/x` becomes `x`, the
+// bare root becomes `.`.
+function rootPattern(roots: readonly string[]): RegExp | null {
+ if (roots.length === 0) return null;
+ const alternatives = roots.map(escapeRegExp).join("|");
+ return new RegExp(
+ `(?]))`,
+ "g",
+ );
+}
+
+export function relativizePaths(value: unknown, roots: readonly string[]): unknown {
+ const pattern = rootPattern(roots);
+ if (!pattern) return value;
+ const walk = (node: unknown): unknown => {
+ if (typeof node === "string") {
+ return node.replace(pattern, (match) => (/[\\/]$/.test(match) ? "" : "."));
+ }
+ if (Array.isArray(node)) return node.map(walk);
+ if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) {
+ return Object.fromEntries(Object.entries(node).map(([key, child]) => [key, walk(child)]));
+ }
+ return node;
+ };
+ return walk(value);
+}
diff --git a/test/hook-relative-paths.test.ts b/test/hook-relative-paths.test.ts
new file mode 100644
index 0000000000..2d44a436ca
--- /dev/null
+++ b/test/hook-relative-paths.test.ts
@@ -0,0 +1,143 @@
+import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { relativizePaths, repositoryRoots } from "../src/hooks/_relative-paths.js";
+
+describe("relativizePaths", () => {
+ const roots = ["/work/app/.claude/worktrees/fix", "/work/app"];
+
+ it("strips the root from a file path", () => {
+ expect(relativizePaths({ file_path: "/work/app/src/a.ts" }, roots)).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)).toBe("src/a.ts");
+ });
+
+ it("rewrites every occurrence inside free text", () => {
+ expect(relativizePaths("cd /work/app && cat /work/app/README.md", roots)).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)).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)).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),
+ ).toEqual({ edits: [{ path: "x.ts", line: 3 }], ok: true, none: null });
+ });
+
+ it("returns the value untouched when there are no roots", () => {
+ const value = { file_path: "/work/app/src/a.ts" };
+ expect(relativizePaths(value, [])).toBe(value);
+ });
+});
+
+describe("repositoryRoots", () => {
+ let tmpRoot: string;
+ let repoDir: string;
+ let worktreeDir: string;
+ let linkDir: string;
+
+ 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);
+ });
+
+ afterAll(() => {
+ rmSync(tmpRoot, { recursive: true, force: true });
+ });
+
+ it("lists every worktree, longest first, from inside the main checkout", () => {
+ expect(repositoryRoots(repoDir)).toEqual([worktreeDir, repoDir]);
+ });
+
+ it("lists the same roots from inside a worktree", () => {
+ expect(repositoryRoots(join(worktreeDir))).toEqual([worktreeDir, repoDir]);
+ });
+
+ it("adds the symlinked spelling cwd was reached through", () => {
+ expect(repositoryRoots(linkDir)).toContain(linkDir);
+ });
+
+ 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> {
+ if (flag !== undefined) 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") } });
+ });
+});
From bad6a99b37c09f533d3bc8fad38a7df8dcfd0aa5 Mon Sep 17 00:00:00 2001
From: Spike Jourdain
Date: Tue, 27 Oct 2026 09:55:20 +1100
Subject: [PATCH 2/7] fix(hooks): address review on repository-relative paths
- Scope relative matches: an absolute query matches a repository-relative
entry only in a project-scoped lookup, so unrelated repositories that
share `src/a.ts` stay apart. Enrich passes its project through, and
memory_file_history takes an optional `project`.
- Windows: roots match case-insensitively and the rest of the path is
written with forward slashes, like the file index expects.
- A cwd symlinked to a repository subdirectory maps onto that
subdirectory instead of staying absolute.
- Read `git worktree list --porcelain -z`, falling back to line output on
git older than 2.36.
- Drop the CHANGELOG entry (release PRs only) and trim the comments.
Co-Authored-By: Claude Opus 5.5
Signed-off-by: Spike Jourdain
---
CHANGELOG.md | 4 -
plugin/scripts/_capture.mjs | 103 ++++++++++------
.../skills/agentmemory-mcp-tools/REFERENCE.md | 2 +-
src/functions/enrich.ts | 3 +-
src/functions/file-index.ts | 10 +-
src/hooks/_relative-paths.ts | 111 +++++++++++-------
src/mcp/server.ts | 4 +-
src/mcp/tools-registry.ts | 4 +
test/file-context-relative-paths.test.ts | 78 ++++++++++++
test/hook-relative-paths.test.ts | 44 ++++++-
10 files changed, 268 insertions(+), 95 deletions(-)
create mode 100644 test/file-context-relative-paths.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cc59a44a62..abac402cbc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,10 +6,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
-### Added
-
-- **Repository-relative paths in captures.** With `AGENTMEMORY_RELATIVE_PATHS=true` on the machine running the hooks, every path under the current repository, or under any of its worktrees, reaches the daemon relative to that worktree's root (`src/a.ts`, not `/Users/me/dev/app/src/a.ts`). Machines that clone the same repository to different places, and worktrees of one checkout, then share file nodes, file history and recall in one daemon. `cwd` is still sent as it is. Off by default.
-
## [0.9.31] — 2026-10-25
### Upgrade notes
diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs
index 4195a89da9..7b456619fa 100644
--- a/plugin/scripts/_capture.mjs
+++ b/plugin/scripts/_capture.mjs
@@ -832,36 +832,29 @@ async function drainSpool(url, send, options = {}) {
function relativePathsEnabled() {
return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true";
}
-function repositoryRoots(cwd) {
- let listing;
+function gitWorktreeListing(cwd) {
+ const run = (args) => execFileSync("git", [
+ "worktree",
+ "list",
+ "--porcelain",
+ ...args
+ ], {
+ cwd,
+ stdio: [
+ "ignore",
+ "pipe",
+ "ignore"
+ ],
+ timeout: 500
+ }).toString();
+ try {
+ return run(["-z"]).split("\0");
+ } catch {}
try {
- listing = execFileSync("git", [
- "worktree",
- "list",
- "--porcelain"
- ], {
- cwd,
- stdio: [
- "ignore",
- "pipe",
- "ignore"
- ],
- timeout: 500
- }).toString();
+ return run([]).split(/\r?\n/);
} catch {
return [];
}
- const recorded = listing.split(/\r?\n/).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 logical = logicalRoot(cwd, [...roots]);
- if (logical) roots.add(logical);
- if (process.platform === "win32") for (const root of [...roots]) roots.add(root.replace(/\//g, "\\"));
- return [...roots].sort((a, b) => b.length - a.length);
}
function tryRealpath(path) {
try {
@@ -870,29 +863,63 @@ function tryRealpath(path) {
return;
}
}
-function logicalRoot(cwd, roots) {
+function cwdAliases(cwd, roots) {
const physical = tryRealpath(cwd);
- if (!physical || physical === cwd) return void 0;
+ if (!physical || physical === cwd) return [];
for (const root of roots) {
- if (physical === root) return cwd;
- if (!physical.startsWith(`${root}/`)) continue;
+ if (physical !== root && !physical.startsWith(`${root}/`)) continue;
const inside = physical.slice(root.length);
- if (cwd.endsWith(inside)) return cwd.slice(0, cwd.length - inside.length);
+ if (inside && cwd.endsWith(inside)) return [{
+ from: cwd.slice(0, cwd.length - inside.length),
+ to: ""
+ }];
+ return [{
+ from: cwd,
+ to: relative(root, physical)
+ }];
}
+ return [];
+}
+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 aliases = [...roots].map((from) => ({
+ from,
+ to: ""
+ }));
+ aliases.push(...cwdAliases(cwd, [...roots]));
+ 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, "\\$&");
}
-function rootPattern(roots) {
- if (roots.length === 0) return null;
- const alternatives = roots.map(escapeRegExp).join("|");
- return new RegExp(`(?]))`, "g");
+const PATH_END = `$|[\\s"'\`:;,)\\]}>]`;
+const PATH_REST = `[^\\s"'\`:;,)\\]}>]*`;
+function aliasPattern(aliases, windows) {
+ if (aliases.length === 0) return null;
+ const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|");
+ return new RegExp(`(? {
+ 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) => {
- if (typeof node === "string") return node.replace(pattern, (match) => /[\\/]$/.test(match) ? "" : ".");
+ if (typeof node === "string") return node.replace(pattern, rewrite);
if (Array.isArray(node)) return node.map(walk);
if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) return Object.fromEntries(Object.entries(node).map(([key, child]) => [key, walk(child)]));
return node;
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/src/functions/enrich.ts b/src/functions/enrich.ts
index 05f62acb9d..c022d0ee7e 100644
--- a/src/functions/enrich.ts
+++ b/src/functions/enrich.ts
@@ -25,11 +25,12 @@ 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 }, { context: string }>({
function_id: "mem::file-context",
payload: {
sessionId: data.sessionId,
files: data.files,
+ ...(project !== undefined && { project }),
},
})
.catch(() => ({ context: "" }));
diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts
index a52bf0356f..e237f61552 100644
--- a/src/functions/file-index.ts
+++ b/src/functions/file-index.ts
@@ -19,6 +19,12 @@ interface FileHistory {
}>;
}
+// A repository-relative path names a file only within its project, so an absolute query
+// may match one only when the lookup is scoped to a project.
+function isAbsolutePath(path: string): boolean {
+ return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path);
+}
+
export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void {
sdk.registerFunction("mem::file-context",
async (
@@ -69,6 +75,7 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void {
for (const file of files) {
const history: FileHistory = { file, observations: [] };
const normalizedFile = file.replace(/^\.\//, "");
+ const queryIsAbsolute = isAbsolutePath(file);
for (const session of otherSessions) {
const observations = obsCache.get(session.id) || [];
@@ -80,7 +87,8 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void {
f === file ||
f === normalizedFile ||
f.endsWith(`/${normalizedFile}`) ||
- normalizedFile.endsWith(`/${f}`),
+ (normalizedFile.endsWith(`/${f}`) &&
+ (normalizedProject !== undefined || !queryIsAbsolute || isAbsolutePath(f))),
);
if (matches && obs.importance >= 4) {
history.observations.push({
diff --git a/src/hooks/_relative-paths.ts b/src/hooks/_relative-paths.ts
index 5a510832ca..7dcbd8d3f3 100644
--- a/src/hooks/_relative-paths.ts
+++ b/src/hooks/_relative-paths.ts
@@ -1,42 +1,31 @@
import { execFileSync } from "node:child_process";
import { realpathSync } from "node:fs";
+import { relative } from "node:path";
+
+export interface PathAlias {
+ from: string;
+ to: string;
+}
export function relativePathsEnabled(): boolean {
return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true";
}
-// Every worktree of the repository that holds cwd, under each spelling a hook can see:
-// the path git recorded, its resolved form, and the path cwd was reached through when
-// that goes through a symlink. Longest first, so a worktree nested inside the main
-// checkout is stripped before the checkout itself.
-export function repositoryRoots(cwd: string): string[] {
- let listing: string;
- try {
- listing = execFileSync("git", ["worktree", "list", "--porcelain"], {
+function gitWorktreeListing(cwd: string): string[] {
+ const run = (args: string[]) =>
+ execFileSync("git", ["worktree", "list", "--porcelain", ...args], {
cwd,
stdio: ["ignore", "pipe", "ignore"],
timeout: 500,
}).toString();
+ try {
+ return run(["-z"]).split("\0");
+ } catch {}
+ try {
+ return run([]).split(/\r?\n/);
} catch {
return [];
}
- const recorded = listing
- .split(/\r?\n/)
- .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 logical = logicalRoot(cwd, [...roots]);
- if (logical) roots.add(logical);
- if (process.platform === "win32") {
- for (const root of [...roots]) roots.add(root.replace(/\//g, "\\"));
- }
- return [...roots].sort((a, b) => b.length - a.length);
}
function tryRealpath(path: string): string | undefined {
@@ -47,41 +36,75 @@ function tryRealpath(path: string): string | undefined {
}
}
-function logicalRoot(cwd: string, roots: string[]): string | undefined {
+function cwdAliases(cwd: string, roots: string[]): PathAlias[] {
const physical = tryRealpath(cwd);
- if (!physical || physical === cwd) return undefined;
+ if (!physical || physical === cwd) return [];
for (const root of roots) {
- if (physical === root) return cwd;
- if (!physical.startsWith(`${root}/`)) continue;
+ if (physical !== root && !physical.startsWith(`${root}/`)) continue;
const inside = physical.slice(root.length);
- if (cwd.endsWith(inside)) return cwd.slice(0, cwd.length - inside.length);
+ if (inside && cwd.endsWith(inside)) {
+ return [{ from: cwd.slice(0, cwd.length - inside.length), to: "" }];
+ }
+ return [{ from: cwd, to: relative(root, physical) }];
}
- return undefined;
+ return [];
+}
+
+// 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 aliases = [...roots].map((from) => ({ from, to: "" }));
+ aliases.push(...cwdAliases(cwd, [...roots]));
+ 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, "\\$&");
}
-// A root counts only where a path starts (not inside a longer path) and only where it
-// ends (not as the prefix of a sibling such as `repo-old`). `root/x` becomes `x`, the
-// bare root becomes `.`.
-function rootPattern(roots: readonly string[]): RegExp | null {
- if (roots.length === 0) return null;
- const alternatives = roots.map(escapeRegExp).join("|");
+const PATH_END = `$|[\\s"'\`:;,)\\]}>]`;
+const PATH_REST = `[^\\s"'\`:;,)\\]}>]*`;
+
+// A root counts only where a path starts and ends, so `/mnt/repo/x` and `repo-old/` are left alone.
+// Windows paths compare case-insensitively and come out with forward slashes, like the file index.
+function aliasPattern(aliases: readonly PathAlias[], windows: boolean): RegExp | null {
+ if (aliases.length === 0) return null;
+ const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|");
+ const rest = windows ? PATH_REST : "";
return new RegExp(
- `(?]))`,
- "g",
+ `(? {
+ const to = aliases[groups.findIndex((group) => typeof group === "string")]?.to ?? "";
+ const separator = groups[aliases.length];
+ if (typeof separator !== "string") return to || ".";
+ const tail = String(groups[aliases.length + 1] ?? "").replace(/\\/g, "/");
+ return to ? `${to}/${tail}` : tail;
+ };
const walk = (node: unknown): unknown => {
- if (typeof node === "string") {
- return node.replace(pattern, (match) => (/[\\/]$/.test(match) ? "" : "."));
- }
+ if (typeof node === "string") return node.replace(pattern, rewrite);
if (Array.isArray(node)) return node.map(walk);
if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) {
return Object.fromEntries(Object.entries(node).map(([key, child]) => [key, walk(child)]));
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..e190c3a14e 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: "Project to search; required to match repository-relative paths",
+ },
},
required: ["files"],
},
diff --git a/test/file-context-relative-paths.test.ts b/test/file-context-relative-paths.test.ts
new file mode 100644
index 0000000000..01c18029e6
--- /dev/null
+++ b/test/file-context-relative-paths.test.ts
@@ -0,0 +1,78 @@
+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(),
+}));
+
+async function seed(kv: ReturnType, sessionId: string, project: string, file: string) {
+ const startedAt = new Date().toISOString();
+ await kv.set(KV.sessions, sessionId, { id: sessionId, project, cwd: `/repos/${project}`, startedAt, status: "completed", observationCount: 1 });
+ await kv.set(KV.observations(sessionId), `obs_${sessionId}`, {
+ id: `obs_${sessionId}`,
+ sessionId,
+ timestamp: startedAt,
+ type: "file_edit",
+ title: `edited ${file} in ${project}`,
+ narrative: "",
+ facts: [],
+ concepts: [],
+ files: [file],
+ importance: 6,
+ });
+}
+
+describe("mem::file-context with repository-relative paths", () => {
+ let sdk: ReturnType;
+ let kv: ReturnType;
+
+ const lookup = async (payload: Record) => {
+ const { context } = (await sdk.trigger("mem::file-context", payload)) as { context: string };
+ return ["repo-a", "repo-b", "repo-c"].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");
+ });
+
+ it("does not match relative entries to an absolute query without a project", async () => {
+ expect(await lookup({ files: ["/repos/repo-c/src/a.ts"] })).toEqual(["repo-c"]);
+ });
+
+ it("matches relative entries of the scoped project only", async () => {
+ expect(await lookup({ files: ["/repos/repo-a/src/a.ts"], project: "repo-a" })).toEqual(["repo-a"]);
+ });
+
+ it("still matches a relative query against relative entries", async () => {
+ expect(await lookup({ files: ["src/a.ts"], project: "repo-b" })).toEqual(["repo-b"]);
+ });
+});
+
+describe("mem::enrich", () => {
+ it("passes its project to mem::file-context", async () => {
+ const sdk = mockSdk({ looseTrigger: true });
+ const kv = mockKV();
+ registerEnrichFunction(sdk as never, kv as never);
+ const fileContext = vi.fn(async () => ({ context: "" }));
+ sdk.registerFunction("mem::file-context", fileContext);
+ sdk.registerFunction("mem::search", async () => ({ results: [] }));
+ await sdk.trigger("mem::enrich", { sessionId: "ses_now", files: ["/repos/repo-a/src/a.ts"], project: "repo-a" });
+ expect(fileContext).toHaveBeenCalledWith(expect.objectContaining({ project: "repo-a" }));
+ });
+});
diff --git a/test/hook-relative-paths.test.ts b/test/hook-relative-paths.test.ts
index 2d44a436ca..8c93499c8d 100644
--- a/test/hook-relative-paths.test.ts
+++ b/test/hook-relative-paths.test.ts
@@ -6,7 +6,10 @@ import { dirname, join } from "node:path";
import { relativizePaths, repositoryRoots } from "../src/hooks/_relative-paths.js";
describe("relativizePaths", () => {
- const roots = ["/work/app/.claude/worktrees/fix", "/work/app"];
+ 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)).toEqual({ file_path: "src/a.ts" });
@@ -34,6 +37,21 @@ describe("relativizePaths", () => {
).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)).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, true)).toBe("src/a.ts");
+ expect(relativizePaths("type C:\\work\\app\\x.ts", aliases, true)).toBe("type x.ts");
+ });
+
+ it("keeps a POSIX path's case and backslashes", () => {
+ expect(relativizePaths("/work/app/my\\ file.ts /Work/App/x", roots, false)).toBe("my\\ file.ts /Work/App/x");
+ });
+
it("returns the value untouched when there are no roots", () => {
const value = { file_path: "/work/app/src/a.ts" };
expect(relativizePaths(value, [])).toBe(value);
@@ -45,6 +63,9 @@ describe("repositoryRoots", () => {
let repoDir: string;
let worktreeDir: string;
let linkDir: string;
+ let subLinkDir: 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-")));
@@ -58,6 +79,11 @@ describe("repositoryRoots", () => {
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);
+ newlineWorktreeDir = join(tmpRoot, "odd\nname");
+ git("worktree", "add", "--quiet", "-b", "odd", newlineWorktreeDir);
});
afterAll(() => {
@@ -65,15 +91,23 @@ describe("repositoryRoots", () => {
});
it("lists every worktree, longest first, from inside the main checkout", () => {
- expect(repositoryRoots(repoDir)).toEqual([worktreeDir, repoDir]);
+ expect(froms(repoDir)).toEqual([worktreeDir, repoDir]);
});
it("lists the same roots from inside a worktree", () => {
- expect(repositoryRoots(join(worktreeDir))).toEqual([worktreeDir, repoDir]);
+ expect(froms(worktreeDir)).toEqual([worktreeDir, repoDir]);
});
it("adds the symlinked spelling cwd was reached through", () => {
- expect(repositoryRoots(linkDir)).toContain(linkDir);
+ 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("reads a worktree path that contains a newline", () => {
+ expect(repositoryRoots(repoDir)).toContainEqual({ from: newlineWorktreeDir, to: "" });
});
it("returns nothing outside a repository", () => {
@@ -110,7 +144,7 @@ describe("captureObservation with AGENTMEMORY_RELATIVE_PATHS", () => {
});
async function sentBody(flag: string | undefined): Promise> {
- if (flag !== undefined) vi.stubEnv("AGENTMEMORY_RELATIVE_PATHS", flag);
+ 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);
From f39ff4dea2af4a405716cd5dd0695e85b3af6a1b Mon Sep 17 00:00:00 2001
From: Spike Jourdain
Date: Tue, 27 Oct 2026 10:13:49 +1100
Subject: [PATCH 3/7] fix(hooks): address second review on repository-relative
paths
- Windows: a path through directories with spaces is normalized in full;
a space continues the path only while another separator follows.
- pre-tool-use: with AGENTMEMORY_RELATIVE_PATHS on and no project in the
hook payload (Claude Code sends none), scope enrichment to the
repository's project so relative history can match.
- file-context: compare with forward slashes on both sides, so a Windows
query matches a relative entry and a stored backslash entry matches.
- A cwd symlinked into a nested worktree maps onto that worktree (roots
are tried longest first), and a Windows realpath with backslashes is
recognised inside its root.
- docs:sync: the test count passed 4,100.
Co-Authored-By: Claude Opus 5.5
Signed-off-by: Spike Jourdain
---
AGENTS.md | 4 +-
README.md | 4 +-
READMEs/README.ar-SA.md | 4 +-
READMEs/README.bn-BD.md | 4 +-
READMEs/README.cs-CZ.md | 4 +-
READMEs/README.da-DK.md | 4 +-
READMEs/README.de-DE.md | 4 +-
READMEs/README.el-GR.md | 4 +-
READMEs/README.es-ES.md | 4 +-
READMEs/README.fi-FI.md | 4 +-
READMEs/README.fr-FR.md | 4 +-
READMEs/README.he-IL.md | 4 +-
READMEs/README.hi-IN.md | 4 +-
READMEs/README.hu-HU.md | 4 +-
READMEs/README.id-ID.md | 4 +-
READMEs/README.it-IT.md | 4 +-
READMEs/README.ja-JP.md | 4 +-
READMEs/README.ko-KR.md | 4 +-
READMEs/README.nb-NO.md | 4 +-
READMEs/README.nl-NL.md | 4 +-
READMEs/README.pl-PL.md | 4 +-
READMEs/README.pt-BR.md | 4 +-
READMEs/README.pt-PT.md | 4 +-
READMEs/README.ro-RO.md | 4 +-
READMEs/README.ru-RU.md | 4 +-
READMEs/README.sv-SE.md | 4 +-
READMEs/README.th-TH.md | 4 +-
READMEs/README.tl-PH.md | 4 +-
READMEs/README.tr-TR.md | 4 +-
READMEs/README.uk-UA.md | 4 +-
READMEs/README.ur-PK.md | 4 +-
READMEs/README.vi-VN.md | 4 +-
READMEs/README.zh-CN.md | 4 +-
READMEs/README.zh-TW.md | 4 +-
assets/tags/light/stat-tests.svg | 4 +-
assets/tags/stat-tests.svg | 4 +-
plugin/scripts/_capture.mjs | 35 ++++++------
plugin/scripts/pre-tool-use.mjs | 51 ++++++++++++++++-
scripts/docs-sync.state.json | 2 +-
src/functions/file-index.ts | 18 ++++--
src/hooks/_relative-paths.ts | 32 ++++++-----
src/hooks/pre-tool-use.ts | 6 +-
test/file-context-relative-paths.test.ts | 12 +++-
test/hook-relative-paths.test.ts | 71 +++++++++++++++++++++++-
44 files changed, 257 insertions(+), 114 deletions(-)
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..84bb095022 100644
--- a/README.md
+++ b/README.md
@@ -71,7 +71,7 @@
-
+
@@ -1485,7 +1485,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 @@
-