Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
fix(hooks): do nothing in a repository that is not the project
Erenbaa40fb86ce5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bda12da..66bd13a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Every message now gets a one-line summary of what came of it (`messageSummaries` is on by default, and turned on once for existing setups). Without it, a message that only discussed or advised kept nothing but its title, so the map and search lost what the agent said. Turn it off with `cogit config set messageSummaries false`; it then stays off.### Fixed+- With a hooks folder shared by every repository (a global `core.hooksPath`), cogit's hooks no longer act in repositories that are not the project: a commit there no longer takes the project's `Thought:` trailer, and a push there no longer announces the project's records.- With Husky, cogit's hook blocks no longer vanish for good after `npm install` (Husky rewrites `.husky/_`): the next chat message puts them back. `cogit hooks uninstall` is remembered, so blocks you removed on purpose stay out.- A session the side model left untitled takes its first thread's title (or its first message's) at session end, instead of showing only its id on the map and in `cogit log`; `cogit log` also stops printing such an id twice.diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.tsindex cf59c28..88af92a 100644--- a/packages/cli/src/git-hooks.ts+++ b/packages/cli/src/git-hooks.ts@@ -1,6 +1,8 @@+import { execFile } from "node:child_process";import { existsSync, realpathSync } from "node:fs";-import { chmod, mkdir, readFile, rm, stat } from "node:fs/promises";-import { dirname, join } from "node:path";+import { chmod, mkdir, readFile, realpath, rm, stat } from "node:fs/promises";+import { dirname, join, resolve } from "node:path";+import { promisify } from "node:util";import { findGitRoot, gitHooksDir, resolveCommit } from "./git.js";import { spawnDetachedProcess } from "./hooks/run.js";import { pushIsDryRun } from "./push-command.js";@@ -8,6 +10,11 @@ import { countUnsentRecords } from "./record-sync.js";import { atomicWrite } from "./store/fs.js";import { captureDisabled, projectPaths } from "./store/paths.js";import { loadConfig } from "./store/stores.js";++const execFileAsync = promisify(execFile);+const execGit = (args: string[], opts: { cwd: string; env: NodeJS.ProcessEnv }) =>+ execFileAsync("git", args, opts);+import { addThoughtTrailer } from "./thought.js";/**@@ -336,6 +343,37 @@ async function queueShape(spawn(cli, ["shape", "--commit", commit, "-C", dir], env, projectPaths(dir).detachedLog);}+/** Git's own variables in a hook; a lookup of another repository must not inherit them. */+const GIT_REPO_ENV = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_PREFIX"];++async function commonDir(cwd: string, env: NodeJS.ProcessEnv): Promise<string | undefined> {+ try {+ const { stdout } = await execGit(["rev-parse", "--git-common-dir"], { cwd, env });+ const dir = resolve(cwd, String(stdout).trim());+ return await realpath(dir).catch(() => dir);+ } catch {+ return undefined;+ }+}++/**+ * True when the hook runs in the project's repository (or one of its worktrees).+ * A hooks folder shared by every repository (a global `core.hooksPath`) carries+ * the block of the one project that installed it; in any other repository the+ * block must do nothing, or a commit there takes that project's `Thought:`.+ * Unknown counts as the same, as before.+ */+export async function sameRepository(hookCwd: string, dir: string): Promise<boolean> {+ const clean = Object.fromEntries(+ Object.entries(process.env).filter(([key]) => !GIT_REPO_ENV.includes(key)),+ );+ const [here, project] = await Promise.all([+ commonDir(hookCwd, process.env),+ commonDir(dir, clean),+ ]);+ return here === undefined || project === undefined || here === project;+}+/*** Runs one git hook. A git hook that fails would block the user's commit, so the* CLI calls this inside its own silence: nothing here throws or prints. `args`@@ -351,7 +389,9 @@ export async function runGitHook(spawn: typeof spawnDetachedProcess = spawnDetachedProcess,pushedRefs: () => Promise<string> = async () => "",dryRun: () => boolean = pushIsDryRun,+ hookCwd?: string,): Promise<void> {+ if (hookCwd !== undefined && !(await sameRepository(hookCwd, dir))) return;if (event === "pre-push") {await sendWithPush(dir, env, args[0], await pushedRefs(), spawn, dryRun);return;diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 38baf25..526a9e1 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -48,6 +48,8 @@ export interface ProgramDeps {server?: (env: NodeJS.ProcessEnv) => Promise<string | null>;/** Reads a hook's JSON input; tests pass it directly. */stdin?: () => Promise<string>;+ /** Where a git hook runs; git starts it at the top of its repository. */+ cwd?: () => string;/** Sets the process exit code; tests observe it. */exitCode?: (code: number) => void;}@@ -680,6 +682,9 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =new Date(io.now()),undefined,deps.stdin ?? readStdin,+ undefined,+ // Git runs a hook at the top of the repository it is working in.+ deps.cwd?.() ?? process.cwd(),);} catch {// A hook must never block the commit or the session.diff --git a/packages/cli/test/git-hook-block.test.ts b/packages/cli/test/git-hook-block.test.tsindex d820493..e65ae67 100644--- a/packages/cli/test/git-hook-block.test.ts+++ b/packages/cli/test/git-hook-block.test.ts@@ -7,6 +7,8 @@ import {hookBlock,installGitHook,isShellHook,+ runGitHook,+ sameRepository,withHookBlock,withoutHookBlock,} from "../src/git-hooks.js";@@ -19,7 +21,7 @@ import {readProcess,readPs,} from "../src/push-command.js";-import { tempDir } from "./helpers.js";+import { noGitDir, tempDir } from "./helpers.js";const run = promisify(execFile);@@ -183,3 +185,70 @@ describe("telling a dry-run push apart", () => {expect(pushIsDryRun(() => ({ ppid: 1, args: ["git", "push", "-n"] }))).toBe(true);});});++describe("a hooks folder shared by every repository", () => {+ it("tells the project's repository and its worktrees from any other", async () => {+ const dir = await tempDir();+ const env = { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir };+ const repo = async (name: string): Promise<string> => {+ const path = join(dir, name);+ await run("git", ["init", "-q", "-b", "main", path], { env });+ await run(+ "git",+ [+ "-C",+ path,+ "-c",+ "user.name=A",+ "-c",+ "[email protected]",+ "commit",+ "-q",+ "--allow-empty",+ "-m",+ "init",+ ],+ { env },+ );+ return path;+ };+ const project = await repo("project");+ const other = await repo("other");+ const tree = join(dir, "tree");+ await run("git", ["-C", project, "worktree", "add", "-q", tree, "-b", "wt"], { env });++ expect(await sameRepository(project, project)).toBe(true);+ expect(await sameRepository(join(tree), project)).toBe(true);+ expect(await sameRepository(other, project)).toBe(false);+ // Outside any repository nothing is known: as before, the hook runs.+ expect(await sameRepository(await noGitDir(), project)).toBe(true);++ // Git's own variables in the hook must not make the project look like this repository.+ const saved = process.env.GIT_DIR;+ process.env.GIT_DIR = join(other, ".git");+ try {+ expect(await sameRepository(other, project)).toBe(false);+ } finally {+ if (saved === undefined) delete process.env.GIT_DIR;+ else process.env.GIT_DIR = saved;+ }++ // A hook run from the other repository does nothing at all.+ const started: string[][] = [];+ const spawned = ((_cli: string, args: string[]) => {+ started.push(args);+ }) as never;+ await runGitHook(+ "pre-push",+ project,+ env,+ ["origin", "x"],+ new Date(),+ spawned,+ async () => `refs/heads/main ${"a".repeat(40)} refs/heads/main ${"0".repeat(40)}\n`,+ () => false,+ other,+ );+ expect(started).toEqual([]);+ });+});diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.tsindex 51ea446..e89258e 100644--- a/packages/cli/test/thought.test.ts+++ b/packages/cli/test/thought.test.ts@@ -446,15 +446,23 @@ describe("the thought behind a commit (Story 9.4)", () => {expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);});- it("runs through the CLI's prepare-commit-msg hook", async () => {+ it("runs through the CLI's prepare-commit-msg hook, only in the project's repository", async () => {await writeHead();- const file = await messageFile();- const program = createProgram(() => io);- program.exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });- await program.parseAsync(["hook", "prepare-commit-msg", "--dir", root, file, "message"], {- from: "user",- });- expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);+ const hook = async (cwd: string): Promise<string> => {+ const file = await messageFile();+ const program = createProgram(() => io, { cwd: () => cwd });+ program.exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });+ await program.parseAsync(["hook", "prepare-commit-msg", "--dir", root, file, "message"], {+ from: "user",+ });+ return readMessage(file);+ };+ expect(await hook(root)).toContain(`Thought: ${thoughtOf()}`);+ // A shared hooks folder runs the block in another repository: no trailer there.+ const other = join(dir, "other");+ await mkdir(other, { recursive: true });+ await run("git", ["init", "-q", other]);+ expect(await hook(other)).not.toContain("Thought:");});});