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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 MCP টুল 12 অটো হুক 0 এক্সটার্নাল ডিবি - 4,000+ টেস্ট পাস + 4,100+ টেস্ট পাস

@@ -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 @@ 54 MCP nástrojů 12 automatických hooks 0 externích databází - 4,000+ testů úspěšně proběhlo + 4,100+ testů úspěšně proběhlo

@@ -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 @@ 54 MCP-værktøjer 12 automatiske hooks 0 eksterne databaser - 4,000+ beståede tests + 4,100+ beståede tests

@@ -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 @@ 54 MCP-Tools 12 Auto-Hooks 0 externe DBs - 4,000+ bestandene Tests + 4,100+ bestandene Tests

@@ -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 @@ 54 εργαλεία MCP 12 αυτόματα hooks 0 εξωτερικές βάσεις δεδομένων - 4,000+ επιτυχημένες δοκιμές + 4,100+ επιτυχημένες δοκιμές

@@ -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 @@ 54 tools MCP 12 hooks automáticos 0 bases de datos externas - 4,000+ tests superados + 4,100+ tests superados

@@ -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 @@ 54 MCP-työkalua 12 automaattista hookia 0 ulkoista tietokantaa - 4,000+ testiä läpäisty + 4,100+ testiä läpäisty

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 כלי MCP 12 hooks אוטומטיים 0 מסדי נתונים חיצוניים - 4,000+ בדיקות עוברות + 4,100+ בדיקות עוברות

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 MCP eszköz 12 automatikus hook 0 külső adatbázis - 4,000+ sikeres teszt + 4,100+ sikeres teszt

@@ -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 @@ 54 tool MCP 12 hook otomatis 0 DB eksternal - 4,000+ pengujian lolos + 4,100+ pengujian lolos

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 MCP ツール 12 自動 hooks 外部 DB 0 個 - 4,000+ 件のテストが成功 + 4,100+ 件のテストが成功

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 narzędzia MCP 12 automatycznych hooków 0 zewnętrznych baz danych - 4,000+ zaliczonych testów + 4,100+ zaliczonych testów

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 ferramentas MCP 12 hooks automáticos 0 bases de dados externas - 4,000+ testes aprovados + 4,100+ testes aprovados

@@ -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 @@ 54 de instrumente MCP 12 hook-uri automate 0 baze de date externe - 4,000+ teste trecute + 4,100+ teste trecute

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 MCP-verktyg 12 automatiska hooks 0 externa databaser - 4,000+ godkända tester + 4,100+ godkända tester

@@ -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 @@ 54 เครื่องมือ MCP 12 hook อัตโนมัติ ไม่ต้องพึ่ง external DB เลย - ผ่านการทดสอบ 4,000+ รายการ + ผ่านการทดสอบ 4,100+ รายการ

@@ -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 @@ 54 MCP tool 12 awtomatikong hook 0 panlabas na DB - 4,000+ pumapasang test + 4,100+ pumapasang test

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 інструменти MCP 12 автоматичних хуків 0 зовнішніх БД - 4,000+ тестів пройдено + 4,100+ тестів пройдено

@@ -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 @@ 54 MCP ٹولز 12 خودکار ہکس 0 خارجی ڈیٹابیسز - 4,000+ ٹیسٹس پاس ہو رہے ہیں + 4,100+ ٹیسٹس پاس ہو رہے ہیں

@@ -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 @@ 54 MCP tools 12 auto hooks 0 external DBs - 4,000+ tests passing + 4,100+ tests passing

@@ -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 @@ 54 个 MCP 工具 12 个自动 hooks 0 个外部数据库 - 4,000+ 项测试通过 + 4,100+ 项测试通过

@@ -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 @@ 54 個 MCP 工具 12 個自動 hooks 0 個外部資料庫 - 4,000+ 測試通過 + 4,100+ 測試通過

