|
| 1 | +/** |
| 2 | + * Cross-process deduplication for Claude hooks installed in multiple scopes. |
| 3 | + * |
| 4 | + * Claude starts one hook process per matching user/project/local registration. |
| 5 | + * Those processes receive the same session + tool-use identifiers. An exclusive |
| 6 | + * lock elects one process to evaluate policies; the others wait briefly and |
| 7 | + * replay its response without duplicating activity or telemetry. |
| 8 | + */ |
| 9 | +import { createHash } from "node:crypto"; |
| 10 | +import { mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises"; |
| 11 | +import { homedir } from "node:os"; |
| 12 | +import { join } from "node:path"; |
| 13 | +import type { IntegrationType } from "./types"; |
| 14 | + |
| 15 | +const RESULT_TTL_MS = 5 * 60_000; |
| 16 | +const WAIT_TIMEOUT_MS = 12_000; |
| 17 | +const POLL_INTERVAL_MS = 10; |
| 18 | + |
| 19 | +let dedupDir = join(homedir(), ".failproofai", "cache", "hook-invocations"); |
| 20 | + |
| 21 | +export interface HookInvocationResponse { |
| 22 | + exitCode: number; |
| 23 | + stdout: string; |
| 24 | + stderr: string; |
| 25 | +} |
| 26 | + |
| 27 | +export type HookInvocationClaim = |
| 28 | + | { role: "owner"; complete: (response: HookInvocationResponse) => Promise<void>; release: () => Promise<void> } |
| 29 | + | { role: "duplicate"; response: HookInvocationResponse } |
| 30 | + | { role: "independent" }; |
| 31 | + |
| 32 | +function invocationKey( |
| 33 | + eventType: string, |
| 34 | + cli: IntegrationType, |
| 35 | + payload: Record<string, unknown>, |
| 36 | +): string | null { |
| 37 | + if (cli !== "claude") return null; |
| 38 | + const sessionId = payload.session_id; |
| 39 | + const toolUseId = payload.tool_use_id; |
| 40 | + if (typeof sessionId !== "string" || typeof toolUseId !== "string") return null; |
| 41 | + return createHash("sha256").update(`${cli}\0${eventType}\0${sessionId}\0${toolUseId}`).digest("hex"); |
| 42 | +} |
| 43 | + |
| 44 | +async function removeOldEntries(): Promise<void> { |
| 45 | + try { |
| 46 | + const names = await readdir(dedupDir); |
| 47 | + const now = Date.now(); |
| 48 | + await Promise.all(names.map(async (name) => { |
| 49 | + const path = join(dedupDir, name); |
| 50 | + try { |
| 51 | + if (now - (await stat(path)).mtimeMs > RESULT_TTL_MS) await unlink(path); |
| 52 | + } catch { |
| 53 | + // Another hook process may have removed it first. |
| 54 | + } |
| 55 | + })); |
| 56 | + } catch { |
| 57 | + // Cleanup is best-effort and must never delay or block policy evaluation. |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +async function readResponse(path: string): Promise<HookInvocationResponse | null> { |
| 62 | + try { |
| 63 | + const parsed = JSON.parse(await readFile(path, "utf8")) as Partial<HookInvocationResponse>; |
| 64 | + if ( |
| 65 | + typeof parsed.exitCode === "number" |
| 66 | + && typeof parsed.stdout === "string" |
| 67 | + && typeof parsed.stderr === "string" |
| 68 | + ) { |
| 69 | + return parsed as HookInvocationResponse; |
| 70 | + } |
| 71 | + } catch { |
| 72 | + // The owner has not published its response yet. |
| 73 | + } |
| 74 | + return null; |
| 75 | +} |
| 76 | + |
| 77 | +async function readFreshResponse(path: string): Promise<HookInvocationResponse | null> { |
| 78 | + try { |
| 79 | + if (Date.now() - (await stat(path)).mtimeMs > RESULT_TTL_MS) return null; |
| 80 | + } catch { |
| 81 | + return null; |
| 82 | + } |
| 83 | + return readResponse(path); |
| 84 | +} |
| 85 | + |
| 86 | +export async function claimHookInvocation( |
| 87 | + eventType: string, |
| 88 | + cli: IntegrationType, |
| 89 | + payload: Record<string, unknown>, |
| 90 | +): Promise<HookInvocationClaim> { |
| 91 | + const key = invocationKey(eventType, cli, payload); |
| 92 | + if (!key) return { role: "independent" }; |
| 93 | + |
| 94 | + try { |
| 95 | + await mkdir(dedupDir, { recursive: true }); |
| 96 | + void removeOldEntries(); |
| 97 | + const lockPath = join(dedupDir, `${key}.lock`); |
| 98 | + const resultPath = join(dedupDir, `${key}.json`); |
| 99 | + const existingResponse = await readFreshResponse(resultPath); |
| 100 | + if (existingResponse) return { role: "duplicate", response: existingResponse }; |
| 101 | + |
| 102 | + try { |
| 103 | + const handle = await open(lockPath, "wx"); |
| 104 | + await handle.close(); |
| 105 | + const racedResponse = await readFreshResponse(resultPath); |
| 106 | + if (racedResponse) { |
| 107 | + try { await unlink(lockPath); } catch { /* best-effort */ } |
| 108 | + return { role: "duplicate", response: racedResponse }; |
| 109 | + } |
| 110 | + let completed = false; |
| 111 | + return { |
| 112 | + role: "owner", |
| 113 | + complete: async (response) => { |
| 114 | + try { |
| 115 | + const tmpPath = `${resultPath}.${process.pid}.tmp`; |
| 116 | + await writeFile(tmpPath, JSON.stringify(response), "utf8"); |
| 117 | + await rename(tmpPath, resultPath); |
| 118 | + completed = true; |
| 119 | + } catch { |
| 120 | + // Publishing is best-effort; the owner must still return its policy result. |
| 121 | + } finally { |
| 122 | + try { await unlink(lockPath); } catch { /* best-effort */ } |
| 123 | + } |
| 124 | + }, |
| 125 | + release: async () => { |
| 126 | + if (!completed) { |
| 127 | + try { await unlink(lockPath); } catch { /* best-effort */ } |
| 128 | + } |
| 129 | + }, |
| 130 | + }; |
| 131 | + } catch (error) { |
| 132 | + if ((error as NodeJS.ErrnoException).code !== "EEXIST") return { role: "independent" }; |
| 133 | + } |
| 134 | + |
| 135 | + const deadline = Date.now() + WAIT_TIMEOUT_MS; |
| 136 | + while (Date.now() < deadline) { |
| 137 | + const response = await readResponse(resultPath); |
| 138 | + if (response) return { role: "duplicate", response }; |
| 139 | + await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); |
| 140 | + } |
| 141 | + } catch { |
| 142 | + // Deduplication is an optimization. Fail open into normal policy evaluation. |
| 143 | + } |
| 144 | + return { role: "independent" }; |
| 145 | +} |
| 146 | + |
| 147 | +export function setHookInvocationDedupDirForTests(path: string): void { |
| 148 | + dedupDir = path; |
| 149 | +} |
0 commit comments