Repository navigation
fix(hooks): scope pre-tool-use enrichment to the current project #1220
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() { | ||
|
|
@@ -146,6 +147,43 @@ function hookAuthHeaders(endpoint) { | |
| return h; | ||
| } | ||
| //#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); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
| 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/pre-tool-use.ts | ||
| function isSdkChildContext(payload) { | ||
| if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; | ||
|
|
@@ -222,7 +260,8 @@ 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() : void 0) ?? resolveProject(hookCwd(data) || process.cwd())).trim(); | ||
| if (!project) return; | ||
| try { | ||
| const res = await fetch(`${REST_URL}/agentmemory/enrich`, { | ||
| method: "POST", | ||
|
|
@@ -232,7 +271,7 @@ async function main() { | |
| files, | ||
| terms, | ||
| toolName, | ||
| ...project !== void 0 && { project } | ||
| project | ||
| }), | ||
| signal: AbortSignal.timeout(enrichTimeoutMs()) | ||
| }); | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔍 Commits lack required sign-offs All three PR commits lack the Was this helpful? React with 👍 or 👎 to provide feedback. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| #!/usr/bin/env node | ||
| import { hookAuthHeaders, hookSetting, reportBlockedTransport, resolveHookEndpoint } from "./_endpoint.js"; | ||
| import { resolveProject, hookCwd } from "./_project.js"; | ||
|
|
||
| function isSdkChildContext(payload: unknown): boolean { | ||
| if (process.env["AGENTMEMORY_SDK_CHILD"] === "1") return true; | ||
|
|
@@ -102,10 +103,12 @@ async function main() { | |
| typeof rawSessionId === "string" && rawSessionId.length > 0 | ||
| ? rawSessionId | ||
| : "unknown"; | ||
| const project = | ||
| const explicitProject = | ||
| typeof data.project === "string" && data.project.trim().length > 0 | ||
| ? data.project.trim() | ||
| : undefined; | ||
| const project = (explicitProject ?? resolveProject(hookCwd(data) || process.cwd())).trim(); | ||
| if (!project) return; | ||
|
|
||
| try { | ||
| const res = await fetch(`${REST_URL}/agentmemory/enrich`, { | ||
|
|
@@ -116,7 +119,7 @@ async function main() { | |
| files, | ||
| terms, | ||
| toolName, | ||
| ...(project !== undefined && { project }), | ||
| project, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| }), | ||
| signal: AbortSignal.timeout(enrichTimeoutMs()), | ||
| }); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| import { describe, it, expect, beforeAll, afterAll } from "vitest"; | ||
| import { execFileSync, spawn } from "node:child_process"; | ||
| import { createServer, type Server } from "node:http"; | ||
| import { mkdtempSync, mkdirSync, rmSync } from "node:fs"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
|
|
||
| let server: Server; | ||
| let port: number; | ||
| let posts: Array<{ path: string; body: Record<string, unknown> }> = []; | ||
|
|
||
| const REPO_NAME = "amem-pretool-fixture"; | ||
|
|
||
| function runHook( | ||
| payload: Record<string, unknown>, | ||
| env: Record<string, string> = {}, | ||
| ): Promise<number> { | ||
| return new Promise((resolve) => { | ||
| const child = spawn("node", ["plugin/scripts/pre-tool-use.mjs"], { | ||
| env: { | ||
| ...process.env, | ||
| AGENTMEMORY_URL: `http://127.0.0.1:${port}`, | ||
| AGENTMEMORY_INJECT_CONTEXT: "true", | ||
| AGENTMEMORY_PROJECT_NAME: "", | ||
| ...env, | ||
| }, | ||
| }); | ||
| child.on("exit", (code) => resolve(code ?? 1)); | ||
| child.stdin.write(JSON.stringify(payload)); | ||
| child.stdin.end(); | ||
| }); | ||
| } | ||
|
|
||
| describe("pre-tool-use enrich is project-scoped", () => { | ||
| let tmpRoot: string; | ||
| let repoDir: string; | ||
| let nestedDir: string; | ||
|
|
||
| beforeAll(async () => { | ||
| tmpRoot = mkdtempSync(join(tmpdir(), "am-pretool-")); | ||
| repoDir = join(tmpRoot, REPO_NAME); | ||
| nestedDir = join(repoDir, "src", "deep"); | ||
| mkdirSync(nestedDir, { recursive: true }); | ||
| execFileSync("git", ["init", "--quiet"], { cwd: repoDir, stdio: "ignore" }); | ||
|
|
||
| server = createServer((req, res) => { | ||
| let body = ""; | ||
| req.on("data", (c) => (body += c)); | ||
| req.on("end", () => { | ||
| try { | ||
| posts.push({ path: req.url ?? "", body: JSON.parse(body || "{}") }); | ||
| } catch { | ||
| posts.push({ path: req.url ?? "", body: {} }); | ||
| } | ||
| res.writeHead(200, { "Content-Type": "application/json" }); | ||
| res.end(JSON.stringify({ context: "" })); | ||
| }); | ||
| }); | ||
| await new Promise<void>((r) => server.listen(0, "127.0.0.1", r)); | ||
| port = (server.address() as { port: number }).port; | ||
| }); | ||
|
|
||
| afterAll(() => { | ||
| server.close(); | ||
| rmSync(tmpRoot, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| it("derives project from the payload cwd", async () => { | ||
| posts = []; | ||
| await runHook({ | ||
| session_id: "s1", | ||
| cwd: repoDir, | ||
| tool_name: "Read", | ||
| tool_input: { file_path: join(repoDir, "src", "thing.ts") }, | ||
| }); | ||
|
|
||
| expect(posts.length).toBe(1); | ||
| expect(posts[0]!.path).toContain("/agentmemory/enrich"); | ||
| expect(posts[0]!.body.project).toBe(REPO_NAME); | ||
| }); | ||
|
|
||
| it("resolves to the git toplevel from a nested cwd", async () => { | ||
| posts = []; | ||
| await runHook({ | ||
| session_id: "s2", | ||
| cwd: nestedDir, | ||
| tool_name: "Edit", | ||
| tool_input: { file_path: join(nestedDir, "x.ts") }, | ||
| }); | ||
|
|
||
| expect(posts.length).toBe(1); | ||
| expect(posts[0]!.body.project).toBe(REPO_NAME); | ||
| }); | ||
|
|
||
| it("never sends an unscoped enrich request", async () => { | ||
| posts = []; | ||
| await runHook({ | ||
| session_id: "s3", | ||
| cwd: repoDir, | ||
| tool_name: "Grep", | ||
| tool_input: { pattern: "handleError", path: repoDir }, | ||
| }); | ||
|
|
||
| expect(posts.length).toBe(1); | ||
| const project = posts[0]!.body.project; | ||
| expect(project).toBeTruthy(); | ||
| expect(typeof project).toBe("string"); | ||
| }); | ||
|
|
||
| it("an explicit payload project still wins (hosts that do supply one)", async () => { | ||
| posts = []; | ||
| await runHook({ | ||
| session_id: "s4", | ||
| cwd: repoDir, | ||
| project: "explicit-project", | ||
| tool_name: "Read", | ||
| tool_input: { file_path: join(repoDir, "y.ts") }, | ||
| }); | ||
|
|
||
| expect(posts.length).toBe(1); | ||
| expect(posts[0]!.body.project).toBe("explicit-project"); | ||
| }); | ||
|
|
||
| it("skips enrich when the resolved project is empty", async () => { | ||
| posts = []; | ||
| await runHook({ | ||
| session_id: "s6", | ||
| cwd: "/", | ||
| tool_name: "Read", | ||
| tool_input: { file_path: "/etc/hosts" }, | ||
| }); | ||
|
|
||
| expect(posts.length).toBe(0); | ||
| }); | ||
|
|
||
| it("stays a no-op when AGENTMEMORY_INJECT_CONTEXT is not true", async () => { | ||
| posts = []; | ||
| await runHook( | ||
| { | ||
| session_id: "s5", | ||
| cwd: repoDir, | ||
| tool_name: "Read", | ||
| tool_input: { file_path: join(repoDir, "z.ts") }, | ||
| }, | ||
| { AGENTMEMORY_INJECT_CONTEXT: "false" }, | ||
| ); | ||
|
|
||
| expect(posts.length).toBe(0); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: rohitg00/agentmemory
Length of output: 7754
Script executed:
Repository: rohitg00/agentmemory
Length of output: 42106
Web query:
Claude Code hooks PreToolUse command synchronous blocks tool until hook finishes documentation asyncResult:
Script executed:
Repository: rohitg00/agentmemory
Length of output: 15693
Avoid resolving the project with Git on every tool call.
When context injection is enabled and no project override is set, a slow filesystem can add close to 500 ms to each eligible file-tool call before enrichment starts. Reuse a correctly scoped project resolution across hook invocations.