@@ -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 7b456619fa..37787db86f 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -863,22 +863,23 @@ function tryRealpath(path) { return; } } +function isInsideRoot(root, path) { + return path === root || path.startsWith(`${root}/`) || path.startsWith(`${root}\\`); +} function cwdAliases(cwd, roots) { const physical = tryRealpath(cwd); if (!physical || physical === cwd) return []; - for (const root of roots) { - if (physical !== root && !physical.startsWith(`${root}/`)) continue; - const inside = physical.slice(root.length); - if (inside && cwd.endsWith(inside)) return [{ - from: cwd.slice(0, cwd.length - inside.length), - to: "" - }]; - return [{ - from: cwd, - to: relative(root, physical) - }]; - } - return []; + const root = roots.find((candidate) => isInsideRoot(candidate, physical)); + if (root === void 0) return []; + const inside = physical.slice(root.length); + if (inside && cwd.endsWith(inside)) return [{ + from: cwd.slice(0, cwd.length - inside.length), + 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); @@ -888,11 +889,12 @@ function repositoryRoots(cwd) { const physical = tryRealpath(root); if (physical) roots.add(physical); } - const aliases = [...roots].map((from) => ({ + const longestFirst = [...roots].sort((a, b) => b.length - a.length); + const aliases = longestFirst.map((from) => ({ from, to: "" })); - aliases.push(...cwdAliases(cwd, [...roots])); + aliases.push(...cwdAliases(cwd, longestFirst)); if (process.platform === "win32") for (const alias of [...aliases]) aliases.push({ ...alias, from: alias.from.replace(/\//g, "\\") @@ -903,7 +905,8 @@ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } const PATH_END = `$|[\\s"'\`:;,)\\]}>]`; -const PATH_REST = `[^\\s"'\`:;,)\\]}>]*`; +const NAME = `[^\\\\/\\s"'\`:;,)\\]}>]+`; +const PATH_REST = `(?:${NAME}(?: ${NAME})*[\\\\/])*(?:${NAME})?`; function aliasPattern(aliases, windows) { if (aliases.length === 0) return null; const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 2761d007a2..5f64c09a57 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 } from "node:fs"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { basename, dirname, join, resolve } from "node:path"; +import { execSync } from "node:child_process"; //#region src/secret-store.ts const SECRET_KEY = "AGENTMEMORY_SECRET"; function agentmemoryHomeDir() { @@ -89,6 +90,50 @@ function canonicalSecretPath() { return join(homedir(), ".agentmemory", "secret"); } //#endregion +//#region src/hooks/_project.ts +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 relativePathsEnabled() { + return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true"; +} +const NAME = `[^\\\\/\\s"'\`:;,)\\]}>]+`; +`${NAME}${NAME}${NAME}`; +//#endregion //#region src/hooks/pre-tool-use.ts function isSdkChildContext(payload) { if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; @@ -148,7 +193,7 @@ 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 project = typeof data.project === "string" && data.project.trim().length > 0 ? data.project.trim() : relativePathsEnabled() ? resolveProject(hookCwd(data) || process.cwd()) : void 0; try { const res = await fetch(`${REST_URL}/agentmemory/enrich`, { method: "POST", diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json index 377ea77be8..bf7cab5337 100644 --- a/scripts/docs-sync.state.json +++ b/scripts/docs-sync.state.json @@ -20,7 +20,7 @@ "12" ], "tests": [ - "4000+" + "4100+" ], "functions": [ "322" diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts index e237f61552..59741d22c1 100644 --- a/src/functions/file-index.ts +++ b/src/functions/file-index.ts @@ -21,6 +21,10 @@ 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 forwardSlashes(path: string): string { + return path.replace(/\\/g, "/"); +} + function isAbsolutePath(path: string): boolean { return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path); } @@ -74,7 +78,7 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void { for (const file of files) { const history: FileHistory = { file, observations: [] }; - const normalizedFile = file.replace(/^\.\//, ""); + const normalizedFile = forwardSlashes(file).replace(/^\.\//, ""); const queryIsAbsolute = isAbsolutePath(file); for (const session of otherSessions) { @@ -82,14 +86,16 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void { for (const obs of observations) { if (!obs.files || !obs.title) continue; - const matches = obs.files.some( - (f) => - f === file || + const matches = obs.files.some((stored) => { + const f = forwardSlashes(stored); + return ( + stored === file || f === normalizedFile || f.endsWith(`/${normalizedFile}`) || (normalizedFile.endsWith(`/${f}`) && - (normalizedProject !== undefined || !queryIsAbsolute || isAbsolutePath(f))), - ); + (normalizedProject !== undefined || !queryIsAbsolute || isAbsolutePath(f))) + ); + }); if (matches && obs.importance >= 4) { history.observations.push({ sessionId: session.id, diff --git a/src/hooks/_relative-paths.ts b/src/hooks/_relative-paths.ts index 7dcbd8d3f3..b8ec3b97cb 100644 --- a/src/hooks/_relative-paths.ts +++ b/src/hooks/_relative-paths.ts @@ -36,18 +36,21 @@ function tryRealpath(path: string): string | undefined { } } -function cwdAliases(cwd: string, roots: string[]): PathAlias[] { +function isInsideRoot(root: string, path: string): boolean { + return path === root || path.startsWith(`${root}/`) || path.startsWith(`${root}\\`); +} + +// `roots` must be longest first, so a cwd inside a nested worktree maps onto that worktree. +function cwdAliases(cwd: string, roots: readonly string[]): PathAlias[] { const physical = tryRealpath(cwd); if (!physical || physical === cwd) return []; - for (const root of roots) { - if (physical !== root && !physical.startsWith(`${root}/`)) continue; - const inside = physical.slice(root.length); - if (inside && cwd.endsWith(inside)) { - return [{ from: cwd.slice(0, cwd.length - inside.length), to: "" }]; - } - return [{ from: cwd, to: relative(root, physical) }]; + const root = roots.find((candidate) => isInsideRoot(candidate, physical)); + if (root === undefined) return []; + const inside = physical.slice(root.length); + if (inside && cwd.endsWith(inside)) { + return [{ from: cwd.slice(0, cwd.length - inside.length), to: "" }]; } - return []; + return [{ from: cwd, to: relative(root, physical).replace(/\\/g, "/") }]; } // Longest first: a worktree nested inside the main checkout must be stripped before it. @@ -62,8 +65,9 @@ export function repositoryRoots(cwd: string): PathAlias[] { const physical = tryRealpath(root); if (physical) roots.add(physical); } - const aliases = [...roots].map((from) => ({ from, to: "" })); - aliases.push(...cwdAliases(cwd, [...roots])); + 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, "\\") }); } @@ -75,10 +79,12 @@ function escapeRegExp(text: string): string { } const PATH_END = `$|[\\s"'\`:;,)\\]}>]`; -const PATH_REST = `[^\\s"'\`:;,)\\]}>]*`; +const NAME = `[^\\\\/\\s"'\`:;,)\\]}>]+`; +const PATH_REST = `(?:${NAME}(?: ${NAME})*[\\\\/])*(?:${NAME})?`; // 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. +// Windows paths compare case-insensitively and come out with forward slashes, like the file index; +// a space continues a Windows path only while another separator follows. function aliasPattern(aliases: readonly PathAlias[], windows: boolean): RegExp | null { if (aliases.length === 0) return null; const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts index 51024e86d7..204edb103a 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, resolveProject } from "./_project.js"; +import { relativePathsEnabled } from "./_relative-paths.js"; function isSdkChildContext(payload: unknown): boolean { if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; @@ -84,7 +86,9 @@ async function main() { const project = typeof data.project === "string" && data.project.trim().length > 0 ? data.project.trim() - : undefined; + : relativePathsEnabled() + ? resolveProject(hookCwd(data) || process.cwd()) + : undefined; try { const res = await fetch(`${REST_URL}/agentmemory/enrich`, { diff --git a/test/file-context-relative-paths.test.ts b/test/file-context-relative-paths.test.ts index 01c18029e6..34c992c37b 100644 --- a/test/file-context-relative-paths.test.ts +++ b/test/file-context-relative-paths.test.ts @@ -39,8 +39,9 @@ describe("mem::file-context with repository-relative paths", () => { 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}`)); + return ["repo-a", "repo-b", "repo-c", "repo-w"].filter((project) => context.includes(`in ${project}`)); }; + const lookupFor = (files: string[], project: string) => lookup({ files, project }); beforeEach(async () => { sdk = mockSdk({ looseTrigger: true }); @@ -59,6 +60,15 @@ describe("mem::file-context with repository-relative paths", () => { expect(await lookup({ files: ["/repos/repo-a/src/a.ts"], project: "repo-a" })).toEqual(["repo-a"]); }); + it("matches a Windows query against a forward-slash entry", async () => { + expect(await lookup({ files: ["C:\\repos\\repo-a\\src\\a.ts"], project: "repo-a" })).toEqual(["repo-a"]); + }); + + it("matches a stored Windows entry against a forward-slash query", async () => { + await seed(kv, "ses_win", "repo-w", "src\\w.ts"); + expect(await lookupFor(["src/w.ts"], "repo-w")).toContain("repo-w"); + }); + it("still matches a relative query against relative entries", async () => { expect(await lookup({ files: ["src/a.ts"], project: "repo-b" })).toEqual(["repo-b"]); }); diff --git a/test/hook-relative-paths.test.ts b/test/hook-relative-paths.test.ts index 8c93499c8d..b1413d62de 100644 --- a/test/hook-relative-paths.test.ts +++ b/test/hook-relative-paths.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; +import { createServer } from "node:http"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -48,6 +49,12 @@ describe("relativizePaths", () => { expect(relativizePaths("type C:\\work\\app\\x.ts", aliases, true)).toBe("type x.ts"); }); + it("follows a Windows path through directories with spaces, and stops at the next path", () => { + const aliases = [{ from: "C:\\work\\app", to: "" }]; + expect(relativizePaths("C:\\work\\app\\my dir\\sub\\a.ts", aliases, true)).toBe("my dir/sub/a.ts"); + expect(relativizePaths("C:\\work\\app\\a.ts C:\\work\\app\\b.ts", aliases, true)).toBe("a.ts b.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"); }); @@ -64,6 +71,7 @@ describe("repositoryRoots", () => { let worktreeDir: string; let linkDir: string; let subLinkDir: string; + let worktreeSrcLinkDir: string; let newlineWorktreeDir: string; const froms = (cwd: string) => repositoryRoots(cwd).map((alias) => alias.from).filter((from) => from !== newlineWorktreeDir); @@ -82,6 +90,9 @@ describe("repositoryRoots", () => { 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); newlineWorktreeDir = join(tmpRoot, "odd\nname"); git("worktree", "add", "--quiet", "-b", "odd", newlineWorktreeDir); }); @@ -106,6 +117,10 @@ describe("repositoryRoots", () => { expect(repositoryRoots(subLinkDir)).toContainEqual({ from: subLinkDir, to: join("packages", "sub") }); }); + 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: "" }); }); @@ -175,3 +190,57 @@ describe("captureObservation with AGENTMEMORY_RELATIVE_PATHS", () => { 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 enrichProject(relative: string): Promise { + 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]?.["project"]; + } + + it("scopes enrichment to the repository's project when the hook payload has none", async () => { + expect(await enrichProject("true")).toBe("repo"); + }); + + it("leaves enrichment unscoped by default", async () => { + expect(await enrichProject("")).toBeUndefined(); + }); +}); From 0581b06225ef6b76ab24760cb8ce75ac3ff7de07 Mon Sep 17 00:00:00 2001 From: Spike Jourdain Date: Tue, 27 Oct 2026 10:35:45 +1100 Subject: [PATCH 4/7] fix(hooks): address third review on repository-relative paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Windows: a path field (file_path, path, …) is one path, so it is converted to forward slashes in full, spaces and punctuation included. Free text cannot say where a path ends, so it is converted only up to the next space and later paths in the sentence are left as written. - A symlinked cwd aliases its parent to the root only when that parent resolves to the root; otherwise only the cwd itself is aliased. - file-context: a UNC query is absolute, and a blank project counts as no project for matching as well as filtering. - relativePathsEnabled moves to _project.ts, so pre-tool-use no longer bundles the path matcher. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Spike Jourdain --- plugin/scripts/_capture.mjs | 31 +++++++++++++++++------- plugin/scripts/pre-tool-use.mjs | 10 +++----- src/functions/file-index.ts | 5 ++-- src/hooks/_capture.ts | 3 ++- src/hooks/_project.ts | 4 +++ src/hooks/_relative-paths.ts | 31 ++++++++++++------------ src/hooks/pre-tool-use.ts | 3 +-- test/file-context-relative-paths.test.ts | 8 ++++++ test/hook-relative-paths.test.ts | 29 +++++++++++++++++++--- 9 files changed, 85 insertions(+), 39 deletions(-) diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index 37787db86f..8795ab1713 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -828,10 +828,12 @@ async function drainSpool(url, send, options = {}) { } } //#endregion -//#region src/hooks/_relative-paths.ts +//#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", @@ -872,8 +874,9 @@ function cwdAliases(cwd, roots) { const root = roots.find((candidate) => isInsideRoot(candidate, physical)); if (root === void 0) return []; const inside = physical.slice(root.length); - if (inside && cwd.endsWith(inside)) return [{ - from: cwd.slice(0, cwd.length - inside.length), + const prefix = inside && cwd.endsWith(inside) ? cwd.slice(0, cwd.length - inside.length) : void 0; + if (prefix && tryRealpath(prefix) === root) return [{ + from: prefix, to: "" }]; return [{ @@ -905,8 +908,15 @@ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } const PATH_END = `$|[\\s"'\`:;,)\\]}>]`; -const NAME = `[^\\\\/\\s"'\`:;,)\\]}>]+`; -const PATH_REST = `(?:${NAME}(?: ${NAME})*[\\\\/])*(?:${NAME})?`; +const PATH_REST = `[^\\s"'\`]*`; +const PATH_KEYS = new Set([ + "file_path", + "filePath", + "filepath", + "notebook_path", + "path", + "file" +]); function aliasPattern(aliases, windows) { if (aliases.length === 0) return null; const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); @@ -921,10 +931,13 @@ function relativizePaths(value, aliases, windows = process.platform === "win32") 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, 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)])); + 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)); + if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) return Object.fromEntries(Object.entries(node).map(([k, child]) => [k, walk(child, k)])); return node; }; return walk(value); diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 5f64c09a57..5cb0c01984 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -91,6 +91,9 @@ function canonicalSecretPath() { } //#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(); @@ -127,13 +130,6 @@ function hookCwd(data) { if (projectDir && projectDir.trim()) return projectDir; } //#endregion -//#region src/hooks/_relative-paths.ts -function relativePathsEnabled() { - return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true"; -} -const NAME = `[^\\\\/\\s"'\`:;,)\\]}>]+`; -`${NAME}${NAME}${NAME}`; -//#endregion //#region src/hooks/pre-tool-use.ts function isSdkChildContext(payload) { if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts index 59741d22c1..68c24678d4 100644 --- a/src/functions/file-index.ts +++ b/src/functions/file-index.ts @@ -26,7 +26,8 @@ function forwardSlashes(path: string): string { } function isAbsolutePath(path: string): boolean { - return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path); + const slashed = forwardSlashes(path); + return slashed.startsWith("/") || /^[A-Za-z]:\//.test(slashed); } export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void { @@ -37,7 +38,7 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void { const sessionId = data && typeof data.sessionId === "string" ? data.sessionId.trim() : ""; const normalizedProject = - typeof data?.project === "string" ? data.project.trim() : undefined; + typeof data?.project === "string" && data.project.trim() ? data.project.trim() : undefined; const files = Array.isArray(data?.files) ? data!.files .map((file) => (typeof file === "string" ? file.trim() : "")) diff --git a/src/hooks/_capture.ts b/src/hooks/_capture.ts index 72f0c93ca8..ba43053a28 100644 --- a/src/hooks/_capture.ts +++ b/src/hooks/_capture.ts @@ -13,7 +13,8 @@ import { type SentMark, type SpoolRecord, } from "../capture/spool.js"; -import { relativePathsEnabled, relativizePaths, repositoryRoots } from "./_relative-paths.js"; +import { relativePathsEnabled } from "./_project.js"; +import { relativizePaths, repositoryRoots } from "./_relative-paths.js"; export { stripPrivateData } from "../functions/privacy.js"; 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 index b8ec3b97cb..9586e73de8 100644 --- a/src/hooks/_relative-paths.ts +++ b/src/hooks/_relative-paths.ts @@ -7,10 +7,6 @@ export interface PathAlias { to: string; } -export function relativePathsEnabled(): boolean { - return process.env["AGENTMEMORY_RELATIVE_PATHS"]?.trim().toLowerCase() === "true"; -} - function gitWorktreeListing(cwd: string): string[] { const run = (args: string[]) => execFileSync("git", ["worktree", "list", "--porcelain", ...args], { @@ -47,9 +43,8 @@ function cwdAliases(cwd: string, roots: readonly string[]): PathAlias[] { const root = roots.find((candidate) => isInsideRoot(candidate, physical)); if (root === undefined) return []; const inside = physical.slice(root.length); - if (inside && cwd.endsWith(inside)) { - return [{ from: cwd.slice(0, cwd.length - inside.length), to: "" }]; - } + const prefix = inside && cwd.endsWith(inside) ? cwd.slice(0, cwd.length - inside.length) : undefined; + if (prefix && tryRealpath(prefix) === root) return [{ from: prefix, to: "" }]; return [{ from: cwd, to: relative(root, physical).replace(/\\/g, "/") }]; } @@ -79,12 +74,13 @@ function escapeRegExp(text: string): string { } const PATH_END = `$|[\\s"'\`:;,)\\]}>]`; -const NAME = `[^\\\\/\\s"'\`:;,)\\]}>]+`; -const PATH_REST = `(?:${NAME}(?: ${NAME})*[\\\\/])*(?:${NAME})?`; +const PATH_REST = `[^\\s"'\`]*`; +const PATH_KEYS = new Set(["file_path", "filePath", "filepath", "notebook_path", "path", "file"]); // 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; -// a space continues a Windows path only while another separator follows. +// Windows paths compare case-insensitively and come out with forward slashes, like the file index. +// Free text cannot say where a path ends, so it is converted only up to the next space; a path +// field is one path, so it is converted in full. function aliasPattern(aliases: readonly PathAlias[], windows: boolean): RegExp | null { if (aliases.length === 0) return null; const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); @@ -109,11 +105,16 @@ export function relativizePaths( 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, rewrite); - if (Array.isArray(node)) return node.map(walk); + 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)); if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) { - return Object.fromEntries(Object.entries(node).map(([key, child]) => [key, walk(child)])); + return Object.fromEntries(Object.entries(node).map(([k, child]) => [k, walk(child, k)])); } return node; }; diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts index 204edb103a..dbcd610bf6 100644 --- a/src/hooks/pre-tool-use.ts +++ b/src/hooks/pre-tool-use.ts @@ -1,7 +1,6 @@ #!/usr/bin/env node import { resolveClientSecret } from "../secret-store.js"; -import { hookCwd, resolveProject } from "./_project.js"; -import { relativePathsEnabled } from "./_relative-paths.js"; +import { hookCwd, relativePathsEnabled, resolveProject } from "./_project.js"; function isSdkChildContext(payload: unknown): boolean { if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; diff --git a/test/file-context-relative-paths.test.ts b/test/file-context-relative-paths.test.ts index 34c992c37b..f4b8f3d988 100644 --- a/test/file-context-relative-paths.test.ts +++ b/test/file-context-relative-paths.test.ts @@ -56,6 +56,14 @@ describe("mem::file-context with repository-relative paths", () => { expect(await lookup({ files: ["/repos/repo-c/src/a.ts"] })).toEqual(["repo-c"]); }); + it("treats a UNC query as absolute", async () => { + expect(await lookup({ files: ["\\\\server\\share\\repo-c\\src\\a.ts"] })).toEqual([]); + }); + + it("treats a blank project as no project", async () => { + expect(await lookup({ files: ["/repos/repo-c/src/a.ts"], project: " " })).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"]); }); diff --git a/test/hook-relative-paths.test.ts b/test/hook-relative-paths.test.ts index b1413d62de..e72545524f 100644 --- a/test/hook-relative-paths.test.ts +++ b/test/hook-relative-paths.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest"; import { execFileSync, spawn } from "node:child_process"; import { createServer } from "node:http"; -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, 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"; @@ -49,10 +49,18 @@ describe("relativizePaths", () => { expect(relativizePaths("type C:\\work\\app\\x.ts", aliases, true)).toBe("type x.ts"); }); - it("follows a Windows path through directories with spaces, and stops at the next path", () => { + it("converts a Windows path field in full, spaces and punctuation included", () => { const aliases = [{ from: "C:\\work\\app", to: "" }]; - expect(relativizePaths("C:\\work\\app\\my dir\\sub\\a.ts", aliases, true)).toBe("my dir/sub/a.ts"); + expect(relativizePaths({ file_path: "C:\\work\\app\\my dir\\lib(test)\\a.ts" }, aliases, true)).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, true)).toBe("a.ts and docs\\guide.md"); expect(relativizePaths("C:\\work\\app\\a.ts C:\\work\\app\\b.ts", aliases, true)).toBe("a.ts b.ts"); + expect(relativizePaths("see C:\\work\\app\\src\\lib(test)\\x.ts", aliases, true)).toBe("see src/lib(test)/x.ts"); }); it("keeps a POSIX path's case and backslashes", () => { @@ -72,6 +80,7 @@ describe("repositoryRoots", () => { 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); @@ -93,6 +102,9 @@ describe("repositoryRoots", () => { 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); }); @@ -117,6 +129,12 @@ describe("repositoryRoots", () => { 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" }); }); @@ -243,4 +261,9 @@ describe("pre-tool-use with AGENTMEMORY_RELATIVE_PATHS", () => { it("leaves enrichment unscoped by default", async () => { expect(await enrichProject("")).toBeUndefined(); }); + + it("ships without the path matcher", () => { + const bundle = readFileSync(join(import.meta.dirname, "..", "plugin", "scripts", "pre-tool-use.mjs"), "utf8"); + expect(bundle).not.toMatch(/PATH_REST|PATH_END|function relativizePaths/); + }); }); From 0c534ba67ae5689160b32f8a160958c61605b53a Mon Sep 17 00:00:00 2001 From: Spike Jourdain Date: Tue, 27 Oct 2026 11:04:05 +1100 Subject: [PATCH 5/7] fix(hooks): make relative lookup opt-in end to end, and harden the matcher Reworks how relative paths are looked up, after the third review and a self-review found that the daemon-side change reached users who never set AGENTMEMORY_RELATIVE_PATHS. - file-context and enrich behave exactly as on main unless the request says `relativeFiles: true`. pre-tool-use sends that, with its query paths converted by the same matcher and the project from cwd. - In relative mode a relative entry must equal the query, so a root `package.json` no longer matches every `package.json` below it. An older absolute entry must be that file under its session's repository root. Bug memories match at path boundaries. Enrich scopes file history to its project only in this mode. - REST enrich and file-context pass on only the fields they know. - Matcher: trailing and doubled slashes, `host:` prefixes, `|` and `&`, Windows list separators, macOS case-insensitive roots with the native realpath, Windows separators in the cwd alias, a trailing slash on cwd, no scan of image_data, one git call outside a repository, and git run with LC_ALL=C so the old-git fallback works in any locale. - README section on setting it up and its limits. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Spike Jourdain --- README.md | 11 ++ plugin/scripts/_capture.mjs | 46 +++++--- plugin/scripts/pre-tool-use.mjs | 142 ++++++++++++++++++++++- src/functions/enrich.ts | 13 ++- src/functions/file-index.ts | 67 +++++++---- src/hooks/_relative-paths.ts | 72 ++++++++---- src/hooks/pre-tool-use.ts | 12 +- src/mcp/tools-registry.ts | 2 +- src/triggers/api.ts | 15 ++- test/file-context-relative-paths.test.ts | 126 +++++++++++++++----- test/hook-relative-paths.test.ts | 95 ++++++++++----- 11 files changed, 467 insertions(+), 134 deletions(-) diff --git a/README.md b/README.md index 84bb095022..687951ca7b 100644 --- a/README.md +++ b/README.md @@ -1326,6 +1326,17 @@ 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. + ### Ports The API and viewer bind to loopback by default. diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index 8795ab1713..579b923864 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -842,16 +842,23 @@ function gitWorktreeListing(cwd) { ...args ], { cwd, + env: { + ...process.env, + LC_ALL: "C" + }, stdio: [ "ignore", "pipe", - "ignore" + "pipe" ], timeout: 500 }).toString(); try { return run(["-z"]).split("\0"); - } catch {} + } catch (err) { + const stderr = String(err.stderr ?? ""); + if (!/unknown switch|usage:/i.test(stderr)) return []; + } try { return run([]).split(/\r?\n/); } catch { @@ -860,22 +867,27 @@ function gitWorktreeListing(cwd) { } function tryRealpath(path) { try { - return realpathSync(path); + return realpathSync.native(path); } catch { return; } } +function slashed(path) { + return path.replace(/\\/g, "/"); +} function isInsideRoot(root, path) { - return path === root || path.startsWith(`${root}/`) || path.startsWith(`${root}\\`); + return slashed(path) === slashed(root) || slashed(path).startsWith(`${slashed(root)}/`); } -function cwdAliases(cwd, roots) { +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 = physical.slice(root.length); - const prefix = inside && cwd.endsWith(inside) ? cwd.slice(0, cwd.length - inside.length) : void 0; - if (prefix && tryRealpath(prefix) === root) 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: "" }]; @@ -907,8 +919,8 @@ function repositoryRoots(cwd) { function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -const PATH_END = `$|[\\s"'\`:;,)\\]}>]`; -const PATH_REST = `[^\\s"'\`]*`; +const PATH_END = `$|[\\s"'\`:;,)\\]}>|&]`; +const WINDOWS_TAIL = `[^\\s"'\`,;|<>]*`; const PATH_KEYS = new Set([ "file_path", "filePath", @@ -917,14 +929,16 @@ const PATH_KEYS = new Set([ "path", "file" ]); -function aliasPattern(aliases, windows) { +const SKIPPED_KEYS = new Set(["image_data", "imageData"]); +function aliasPattern(aliases, platform) { 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 || "."; @@ -936,8 +950,8 @@ function relativizePaths(value, aliases, windows = process.platform === "win32") 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)); - if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) return Object.fromEntries(Object.entries(node).map(([k, child]) => [k, walk(child, k)])); + 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); diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 5cb0c01984..81fc67fb4d 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -1,8 +1,8 @@ #!/usr/bin/env node import { readFileSync, realpathSync } from "node:fs"; import { homedir } from "node:os"; -import { basename, dirname, join, resolve } from "node:path"; -import { execSync } from "node:child_process"; +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() { @@ -130,6 +130,133 @@ function hookCwd(data) { 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 aliasPattern(aliases, platform) { + 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, 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; @@ -189,17 +316,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() : relativePathsEnabled() ? resolveProject(hookCwd(data) || process.cwd()) : 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/src/functions/enrich.ts b/src/functions/enrich.ts index c022d0ee7e..06dd67f5f7 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 { pathsOverlap } 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,12 +27,15 @@ export function registerEnrichFunction(sdk: IIIClient, kv: StateKV): void { const parts: string[] = []; const fileContextPromise = sdk - .trigger<{ sessionId: string; files: string[]; project?: 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, - ...(project !== undefined && { project }), + ...(data.relativeFiles === true && { relativeFiles: true, ...(project !== undefined && { project }) }), }, }) .catch(() => ({ context: "" })); @@ -68,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 ? pathsOverlap(f, df) : f.includes(df) || df.includes(f), + ), ), ) .sort( diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts index 68c24678d4..22e2aaabd5 100644 --- a/src/functions/file-index.ts +++ b/src/functions/file-index.ts @@ -19,26 +19,52 @@ 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 forwardSlashes(path: string): string { - return path.replace(/\\/g, "/"); +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 = forwardSlashes(path); - return slashed.startsWith("/") || /^[A-Za-z]:\//.test(slashed); + const slashed = normalizePath(path); + return slashed.startsWith("/") || /^[a-z]:\//.test(slashed); +} + +// 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 (candidate.slice(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) && entry === `${sessionRoot(session.cwd, session.project)}/${query}`; +} + +export function pathsOverlap(a: string, b: string): boolean { + const left = normalizePath(a); + const right = normalizePath(b); + 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() : ""; const normalizedProject = - typeof data?.project === "string" && data.project.trim() ? data.project.trim() : undefined; + typeof data?.project === "string" ? data.project.trim() : undefined; const files = Array.isArray(data?.files) ? data!.files .map((file) => (typeof file === "string" ? file.trim() : "")) @@ -79,24 +105,25 @@ export function registerFileIndexFunction(sdk: IIIClient, kv: StateKV): void { for (const file of files) { const history: FileHistory = { file, observations: [] }; - const normalizedFile = forwardSlashes(file).replace(/^\.\//, ""); - const queryIsAbsolute = isAbsolutePath(file); + 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((stored) => { - const f = forwardSlashes(stored); - return ( - stored === file || - f === normalizedFile || - f.endsWith(`/${normalizedFile}`) || - (normalizedFile.endsWith(`/${f}`) && - (normalizedProject !== undefined || !queryIsAbsolute || isAbsolutePath(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({ sessionId: session.id, diff --git a/src/hooks/_relative-paths.ts b/src/hooks/_relative-paths.ts index 9586e73de8..8a787a3bb0 100644 --- a/src/hooks/_relative-paths.ts +++ b/src/hooks/_relative-paths.ts @@ -11,12 +11,16 @@ function gitWorktreeListing(cwd: string): string[] { const run = (args: string[]) => execFileSync("git", ["worktree", "list", "--porcelain", ...args], { cwd, - stdio: ["ignore", "pipe", "ignore"], + env: { ...process.env, LC_ALL: "C" }, + stdio: ["ignore", "pipe", "pipe"], timeout: 500, }).toString(); try { return run(["-z"]).split("\0"); - } catch {} + } 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 { @@ -26,25 +30,31 @@ function gitWorktreeListing(cwd: string): string[] { function tryRealpath(path: string): string | undefined { try { - return realpathSync(path); + return realpathSync.native(path); } catch { return undefined; } } +function slashed(path: string): string { + return path.replace(/\\/g, "/"); +} + function isInsideRoot(root: string, path: string): boolean { - return path === root || path.startsWith(`${root}/`) || path.startsWith(`${root}\\`); + 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(cwd: string, roots: readonly string[]): PathAlias[] { +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 = physical.slice(root.length); - const prefix = inside && cwd.endsWith(inside) ? cwd.slice(0, cwd.length - inside.length) : undefined; - if (prefix && tryRealpath(prefix) === root) return [{ from: prefix, to: "" }]; + 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, "/") }]; } @@ -73,35 +83,38 @@ function escapeRegExp(text: string): string { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -const PATH_END = `$|[\\s"'\`:;,)\\]}>]`; -const PATH_REST = `[^\\s"'\`]*`; +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"]); -// 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. -// Free text cannot say where a path ends, so it is converted only up to the next space; a path -// field is one path, so it is converted in full. -function aliasPattern(aliases: readonly PathAlias[], windows: boolean): RegExp | null { +// 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. Windows and macOS file systems ignore case, so their roots match in any case. 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): RegExp | null { if (aliases.length === 0) return null; const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); - const rest = windows ? PATH_REST : ""; + const tail = platform === "win32" ? WINDOWS_TAIL : ""; return new RegExp( - `(? { const to = aliases[groups.findIndex((group) => typeof group === "string")]?.to ?? ""; - const separator = groups[aliases.length]; - if (typeof separator !== "string") return to || "."; + if (typeof groups[aliases.length] !== "string") return to || "."; const tail = String(groups[aliases.length + 1] ?? "").replace(/\\/g, "/"); return to ? `${to}/${tail}` : tail; }; @@ -112,11 +125,22 @@ export function relativizePaths( ? rewritten.replace(/\\/g, "/") : rewritten; } - if (Array.isArray(node)) return node.map((child) => walk(child)); + 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, walk(child, k)])); + 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 dbcd610bf6..163165335c 100644 --- a/src/hooks/pre-tool-use.ts +++ b/src/hooks/pre-tool-use.ts @@ -1,6 +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; @@ -82,12 +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() - : relativePathsEnabled() - ? resolveProject(hookCwd(data) || process.cwd()) + : 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`, { @@ -95,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/tools-registry.ts b/src/mcp/tools-registry.ts index e190c3a14e..0ba7ded9c8 100644 --- a/src/mcp/tools-registry.ts +++ b/src/mcp/tools-registry.ts @@ -114,7 +114,7 @@ export const CORE_TOOLS: McpToolDef[] = [ }, project: { type: "string", - description: "Project to search; required to match repository-relative paths", + 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 index f4b8f3d988..e476cc878a 100644 --- a/test/file-context-relative-paths.test.ts +++ b/test/file-context-relative-paths.test.ts @@ -16,15 +16,24 @@ vi.mock("../src/functions/access-tracker.js", () => ({ recordAccessBatch: vi.fn(), })); -async function seed(kv: ReturnType, sessionId: string, project: string, file: string) { +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: `/repos/${project}`, startedAt, status: "completed", observationCount: 1 }); + 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 ${file} in ${project}`, + title: `edited ${label} in ${project}`, narrative: "", facts: [], concepts: [], @@ -33,15 +42,15 @@ async function seed(kv: ReturnType, sessionId: string, project: s }); } -describe("mem::file-context with repository-relative paths", () => { +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 ["repo-a", "repo-b", "repo-c", "repo-w"].filter((project) => context.includes(`in ${project}`)); + return context; }; - const lookupFor = (files: string[], project: string) => lookup({ files, project }); + const projectsIn = (context: string) => PROJECTS.filter((project) => context.includes(`in ${project}`)); beforeEach(async () => { sdk = mockSdk({ looseTrigger: true }); @@ -52,45 +61,98 @@ describe("mem::file-context with repository-relative paths", () => { 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"]); + 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"]); + }); }); - it("treats a UNC query as absolute", async () => { - expect(await lookup({ files: ["\\\\server\\share\\repo-c\\src\\a.ts"] })).toEqual([]); - }); + 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("treats a blank project as no project", async () => { - expect(await lookup({ files: ["/repos/repo-c/src/a.ts"], project: " " })).toEqual(["repo-c"]); - }); + 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 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("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("matches a Windows query against a forward-slash entry", async () => { - expect(await lookup({ files: ["C:\\repos\\repo-a\\src\\a.ts"], project: "repo-a" })).toEqual(["repo-a"]); - }); + 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("matches a stored Windows entry against a forward-slash query", async () => { - await seed(kv, "ses_win", "repo-w", "src\\w.ts"); - expect(await lookupFor(["src/w.ts"], "repo-w")).toContain("repo-w"); - }); + it("compares Windows drive letters 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"); + expect(await lookup({ files: ["src/d.ts"], project: "repo-w", relativeFiles: true })).toContain("drive d.ts"); + }); - it("still matches a relative query against relative entries", async () => { - expect(await lookup({ files: ["src/a.ts"], project: "repo-b" })).toEqual(["repo-b"]); + 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", () => { - it("passes its project to mem::file-context", async () => { + async function fileContextPayload(payload: Record) { const sdk = mockSdk({ looseTrigger: true }); - const kv = mockKV(); - registerEnrichFunction(sdk as never, kv as never); - const fileContext = vi.fn(async () => ({ context: "" })); + 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: ["/repos/repo-a/src/a.ts"], project: "repo-a" }); - expect(fileContext).toHaveBeenCalledWith(expect.objectContaining({ project: "repo-a" })); + 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) => { + 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: ["/x/data.ts"], + createdAt: now, updatedAt: now, + }); + const { context } = (await sdk.trigger("mem::enrich", { sessionId: "s", files: ["a.ts"], ...(relativeFiles && { relativeFiles }) })) as { + context: string; + }; + return context.includes("data bug"); + }; + expect(await pastErrors(true)).toBe(false); + expect(await pastErrors(false)).toBe(true); }); }); diff --git a/test/hook-relative-paths.test.ts b/test/hook-relative-paths.test.ts index e72545524f..34defdce45 100644 --- a/test/hook-relative-paths.test.ts +++ b/test/hook-relative-paths.test.ts @@ -1,10 +1,10 @@ import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest"; import { execFileSync, spawn } from "node:child_process"; import { createServer } from "node:http"; -import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync } from "node:fs"; +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"; +import { relativizeFilePath, relativizePaths, repositoryRoots } from "../src/hooks/_relative-paths.js"; describe("relativizePaths", () => { const roots = [ @@ -13,63 +13,100 @@ describe("relativizePaths", () => { ]; it("strips the root from a file path", () => { - expect(relativizePaths({ file_path: "/work/app/src/a.ts" }, roots)).toEqual({ file_path: "src/a.ts" }); + 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)).toBe("src/a.ts"); + 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)).toBe("cd . && cat README.md"); + 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)).toBe("/work/app-old/src/a.ts"); + 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)).toBe("/mnt/work/app/src/a.ts"); + 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), + 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)).toBe("cat packages/sub/a.ts 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, true)).toBe("src/a.ts"); - expect(relativizePaths("type C:\\work\\app\\x.ts", aliases, true)).toBe("type x.ts"); + 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, true)).toEqual({ + 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, true)).toBe("a.ts and docs\\guide.md"); - expect(relativizePaths("C:\\work\\app\\a.ts C:\\work\\app\\b.ts", aliases, true)).toBe("a.ts b.ts"); - expect(relativizePaths("see C:\\work\\app\\src\\lib(test)\\x.ts", aliases, true)).toBe("see src/lib(test)/x.ts"); + 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, false)).toBe("my\\ file.ts /Work/App/x"); + 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"); + }); + + it("matches roots in any case on macOS only", () => { + expect(relativizePaths("/Work/App/x.ts", roots, "darwin")).toBe("x.ts"); + expect(relativizePaths("/Work/App/x.ts", roots, "linux")).toBe("/Work/App/x.ts"); }); it("returns the value untouched when there are no roots", () => { const value = { file_path: "/work/app/src/a.ts" }; - expect(relativizePaths(value, [])).toBe(value); + 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"); }); }); @@ -129,6 +166,10 @@ describe("repositoryRoots", () => { 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") }); @@ -224,7 +265,7 @@ describe("pre-tool-use with AGENTMEMORY_RELATIVE_PATHS", () => { rmSync(tmpRoot, { recursive: true, force: true }); }); - async function enrichProject(relative: string): Promise { + async function enrichBody(relative: string): Promise | undefined> { const bodies: Array> = []; const server = createServer((req, res) => { let raw = ""; @@ -251,19 +292,17 @@ describe("pre-tool-use with AGENTMEMORY_RELATIVE_PATHS", () => { 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]?.["project"]; + return bodies[0]; } - it("scopes enrichment to the repository's project when the hook payload has none", async () => { - expect(await enrichProject("true")).toBe("repo"); - }); - - it("leaves enrichment unscoped by default", async () => { - expect(await enrichProject("")).toBeUndefined(); + 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("ships without the path matcher", () => { - const bundle = readFileSync(join(import.meta.dirname, "..", "plugin", "scripts", "pre-tool-use.mjs"), "utf8"); - expect(bundle).not.toMatch(/PATH_REST|PATH_END|function relativizePaths/); + 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"); }); }); From 21e2cefa055f922a719a4e9483c8305be59018f3 Mon Sep 17 00:00:00 2001 From: Spike Jourdain Date: Tue, 27 Oct 2026 11:25:45 +1100 Subject: [PATCH 6/7] fix(hooks): address fourth review on repository-relative paths - Windows paths (drive letter or UNC) compare in any case, directories included, when an older entry is placed under its session's root. - `&` ends a Windows free-text tail, like `|`. - On macOS, roots match in any case only when the volume ignores case: the root found under its case-swapped name must be the same file. - In relative mode two relative bug-memory paths must be equal; suffix matching stays only for an older absolute entry. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Spike Jourdain --- plugin/scripts/_capture.mjs | 21 +++++++++++++----- plugin/scripts/pre-tool-use.mjs | 23 ++++++++++++++----- src/functions/enrich.ts | 4 ++-- src/functions/file-index.ts | 25 ++++++++++++++++----- src/hooks/_relative-paths.ts | 28 +++++++++++++++++++----- test/file-context-relative-paths.test.ts | 12 ++++++---- test/hook-relative-paths.test.ts | 23 +++++++++++++++---- 7 files changed, 104 insertions(+), 32 deletions(-) diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index 579b923864..f805c1fcfd 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -920,7 +920,7 @@ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } const PATH_END = `$|[\\s"'\`:;,)\\]}>|&]`; -const WINDOWS_TAIL = `[^\\s"'\`,;|<>]*`; +const WINDOWS_TAIL = `[^\\s"'\`,;|&<>]*`; const PATH_KEYS = new Set([ "file_path", "filePath", @@ -930,13 +930,24 @@ const PATH_KEYS = new Set([ "file" ]); const SKIPPED_KEYS = new Set(["image_data", "imageData"]); -function aliasPattern(aliases, platform) { +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 alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); - return new RegExp(`(? 0 && aliases.every((alias) => ignoresCase(alias.from))) { + const pattern = aliasPattern(aliases, platform, caseInsensitive); if (!pattern) return value; const windows = platform === "win32"; const rewrite = (_match, ...groups) => { diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 81fc67fb4d..435bc48b43 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -import { readFileSync, realpathSync } from "node:fs"; +import { readFileSync, realpathSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, join, relative, resolve } from "node:path"; import { execFileSync, execSync } from "node:child_process"; @@ -217,7 +217,7 @@ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } const PATH_END = `$|[\\s"'\`:;,)\\]}>|&]`; -const WINDOWS_TAIL = `[^\\s"'\`,;|<>]*`; +const WINDOWS_TAIL = `[^\\s"'\`,;|&<>]*`; const PATH_KEYS = new Set([ "file_path", "filePath", @@ -227,13 +227,24 @@ const PATH_KEYS = new Set([ "file" ]); const SKIPPED_KEYS = new Set(["image_data", "imageData"]); -function aliasPattern(aliases, platform) { +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 alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); - return new RegExp(`(? 0 && aliases.every((alias) => ignoresCase(alias.from))) { + const pattern = aliasPattern(aliases, platform, caseInsensitive); if (!pattern) return value; const windows = platform === "win32"; const rewrite = (_match, ...groups) => { diff --git a/src/functions/enrich.ts b/src/functions/enrich.ts index 06dd67f5f7..ab13a9937f 100644 --- a/src/functions/enrich.ts +++ b/src/functions/enrich.ts @@ -4,7 +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 { pathsOverlap } from "./file-index.js"; +import { bugFileMatches } from "./file-index.js"; const MAX_CONTEXT_LENGTH = 4000; @@ -74,7 +74,7 @@ export function registerEnrichFunction(sdk: IIIClient, kv: StateKV): void { (!project || !m.project || m.project === project) && m.files.some((f) => data.files.some((df) => - data.relativeFiles === true ? pathsOverlap(f, df) : f.includes(df) || df.includes(f), + data.relativeFiles === true ? bugFileMatches(f, df) : f.includes(df) || df.includes(f), ), ), ) diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts index 22e2aaabd5..ab5f940f17 100644 --- a/src/functions/file-index.ts +++ b/src/functions/file-index.ts @@ -29,12 +29,23 @@ function isAbsolutePath(path: string): boolean { 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 (candidate.slice(candidate.lastIndexOf("/") + 1) === project) return candidate; + if (samePath(candidate, `${candidate.slice(0, candidate.lastIndexOf("/") + 1)}${project}`)) return candidate; } return dir; } @@ -45,12 +56,16 @@ function sessionRoot(cwd: string, project: string): string { function matchesRelativeQuery(query: string, stored: string, session: Session): boolean { const entry = normalizePath(stored); if (!isAbsolutePath(entry)) return entry === query; - return Boolean(session.cwd) && entry === `${sessionRoot(session.cwd, session.project)}/${query}`; + return Boolean(session.cwd) && samePath(entry, `${sessionRoot(session.cwd, session.project)}/${query}`); } -export function pathsOverlap(a: string, b: string): boolean { - const left = normalizePath(a); - const right = normalizePath(b); +// 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}`); } diff --git a/src/hooks/_relative-paths.ts b/src/hooks/_relative-paths.ts index 8a787a3bb0..e04d9ff717 100644 --- a/src/hooks/_relative-paths.ts +++ b/src/hooks/_relative-paths.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { realpathSync } from "node:fs"; +import { realpathSync, statSync } from "node:fs"; import { relative } from "node:path"; export interface PathAlias { @@ -84,23 +84,37 @@ function escapeRegExp(text: string): string { } const PATH_END = `$|[\\s"'\`:;,)\\]}>|&]`; -const WINDOWS_TAIL = `[^\\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. Windows and macOS file systems ignore case, so their roots match in any case. Windows +// are. Roots match in any case on Windows, and on macOS when the volume ignores case. 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): RegExp | null { +function aliasPattern(aliases: readonly PathAlias[], platform: NodeJS.Platform, caseInsensitive: boolean): RegExp | null { if (aliases.length === 0) return null; const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); const tail = platform === "win32" ? WINDOWS_TAIL : ""; return new RegExp( `(? 0 && aliases.every((alias) => ignoresCase(alias.from))), ): unknown { - const pattern = aliasPattern(aliases, platform); + const pattern = aliasPattern(aliases, platform, caseInsensitive); if (!pattern) return value; const windows = platform === "win32"; const rewrite = (_match: string, ...groups: unknown[]): string => { diff --git a/test/file-context-relative-paths.test.ts b/test/file-context-relative-paths.test.ts index e476cc878a..d7ac8b24a2 100644 --- a/test/file-context-relative-paths.test.ts +++ b/test/file-context-relative-paths.test.ts @@ -97,9 +97,11 @@ describe("mem::file-context", () => { expect([outside.includes("outside b.ts"), outside.includes("top b.ts")]).toEqual([false, false]); }); - it("compares Windows drive letters in any case", async () => { + 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 () => { @@ -136,7 +138,7 @@ describe("mem::enrich", () => { }); it("matches bug memories at path boundaries for a relative request, and as before otherwise", async () => { - const pastErrors = async (relativeFiles: boolean) => { + 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); @@ -144,15 +146,17 @@ describe("mem::enrich", () => { 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: ["/x/data.ts"], + 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: ["a.ts"], ...(relativeFiles && { relativeFiles }) })) as { + 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 index 34defdce45..1715809339 100644 --- a/test/hook-relative-paths.test.ts +++ b/test/hook-relative-paths.test.ts @@ -1,10 +1,10 @@ import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest"; import { execFileSync, spawn } from "node:child_process"; import { createServer } from "node:http"; -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; -import { relativizeFilePath, relativizePaths, repositoryRoots } from "../src/hooks/_relative-paths.js"; +import { ignoresCase, relativizeFilePath, relativizePaths, repositoryRoots } from "../src/hooks/_relative-paths.js"; describe("relativizePaths", () => { const roots = [ @@ -85,13 +85,28 @@ describe("relativizePaths", () => { 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 on macOS only", () => { - expect(relativizePaths("/Work/App/x.ts", roots, "darwin")).toBe("x.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("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); From 1f3ff640ef76c66f68c54f068ab8b3a65a7f43b9 Mon Sep 17 00:00:00 2001 From: Spike Jourdain Date: Tue, 27 Oct 2026 11:48:29 +1100 Subject: [PATCH 7/7] fix(hooks): decide case per root; add a spec test and known limits - Each root decides its own case (Windows, or a macOS volume that ignores case), so a case-sensitive worktree no longer turns off any-case matching for the other roots. Node 20 has no inline case flag, so an any-case root's letters are written as `[aA]`. - test/relative-paths-spec.test.ts: one table of capture cases per platform, and a round trip that captures on one machine and looks up on another, including what must not be found and the flag-off parity. - README: known limits (Windows best effort, older absolute entries from sibling-directory worktrees, newlines in a repository path). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Spike Jourdain --- README.md | 6 ++ plugin/scripts/_capture.mjs | 14 ++-- plugin/scripts/pre-tool-use.mjs | 12 ++-- src/hooks/_relative-paths.ts | 33 +++++++--- test/hook-relative-paths.test.ts | 8 +++ test/relative-paths-spec.test.ts | 109 +++++++++++++++++++++++++++++++ 6 files changed, 164 insertions(+), 18 deletions(-) create mode 100644 test/relative-paths-spec.test.ts diff --git a/README.md b/README.md index 687951ca7b..cd625f3762 100644 --- a/README.md +++ b/README.md @@ -1337,6 +1337,12 @@ When several machines share one server, each clone records its files under its o - 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. diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index f805c1fcfd..9ecc18fa53 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -943,11 +943,15 @@ function ignoresCase(path) { } function aliasPattern(aliases, platform, caseInsensitive) { if (aliases.length === 0) return null; - const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); - return new RegExp(`(? 0 && aliases.every((alias) => ignoresCase(alias.from))) { - const pattern = aliasPattern(aliases, platform, caseInsensitive); + 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) => { diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 435bc48b43..c867122121 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -240,11 +240,15 @@ function ignoresCase(path) { } function aliasPattern(aliases, platform, caseInsensitive) { if (aliases.length === 0) return null; - const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); - return new RegExp(`(? 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(`(? 0 && aliases.every((alias) => ignoresCase(alias.from))) { - const pattern = aliasPattern(aliases, platform, caseInsensitive); +function relativizePaths(value, aliases, platform = process.platform, caseInsensitive = (root) => 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) => { diff --git a/src/hooks/_relative-paths.ts b/src/hooks/_relative-paths.ts index e04d9ff717..84e837b6ef 100644 --- a/src/hooks/_relative-paths.ts +++ b/src/hooks/_relative-paths.ts @@ -104,17 +104,28 @@ export function ignoresCase(path: string): boolean { // 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. Roots match in any case on Windows, and on macOS when the volume ignores case. 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 +// 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: boolean): RegExp | null { +function aliasPattern( + aliases: readonly PathAlias[], + platform: NodeJS.Platform, + caseInsensitive: (root: string) => boolean, +): RegExp | null { if (aliases.length === 0) return null; - const alternatives = aliases.map((alias) => `(${escapeRegExp(alias.from)})`).join("|"); + 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( `(? 0 && aliases.every((alias) => ignoresCase(alias.from))), + caseInsensitive: boolean | ((root: string) => boolean) = (root) => + platform === "win32" || (platform === "darwin" && ignoresCase(root)), ): unknown { - const pattern = aliasPattern(aliases, platform, caseInsensitive); + 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 => { diff --git a/test/hook-relative-paths.test.ts b/test/hook-relative-paths.test.ts index 1715809339..329361a035 100644 --- a/test/hook-relative-paths.test.ts +++ b/test/hook-relative-paths.test.ts @@ -94,6 +94,14 @@ describe("relativizePaths", () => { 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); 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"]); + }); +});