#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix(capture): file linked git worktrees under the main checkout's project (#1511)
Dmitrii Zhukove37c6a7eae87
diff --git a/integrations/filesystem-watcher/watcher.mjs b/integrations/filesystem-watcher/watcher.mjsindex b0d37830..49a70741 100644--- a/integrations/filesystem-watcher/watcher.mjs+++ b/integrations/filesystem-watcher/watcher.mjs@@ -1,26 +1,40 @@-import { watch, promises as fsp, readFileSync, statSync } from "node:fs";+import { watch, promises as fsp, readFileSync, realpathSync, statSync } from "node:fs";import { homedir } from "node:os";-import { resolve, relative, join, extname, sep, basename } from "node:path";+import { resolve, relative, join, extname, sep, basename, dirname } from "node:path";import { randomBytes } from "node:crypto";import { execFileSync } from "node:child_process";-// Same resolution order as the hooks' resolveProject (git toplevel basename,+// Same resolution order as the hooks' resolveProject (git repository basename,// then directory basename) so a watched subdirectory scopes to the repository// name instead of the subdirectory name.function deriveProjectName(dir) {try {- const top = execFileSync("git", ["rev-parse", "--show-toplevel"], {- cwd: dir,- stdio: ["ignore", "pipe", "ignore"],- encoding: "utf8",- }).trim();- if (top) return basename(top);+ const [top, gitDir, commonDir] = execFileSync(+ "git",+ ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"],+ {+ cwd: dir,+ stdio: ["ignore", "pipe", "ignore"],+ encoding: "utf8",+ },+ )+ .trim()+ .split(/\r?\n/);+ if (top) return basename(repositoryRoot(dir, top, gitDir, commonDir));} catch {// not a git repo}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);+}+const TEXT_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",".py", ".rb", ".go", ".rs", ".java", ".kt", ".swift",diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.pyindex 878a6524..c2361063 100644--- a/integrations/hermes/__init__.py+++ b/integrations/hermes/__init__.py@@ -19,24 +19,39 @@ from pathlib import PurePathdef _resolve_project(cwd: str) -> str:"""Canonical project scope, matching the hooks' resolveProject order:- AGENTMEMORY_PROJECT_NAME env override, git toplevel basename, cwd basename.+ AGENTMEMORY_PROJECT_NAME env override, git repository basename, cwd basename.Keeps Hermes sessions in the same project bucket as every other agent."""explicit = os.environ.get("AGENTMEMORY_PROJECT_NAME", "").strip()if explicit:return explicittry:- top = subprocess.run(- ["git", "rev-parse", "--show-toplevel"],+ out = subprocess.run(+ ["git", "rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"],cwd=cwd,capture_output=True,text=True,timeout=5,).stdout.strip()+ top, git_dir, common_dir = (out.splitlines() + ["", "", ""])[:3]if top:- return PurePath(top).name+ return PurePath(_repository_root(cwd, top, git_dir, common_dir)).nameexcept Exception:passreturn PurePath(cwd).name or cwd+++def _repository_root(cwd: str, top: str, git_dir: str, common_dir: str) -> str:+ """A linked worktree is named by the main checkout owning the shared .git;+ bare repos and submodules keep the toplevel."""+ if not git_dir or not common_dir:+ return top+ physical = os.path.realpath(cwd)+ common = os.path.normpath(os.path.join(physical, common_dir))+ if os.path.normpath(os.path.join(physical, git_dir)) == common:+ return top+ if os.path.basename(common) != ".git":+ return top+ return os.path.dirname(common)import timefrom pathlib import Pathfrom typing import Any, Callablediff --git a/integrations/pi/index.ts b/integrations/pi/index.tsindex 804c1a9d..c3c45d38 100644--- a/integrations/pi/index.ts+++ b/integrations/pi/index.ts@@ -3,8 +3,17 @@ import { Type } from "typebox";import path from "node:path";import crypto from "node:crypto";import { execFileSync } from "node:child_process";+import { realpathSync } from "node:fs";import { createPlaintextBearerAuthGuard, resolveSecret } from "./security.js";+function repositoryRoot(dir: string, top: string, gitDir?: string, commonDir?: string): string {+ if (!gitDir || !commonDir) return top;+ const physical = realpathSync(dir);+ const common = path.resolve(physical, commonDir);+ if (path.resolve(physical, gitDir) === common || path.basename(common) !== ".git") return top;+ return path.dirname(common);+}+type TextBlock = { type?: string; text?: string };type AssistantMessage = { role?: string; content?: unknown };type SmartSearchResult = {@@ -124,7 +133,7 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {}let sessionId = `ephemeral-${crypto.randomUUID().slice(0, 8)}`;// Canonical project scope, matching the hooks' resolveProject order (env- // override, git toplevel basename, cwd basename) so Pi sessions share a+ // override, git repository basename, cwd basename) so Pi sessions share a// project bucket with every other agent instead of scoping on a raw path.const projectCache = new Map<string, string>();function resolveProjectName(dir: string): string {@@ -134,12 +143,18 @@ export default function agentmemoryExtension(pi: ExtensionAPI) {if (cached) return cached;let name = path.basename(dir) || dir;try {- const top = execFileSync("git", ["rev-parse", "--show-toplevel"], {- cwd: dir,- stdio: ["ignore", "pipe", "ignore"],- encoding: "utf8",- }).trim();- if (top) name = path.basename(top);+ const [top, gitDir, commonDir] = execFileSync(+ "git",+ ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"],+ {+ cwd: dir,+ stdio: ["ignore", "pipe", "ignore"],+ encoding: "utf8",+ },+ )+ .trim()+ .split(/\r?\n/);+ if (top) name = path.basename(repositoryRoot(dir, top, gitDir, commonDir));} catch {// not a git repo}diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.tsindex a5ab188c..bd1ecce3 100644--- a/plugin/opencode/agentmemory-capture.ts+++ b/plugin/opencode/agentmemory-capture.ts@@ -1,8 +1,8 @@import type { Plugin } from "@opencode-ai/plugin";import { execFileSync } from "node:child_process";-import { readFileSync } from "node:fs";+import { readFileSync, realpathSync } from "node:fs";import { homedir } from "node:os";-import { basename, join } from "node:path";+import { basename, dirname, join, resolve } from "node:path";const API = process.env.AGENTMEMORY_URL || "http://localhost:3111";// OpenCode reports tool names in lowercase ("read", "edit", ...); matching is@@ -116,7 +116,7 @@ async function observe(let activeSessionId: string | null = null;let pendingConfig: Record<string, unknown> | null = null;// Default scope resolved at plugin init (same resolution order as the hooks'-// resolveProject: env override, git toplevel basename, cwd basename). In a+// resolveProject: env override, git repository basename, cwd basename). In a// long-lived OpenCode process serving multiple directories these defaults are// only a fallback — attribution is per-session via sessionProjects, resolved// from each session's own directory at session.created. Module-level-only@@ -138,13 +138,19 @@ function resolveProjectName(dir: string): string {const cached = projectNameCache.get(dir);if (cached !== undefined) return cached;try {- const top = execFileSync("git", ["rev-parse", "--show-toplevel"], {- cwd: dir,- stdio: ["ignore", "pipe", "ignore"],- encoding: "utf8",- }).trim();+ const [top, gitDir, commonDir] = execFileSync(+ "git",+ ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"],+ {+ cwd: dir,+ stdio: ["ignore", "pipe", "ignore"],+ encoding: "utf8",+ },+ )+ .trim()+ .split(/\r?\n/);if (top) {- const name = basename(top);+ const name = basename(repositoryRoot(dir, top, gitDir, commonDir));projectNameCache.set(dir, name);return name;}@@ -155,6 +161,14 @@ function resolveProjectName(dir: string): string {projectNameCache.set(dir, fallback);return fallback;}++function repositoryRoot(dir: string, top: string, gitDir?: string, commonDir?: string): string {+ 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);+}const stashedFiles = new Map<string, Set<string>>();const seenSubtaskIds = new Map<string, Set<string>>();const seenToolCallIds = new Map<string, Set<string>>();diff --git a/plugin/scripts/notification.mjs b/plugin/scripts/notification.mjsindex c474a226..423b9965 100755--- a/plugin/scripts/notification.mjs+++ b/plugin/scripts/notification.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";import { captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_project.tsfunction resolveProject(cwd) {@@ -8,7 +9,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -16,11 +17,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjsindex c3ddc2ab..acb2d67a 100755--- a/plugin/scripts/post-tool-failure.mjs+++ b/plugin/scripts/post-tool-failure.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";import { captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_capture-filter.tsconst DEFAULT_DENY_PATTERNS = [@@ -49,7 +50,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -57,11 +58,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/post-tool-use.mjs b/plugin/scripts/post-tool-use.mjsindex 585dea9b..7cdb56ab 100755--- a/plugin/scripts/post-tool-use.mjs+++ b/plugin/scripts/post-tool-use.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";import { captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_capture-filter.tsconst DEFAULT_DENY_PATTERNS = [@@ -70,7 +71,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -78,11 +79,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjsindex d084d86d..0bc22656 100755--- a/plugin/scripts/pre-compact.mjs+++ b/plugin/scripts/pre-compact.mjs@@ -1,7 +1,7 @@#!/usr/bin/env node-import { readFileSync } from "node:fs";+import { readFileSync, realpathSync } from "node:fs";import { homedir } from "node:os";-import { basename, join } from "node:path";+import { basename, dirname, join, resolve } from "node:path";import { execSync } from "node:child_process";//#region src/secret-store.tsconst SECRET_KEY = "AGENTMEMORY_SECRET";@@ -85,7 +85,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -93,11 +93,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/prompt-submit.mjs b/plugin/scripts/prompt-submit.mjsindex 03061e77..38e16274 100755--- a/plugin/scripts/prompt-submit.mjs+++ b/plugin/scripts/prompt-submit.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";import { captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_project.tsfunction resolveProject(cwd) {@@ -8,7 +9,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -16,11 +17,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/session-end.mjs b/plugin/scripts/session-end.mjsindex 8b57637f..2e3b64f6 100755--- a/plugin/scripts/session-end.mjs+++ b/plugin/scripts/session-end.mjs@@ -1,7 +1,7 @@#!/usr/bin/env node-import { readFileSync } from "node:fs";+import { readFileSync, realpathSync } from "node:fs";import { execSync } from "node:child_process";-import { basename } from "node:path";+import { basename, dirname, resolve } from "node:path";import { REST_URL, authHeaders, captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_project.tsfunction resolveProject(cwd) {@@ -9,7 +9,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -17,11 +17,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjsindex e2c83b02..4eaf2479 100755--- a/plugin/scripts/session-start.mjs+++ b/plugin/scripts/session-start.mjs@@ -1,7 +1,7 @@#!/usr/bin/env node-import { readFileSync } from "node:fs";+import { readFileSync, realpathSync } from "node:fs";import { homedir } from "node:os";-import { basename, join } from "node:path";+import { basename, dirname, join, resolve } from "node:path";import { execSync } from "node:child_process";//#region src/secret-store.tsconst SECRET_KEY = "AGENTMEMORY_SECRET";@@ -76,7 +76,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -84,11 +84,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/subagent-start.mjs b/plugin/scripts/subagent-start.mjsindex 01f33785..ebb174b7 100755--- a/plugin/scripts/subagent-start.mjs+++ b/plugin/scripts/subagent-start.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";import { captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_project.tsfunction resolveProject(cwd) {@@ -8,7 +9,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -16,11 +17,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjsindex 8e0797b4..f84008f7 100755--- a/plugin/scripts/subagent-stop.mjs+++ b/plugin/scripts/subagent-stop.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";import { captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_project.tsfunction resolveProject(cwd) {@@ -8,7 +9,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -16,11 +17,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/plugin/scripts/task-completed.mjs b/plugin/scripts/task-completed.mjsindex b5fc0fca..5567f4e9 100755--- a/plugin/scripts/task-completed.mjs+++ b/plugin/scripts/task-completed.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";import { captureObservation, isDrainChild, runDrainChild, withEventId } from "./_capture.mjs";//#region src/hooks/_project.tsfunction resolveProject(cwd) {@@ -8,7 +9,7 @@ function resolveProject(cwd) {if (explicit && explicit.trim()) return explicit.trim();const dir = cwd && cwd.trim() ? cwd : process.cwd();try {- const top = execSync("git rev-parse --show-toplevel", {+ const [top, gitDir, commonDir] = execSync("git rev-parse --show-toplevel --git-dir --git-common-dir", {cwd: dir,stdio: ["ignore",@@ -16,11 +17,18 @@ function resolveProject(cwd) {"ignore"],timeout: 500- }).toString().trim();- if (top) return basename(top);+ }).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;diff --git a/src/hooks/_project.ts b/src/hooks/_project.tsindex 9f0320c5..552468df 100644--- a/src/hooks/_project.ts+++ b/src/hooks/_project.ts@@ -1,24 +1,37 @@import { execSync } from "node:child_process";-import { basename } from "node:path";+import { realpathSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";-// Resolution order: AGENTMEMORY_PROJECT_NAME env → git toplevel basename → cwd basename.+// Resolution order: AGENTMEMORY_PROJECT_NAME env → git repository basename → cwd basename.export function resolveProject(cwd?: string): string {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 = execSync("git rev-parse --show-toplevel", {- cwd: dir,- stdio: ["ignore", "pipe", "ignore"],- timeout: 500,- })+ 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();- if (top) return basename(top);+ .trim()+ .split(/\r?\n/);+ if (top) return basename(repositoryRoot(dir, top, gitDir, commonDir));} catch {}return basename(dir);}+function repositoryRoot(dir: string, top: string, gitDir?: string, commonDir?: string): string {+ 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);+}+export function hookCwd(data: Record<string, unknown> | null | undefined): string | undefined {if (!data || typeof data !== "object") return undefined;if (typeof data.cwd === "string" && data.cwd.trim()) return data.cwd;diff --git a/src/replay/jsonl-parser.ts b/src/replay/jsonl-parser.tsindex ec2f33d1..c5f5ee4c 100644--- a/src/replay/jsonl-parser.ts+++ b/src/replay/jsonl-parser.ts@@ -1,5 +1,6 @@-import { existsSync } from "node:fs";+import { existsSync, realpathSync } from "node:fs";import { execFileSync } from "node:child_process";+import { basename, dirname, resolve } from "node:path";import type { HookType, RawObservation } from "../types.js";import { generateId } from "../state/schema.js";@@ -29,24 +30,38 @@ export interface ParsedTranscript {// Memoized per import run: transcripts repeat the same cwd on every line.const projectByCwd = new Map<string, string>();+function repositoryRoot(dir: string, top: string, gitDir?: string, commonDir?: string): string {+ 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 deriveProject(cwd: string): string {if (!cwd) return "unknown";const cached = projectByCwd.get(cwd);if (cached) return cached;let name = "";// When the recorded cwd still exists on this machine, resolve the git- // toplevel basename so a subdirectory session scopes to the repository+ // repository basename so a subdirectory session scopes to the repository// name, matching the hooks' resolveProject. Historical or cross-platform// paths fall back to the basename below. No env override here: a bulk// import spans many projects, so a global name would mislabel them all.if (existsSync(cwd)) {try {- const top = execFileSync("git", ["rev-parse", "--show-toplevel"], {- cwd,- stdio: ["ignore", "pipe", "ignore"],- encoding: "utf8",- }).trim();- if (top) name = top.split(/[\\/]+/).filter(Boolean).pop() ?? "";+ const [top, gitDir, commonDir] = execFileSync(+ "git",+ ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"],+ {+ cwd,+ stdio: ["ignore", "pipe", "ignore"],+ encoding: "utf8",+ },+ )+ .trim()+ .split(/\r?\n/);+ if (top) name = basename(repositoryRoot(cwd, top, gitDir, commonDir));} catch {// not a git repo}diff --git a/test/hook-project.test.ts b/test/hook-project.test.tsindex 37d0e424..85c9583a 100644--- a/test/hook-project.test.ts+++ b/test/hook-project.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from "vitest";import { execFileSync } from "node:child_process";-import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs";import { tmpdir } from "node:os";import { basename, dirname, join } from "node:path";import { resolveProject } from "../src/hooks/_project.js";@@ -98,3 +98,86 @@ describe("resolveProject — hook project basename resolver", () => {expect(resolveProject(" ")).toBe(REPO_NAME);});});++describe("resolveProject — linked worktrees", () => {+ const originalEnv = process.env.AGENTMEMORY_PROJECT_NAME;+ const MAIN_NAME = "amem-fixture-main";++ let tmpRoot: string;+ let mainDir: string;+ let worktreeDir: string;++ function git(cwd: string, ...args: string[]): void {+ execFileSync(+ "git",+ [+ "-c", "user.name=amem",+ "-c", "[email protected]",+ "-c", "commit.gpgsign=false",+ "-c", "protocol.file.allow=always",+ ...args,+ ],+ { cwd, stdio: "ignore" },+ );+ }++ function initRepo(dir: string): void {+ mkdirSync(dir, { recursive: true });+ git(dir, "init", "--quiet");+ git(dir, "commit", "--quiet", "--allow-empty", "--no-verify", "-m", "init");+ }++ beforeAll(() => {+ tmpRoot = mkdtempSync(join(tmpdir(), "amem-worktree-"));+ mainDir = join(tmpRoot, MAIN_NAME);+ initRepo(mainDir);+ worktreeDir = join(tmpRoot, "feature-branch");+ git(mainDir, "worktree", "add", "-b", "feature-branch", worktreeDir);+ mkdirSync(join(worktreeDir, "src", "deep"), { recursive: true });+ });++ afterAll(() => {+ rmSync(tmpRoot, { recursive: true, force: true });+ });++ beforeEach(() => {+ delete process.env.AGENTMEMORY_PROJECT_NAME;+ });++ afterEach(() => {+ if (originalEnv === undefined) {+ delete process.env.AGENTMEMORY_PROJECT_NAME;+ } else {+ process.env.AGENTMEMORY_PROJECT_NAME = originalEnv;+ }+ });++ it("names a linked worktree after its main checkout", () => {+ expect(resolveProject(worktreeDir)).toBe(MAIN_NAME);+ });++ it("names a subdirectory of a linked worktree after its main checkout", () => {+ expect(resolveProject(join(worktreeDir, "src", "deep"))).toBe(MAIN_NAME);+ });++ it("keeps the main checkout's own name", () => {+ expect(resolveProject(mainDir)).toBe(MAIN_NAME);+ });++ it("keeps a submodule's own name instead of its superproject's module store", () => {+ const lib = join(tmpRoot, "amem-fixture-lib");+ const superproject = join(tmpRoot, "amem-fixture-super");+ initRepo(lib);+ initRepo(superproject);+ git(superproject, "submodule", "--quiet", "add", lib, "vendor/lib");+ expect(resolveProject(join(superproject, "vendor", "lib"))).toBe("lib");+ });++ it("resolves a symlink into a repository subdirectory to the repository name", () => {+ const nested = join(mainDir, "pkg", "core");+ mkdirSync(nested, { recursive: true });+ const link = join(tmpRoot, "shortcut");+ symlinkSync(nested, link);+ expect(resolveProject(link)).toBe(MAIN_NAME);+ });+});diff --git a/test/opencode-auto-context.test.ts b/test/opencode-auto-context.test.tsindex 3faa1d1e..6de034ff 100644--- a/test/opencode-auto-context.test.ts+++ b/test/opencode-auto-context.test.ts@@ -117,6 +117,36 @@ describe("OpenCode plugin project name resolution", () => {rmSync(root, { recursive: true, force: true });}});++ it("names a linked git worktree after its main checkout", async () => {+ const { mkdtempSync, mkdirSync, rmSync } = await import("node:fs");+ const { tmpdir } = await import("node:os");+ const { join } = await import("node:path");+ const { execFileSync } = await import("node:child_process");+ const root = mkdtempSync(join(tmpdir(), "amem-oc-wt-"));+ const repo = join(root, "oc-main-repo");+ const linked = join(root, "oc-feature-branch");+ mkdirSync(repo, { recursive: true });+ const git = (...args: string[]) =>+ execFileSync(+ "git",+ [+ "-c", "user.name=amem",+ "-c", "[email protected]",+ "-c", "commit.gpgsign=false",+ ...args,+ ],+ { cwd: repo, stdio: "ignore" },+ );+ try {+ git("init", "--quiet");+ git("commit", "--quiet", "--allow-empty", "--no-verify", "-m", "init");+ git("worktree", "add", "-b", "oc-feature-branch", linked);+ expect(await projectFor({ worktree: linked })).toBe("oc-main-repo");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });});describe("OpenCode plugin file-tool matching", () => {diff --git a/test/project-scope-parity.test.ts b/test/project-scope-parity.test.tsindex 408e4531..60b39780 100644--- a/test/project-scope-parity.test.ts+++ b/test/project-scope-parity.test.ts@@ -10,7 +10,7 @@ import { parseJsonlText } from "../src/replay/jsonl-parser.js";import { configFromEnv } from "../integrations/filesystem-watcher/watcher.mjs";// Project-scope parity: every capture surface must resolve `project` the same-// way the hooks do (env override, git toplevel basename, cwd basename), or the+// way the hooks do (env override, git repository basename, cwd basename), or the// same repo fragments into per-agent memory buckets that never cross-recall.function transcriptLine(cwd: string): string {@@ -121,6 +121,51 @@ describe("git-toplevel resolution parity", () => {});});+describe("linked worktree parity", () => {+ let tmpRoot: string;+ let worktreeDir: string;++ beforeAll(() => {+ tmpRoot = mkdtempSync(join(tmpdir(), "amem-parity-wt-"));+ const mainDir = join(tmpRoot, "parity-main-repo");+ mkdirSync(mainDir, { recursive: true });+ const git = (...args: string[]) =>+ execFileSync(+ "git",+ [+ "-c", "user.name=amem",+ "-c", "[email protected]",+ "-c", "commit.gpgsign=false",+ ...args,+ ],+ { cwd: mainDir, stdio: "ignore" },+ );+ git("init", "--quiet");+ git("commit", "--quiet", "--allow-empty", "--no-verify", "-m", "init");+ worktreeDir = join(tmpRoot, "parity-feature-branch");+ git("worktree", "add", "-b", "parity-feature-branch", worktreeDir);+ mkdirSync(join(worktreeDir, "packages", "core"), { recursive: true });+ });++ afterAll(() => {+ rmSync(tmpRoot, { recursive: true, force: true });+ });++ it("replay names a linked worktree session after the main checkout", () => {+ const parsed = parseJsonlText(transcriptLine(join(worktreeDir, "packages", "core")));+ expect(parsed.project).toBe("parity-main-repo");+ });++ it("watcher names a linked worktree root after the main checkout", () => {+ const w = new FilesystemWatcher({+ roots: [worktreeDir],+ baseUrl: "http://localhost:3111",+ logger: {},+ });+ expect(w.project).toBe("parity-main-repo");+ });+});+describe("fs-watcher configFromEnv project override", () => {it("prefers the canonical AGENTMEMORY_PROJECT_NAME", () => {const cfg = configFromEnv({