Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

fix(hooks): keep cogit running beside users' own git hooks

Eren8b661bf41845
diff --git a/CHANGELOG.md b/CHANGELOG.md
index adea3ba..d6f51bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Fixed
+- A git hook of your own that ended with `exit 0`, or read the push's input, no longer stops cogit: its block now sits at the top of the hook, hands git's input on to your lines, and adds the `Thought:` trailer after them. Existing hooks move on the next chat message; a Python or Node hook is left alone and `cogit doctor` says so.
+- `git push --dry-run` no longer sends the record (Linux and macOS).
+- After upgrading from a version that committed the record, `cogit doctor` asks you to commit the rewritten `.cogit/.gitignore` too; without it teammates and new clones saw `.cogit/sessions/` in `git status`.
## [1.0.0] - 2026-11-04
### Changed
diff --git a/docs/guide/teams-and-git.md b/docs/guide/teams-and-git.md
index 59664a1..eddfc95 100644
--- a/docs/guide/teams-and-git.md
+++ b/docs/guide/teams-and-git.md
@@ -35,7 +35,7 @@ pages, which also means the record cannot be read there: reading it takes cogit.
- **Sending:** `git push` to `origin` (or your only remote) prints how many records will follow,
and they go in the background once the push has landed. It never slows the push, never asks
- for anything and never fails it. A rejected push sends nothing, and neither does a `--dry-run` with new commits; a `--dry-run` with nothing new to push still sends. What could not
+ for anything and never fails it. A rejected push sends nothing, and neither does `git push --dry-run`: cogit reads it from the running `git` on Linux and macOS. On Windows a `--dry-run` with nothing new to push still sends. What could not
be sent stays queued, the next session start tries again, and `cogit doctor` tells you why.
Pushing to any other remote, such as a deploy target, sends nothing.
- **Receiving:** the first time cogit runs in a clone, it adds one fetch line to that clone's
@@ -65,10 +65,12 @@ delete them. If the repository cannot be reached, nothing is deleted.
### Coming from a version that committed the record
Older versions committed `.cogit/sessions/`. After upgrading, stop tracking them once, in one
-clone, or they keep showing in `git status`:
+clone, or they keep showing in `git status`. The upgrade also rewrote `.cogit/.gitignore`; commit
+it in the same step, or teammates and new clones see `.cogit/sessions/` as untracked:
```bash
git rm -r --cached .cogit/sessions
+git add .cogit/.gitignore
git commit -m "chore: stop tracking the cogit record"
```
@@ -80,14 +82,18 @@ they had, so the repository's size does not shrink. `cogit doctor` reminds you u
## The git hooks
`init` adds a block to three git hooks in your clone (and follows `core.hooksPath`, so Husky
-setups work). The block never fails a commit or a push.
+setups work). The block never fails a commit or a push. It sits right under the first line, so
+an early `exit` in your own lines cannot skip it, and your hook's exit status stays the hook's.
+A hook written in another language (Python, Node) is left alone, and `cogit doctor` says so.
- **`prepare-commit-msg`** adds a `Thought: h<id>` trailer naming the message the commit came
from: the newest message of the current session. It is skipped for merges and squashes, while
a rebase or cherry-pick replays old commits, and when the last message is older than
- `trailerMaxAgeHours` (6 hours), since such a commit is probably not about that message.
+ `trailerMaxAgeHours` (6 hours), since such a commit is probably not about that message. It
+ runs after your own lines, so a tool that rewrites the message (commitizen) keeps it.
- **`post-commit`** starts the commit's Shape in the background.
-- **`pre-push`** sends the session records of a project that shares them.
+- **`pre-push`** sends the session records of a project that shares them. It reads the list of
+ pushed refs git gives the hook and hands it on to your own lines unchanged.
### Rebase and squash
diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts
index 3904c06..abf8d37 100644
--- a/packages/cli/src/commands/doctor.ts
+++ b/packages/cli/src/commands/doctor.ts
@@ -5,10 +5,10 @@ import type { AgentAdapter } from "../agents/index.js";
import { defaultAgent } from "../agents/index.js";
import { compareVersions, versionNotice } from "../cli-version.js";
import { cogitIgnored, findGitRoot, gitHooksDir, gitUserEmail, gitUserName } from "../git.js";
-import { BLOCK_START, GIT_HOOK_EVENTS, hookBlock } from "../git-hooks.js";
+import { BLOCK_START, GIT_HOOK_EVENTS, hookCommandLine, isShellHook } from "../git-hooks.js";
import type { Io } from "../io.js";
import { hashTurns, isRecorded, upgradeSessionIds } from "../messages.js";
-import { recordSyncStatus, trackedRecordFiles } from "../record-sync.js";
+import { cogitGitignoreChanged, recordSyncStatus, trackedRecordFiles } from "../record-sync.js";
import type { Session } from "../schema/session.js";
import { checkHealth } from "../server.js";
import { applyEvents, readEvents } from "../store/events.js";
@@ -310,7 +310,15 @@ const CHECK_SPECS: CheckSpec[] = [
id: "record",
status: "warn",
message: `git still tracks ${tracked} session file${tracked === 1 ? "" : "s"} an older version committed`,
- fix: "git rm -r --cached .cogit/sessions, then commit",
+ fix: "git rm -r --cached .cogit/sessions && git add .cogit/.gitignore, then commit",
+ };
+ if (await cogitGitignoreChanged(ctx.root, ctx.env))
+ return {
+ id: "record",
+ status: "warn",
+ message:
+ "the new .cogit/.gitignore is not committed; teammates see .cogit/sessions/ in git status",
+ fix: "git add .cogit/.gitignore, then commit",
};
const sync = await recordSyncStatus(ctx.root, ctx.env);
if (!sync.sharing)
@@ -497,13 +505,21 @@ async function hookProblems(ctx: DoctorContext): Promise<string[]> {
const problems: string[] = [];
for (const event of GIT_HOOK_EVENTS) {
const text = await readFile(join(dir, event), "utf8").catch(() => undefined);
+ if (text !== undefined && !text.includes(BLOCK_START) && !isShellHook(text)) {
+ problems.push(`the ${event} hook is not a shell script, so cogit cannot add to it`);
+ continue;
+ }
if (text === undefined || !text.includes(BLOCK_START)) {
problems.push(`the ${event} hook is missing`);
continue;
}
const block = /# >>> cogit[\s\S]*?# <<< cogit/.exec(text)?.[0] ?? "";
- const command = hookBlock(event, ctx.root, null).split("\n")[2] ?? "";
- if (!block.split("\n").includes(command)) problems.push(`the ${event} hook is outdated`);
+ // Below the user's lines, an early `exit` there would skip it.
+ const top = text.startsWith("#!") ? text.indexOf("\n") + 1 : 0;
+ const current =
+ block.split("\n").includes(hookCommandLine(event, ctx.root)) &&
+ text.slice(top, text.indexOf(BLOCK_START)).trim() === "";
+ if (!current) problems.push(`the ${event} hook is outdated`);
}
return problems;
}
diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.ts
index e7e6d3f..a131234 100644
--- a/packages/cli/src/git-hooks.ts
+++ b/packages/cli/src/git-hooks.ts
@@ -3,6 +3,7 @@ import { chmod, mkdir, readFile, rm, stat } from "node:fs/promises";
import { join } from "node:path";
import { findGitRoot, gitHooksDir, resolveCommit } from "./git.js";
import { spawnDetachedProcess } from "./hooks/run.js";
+import { pushIsDryRun } from "./push-command.js";
import { countUnsentRecords } from "./record-sync.js";
import { atomicWrite } from "./store/fs.js";
import { captureDisabled, projectPaths } from "./store/paths.js";
@@ -34,30 +35,90 @@ export function currentCliPath(): string | undefined {
}
/**
- * The block `init` adds to a hook; `"$@"` passes git's arguments through. A
- * `cogit` on PATH wins; otherwise the CLI that installed the block runs under
- * `node`; with neither, the hook does nothing and the commit goes on.
+ * The block `init` adds to a hook, at the top so a user line that exits early
+ * (`exit 0`) can never skip it. A `cogit` on PATH wins; otherwise the CLI that
+ * installed the block runs under `node`; with neither, the hook does nothing and
+ * the commit goes on.
+ *
+ * - `pre-push` reads git's stdin itself and hands it back to the lines below,
+ * so a user hook that reads it still gets it and cogit always sees the refs.
+ * - `prepare-commit-msg` runs at exit, after the user's lines: a tool that
+ * rewrites the message file (commitizen) keeps the `Thought:` trailer, and the
+ * user's exit status stays the hook's.
*/
export function hookBlock(
event: string,
projectRoot: string,
cliPath: string | null = currentCliPath() ?? null,
): string {
+ if (event === "pre-push") {
+ return [
+ BLOCK_START,
+ "cogit_stdin=$(cat)",
+ ...cogitCall(event, projectRoot, cliPath, `printf '%s' "$cogit_stdin" | `, ""),
+ 'if [ -n "$cogit_stdin" ]; then exec <<COGIT_STDIN',
+ "$cogit_stdin",
+ "COGIT_STDIN",
+ "else exec </dev/null; fi",
+ BLOCK_END,
+ ].join("\n");
+ }
+ if (event === "prepare-commit-msg") {
+ return [
+ BLOCK_START,
+ "cogit_msg=${1-} cogit_source=${2-}",
+ "cogit_thought() {",
+ ...cogitCall(event, projectRoot, cliPath, "", " "),
+ "}",
+ `trap 'cogit_status=$?; cogit_thought "$cogit_msg" "$cogit_source"; exit $cogit_status' EXIT`,
+ BLOCK_END,
+ ].join("\n");
+ }
+ return [BLOCK_START, ...cogitCall(event, projectRoot, cliPath, "", ""), BLOCK_END].join("\n");
+}
+
+/** The `cogit` / `node <cli>` branches that run one hook; `"$@"` passes git's arguments. */
+function cogitCall(
+ event: string,
+ projectRoot: string,
+ cliPath: string | null,
+ pipe: string,
+ indent: string,
+): string[] {
const args = `hook ${event} --dir ${shellQuote(projectRoot)} "$@"`;
- const lines = [
- BLOCK_START,
- "if command -v cogit >/dev/null 2>&1; then",
- ` cogit ${args} || true`,
- ];
+ const lines = ["if command -v cogit >/dev/null 2>&1; then", ` ${pipe}cogit ${args} || true`];
if (cliPath !== null) {
const cli = shellQuote(cliPath);
lines.push(
`elif command -v node >/dev/null 2>&1 && [ -f ${cli} ]; then`,
- ` node ${cli} ${args} || true`,
+ ` ${pipe}node ${cli} ${args} || true`,
);
}
- lines.push("fi", BLOCK_END);
- return lines.join("\n");
+ lines.push("fi");
+ return lines.map((line) => `${indent}${line}`);
+}
+
+/**
+ * The line of a block that names the project and the hook command; doctor
+ * compares only this one, since the fallback CLI path differs between installs.
+ */
+export function hookCommandLine(event: string, projectRoot: string): string {
+ return (
+ hookBlock(event, projectRoot, null)
+ .split("\n")
+ .find((line) => line.includes("cogit hook ")) ?? ""
+ );
+}
+
+/**
+ * True when cogit can add its block: a new or empty file, one without a
+ * shebang, or a `sh`-family script. A Python or Node hook is left alone, since
+ * shell lines would break it; doctor reports it.
+ */
+export function isShellHook(text: string): boolean {
+ const first = text.split("\n", 1)[0] ?? "";
+ if (!first.startsWith("#!")) return true;
+ return /(^|[/\s])(sh|bash|dash|zsh|ksh|ash)(\s|$)/.test(first.slice(2).trim());
}
/** Single quotes for the shell, with the embedded single quote escaped. */
@@ -65,20 +126,28 @@ function shellQuote(value: string): string {
return `'${value.replaceAll("'", `'\\''`)}'`;
}
-/** Replaces an existing cogit block, or appends one, keeping the file's own content. */
+/**
+ * Puts the cogit block right under the shebang, keeping the file's own content.
+ * An older block anywhere in the file (past versions appended it) moves up.
+ */
export function withHookBlock(text: string, block: string): string {
- const pattern = /# >>> cogit[\s\S]*?# <<< cogit/g;
- if (pattern.test(text)) return text.replace(pattern, block);
+ const rest = text.includes(BLOCK_START) ? withoutHookBlock(text) : text;
// An empty file still has to be runnable: git execs the hook directly.
- if (text === "") return `#!/bin/sh\n\n${block}\n`;
- const sep = text.endsWith("\n") ? "" : "\n";
- return `${text}${sep}\n${block}\n`;
+ if (rest === "") return `#!/bin/sh\n${block}\n`;
+ if (!rest.startsWith("#!")) return `${block}\n${rest}`;
+ const cut = rest.indexOf("\n");
+ if (cut === -1) return `${rest}\n${block}\n`;
+ return `${rest.slice(0, cut + 1)}${block}\n${rest.slice(cut + 1)}`;
}
-/** Removes the marked block and the blank separator `withHookBlock` added. */
+/**
+ * Removes the marked block, and the blank line older versions put before it
+ * when they appended it; the user's own blank lines stay.
+ */
export function withoutHookBlock(text: string): string {
- const next = text.replace(/# >>> cogit\n[\s\S]*?# <<< cogit\n?/, "");
- return next.endsWith("\n\n") ? next.slice(0, -1) : next;
+ return text.replace(/(\n\n)?# >>> cogit\n[\s\S]*?# <<< cogit\n?/, (_all, gap) =>
+ gap === undefined ? "" : "\n",
+ );
}
/** True when what is left is only the shebang `installGitHook` wrote itself. */
@@ -103,8 +172,8 @@ export async function installGitHook(root: string, event: string): Promise<boole
() => false,
);
const current = exists ? await readFile(file, "utf8") : "";
- const block = hookBlock(event, root);
- const next = exists ? withHookBlock(current, block) : `#!/bin/sh\n\n${block}\n`;
+ if (!isShellHook(current)) return false;
+ const next = withHookBlock(current, hookBlock(event, root));
if (exists && next === current) return false;
await atomicWrite(file, next);
await chmod(file, 0o755);
@@ -206,8 +275,10 @@ async function sendWithPush(
pushedRemote: string | undefined,
pushedRefs: string,
spawn: typeof spawnDetachedProcess,
+ dryRun: () => boolean,
): Promise<void> {
if (captureDisabled(env)) return;
+ if (dryRun()) return;
const lines = pushedRefs.split("\n").filter(Boolean);
const going = lines
.map((line) => line.split(" "))
@@ -268,9 +339,10 @@ export async function runGitHook(
now: Date = new Date(),
spawn: typeof spawnDetachedProcess = spawnDetachedProcess,
pushedRefs: () => Promise<string> = async () => "",
+ dryRun: () => boolean = pushIsDryRun,
): Promise<void> {
if (event === "pre-push") {
- await sendWithPush(dir, env, args[0], await pushedRefs(), spawn);
+ await sendWithPush(dir, env, args[0], await pushedRefs(), spawn, dryRun);
return;
}
if (event === "post-commit") {
diff --git a/packages/cli/src/push-command.ts b/packages/cli/src/push-command.ts
new file mode 100644
index 0000000..f2e5b71
--- /dev/null
+++ b/packages/cli/src/push-command.ts
@@ -0,0 +1,100 @@
+import { spawnSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { basename } from "node:path";
+
+/**
+ * Git gives a `pre-push` hook no sign of `--dry-run`, so the `git push` that ran
+ * the hook is read from the process tree: the hook's shell, then git. Linux reads
+ * `/proc`, macOS asks `ps`; elsewhere (Windows) nothing is found and the push
+ * counts as real, as before.
+ */
+
+/** One process: its parent's pid and its argument list. */
+export interface ProcessInfo {
+ ppid: number;
+ args: string[];
+}
+
+export type ReadProcess = (pid: number) => ProcessInfo | undefined;
+
+/** How far up to look: cogit ← its shell (or a subshell) ← hook shell ← git. */
+const MAX_DEPTH = 6;
+
+/** The arguments of the nearest `git … push …` above this process, if any. */
+export function findPushArgs(startPid: number, read: ReadProcess): string[] | undefined {
+ let pid = startPid;
+ for (let depth = 0; depth < MAX_DEPTH && pid > 1; depth++) {
+ const info = read(pid);
+ if (info === undefined) return undefined;
+ const name = basename(info.args[0] ?? "").replace(/\.exe$/i, "");
+ if (name === "git" && info.args.includes("push")) return info.args;
+ pid = info.ppid;
+ }
+ return undefined;
+}
+
+/** `git push` options that take the next word as their value. */
+const VALUE_OPTIONS = new Set(["--push-option", "--repo", "--receive-pack", "--exec"]);
+
+/** True when these `git … push …` arguments ask for `--dry-run` (or `-n`). */
+export function isDryRun(args: readonly string[]): boolean {
+ const start = args.indexOf("push");
+ if (start === -1) return false;
+ for (let i = start + 1; i < args.length; i++) {
+ const arg = args[i] ?? "";
+ if (arg === "--") return false;
+ if (arg === "--dry-run") return true;
+ if (VALUE_OPTIONS.has(arg)) {
+ i++;
+ continue;
+ }
+ if (!/^-[^-]/.test(arg)) continue;
+ // A bundle of short flags, such as `-fn`; `-o` takes the rest (or the next word).
+ for (let c = 1; c < arg.length; c++) {
+ if (arg[c] === "n") return true;
+ if (arg[c] === "o") {
+ if (c === arg.length - 1) i++;
+ break;
+ }
+ }
+ }
+ return false;
+}
+
+/** True when the `git push` running this hook is a dry run; false when unknown. */
+export function pushIsDryRun(read: ReadProcess = (pid) => readProcess(pid)): boolean {
+ const args = findPushArgs(process.ppid, read);
+ return args !== undefined && isDryRun(args);
+}
+
+export function readProcess(
+ pid: number,
+ platform: NodeJS.Platform = process.platform,
+): ProcessInfo | undefined {
+ if (platform === "linux") return readProc(pid);
+ if (platform === "darwin") return readPs(pid);
+ return undefined;
+}
+
+export function readProc(pid: number): ProcessInfo | undefined {
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ // The command name sits in parentheses and may hold spaces: read after the last one.
+ const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
+ const args = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").filter(Boolean);
+ return Number.isInteger(ppid) ? { ppid, args } : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** `ps` joins the arguments with spaces; enough to spot `push` and its flags. */
+export function readPs(pid: number): ProcessInfo | undefined {
+ const out = spawnSync("ps", ["-o", "ppid=,args=", "-p", String(pid)], {
+ encoding: "utf8",
+ timeout: 1000,
+ });
+ const match = /^(\d+)\s+([\s\S]*)$/.exec((out.stdout ?? "").trim());
+ if (out.status !== 0 || match === null) return undefined;
+ return { ppid: Number(match[1]), args: (match[2] ?? "").trim().split(/\s+/) };
+}
diff --git a/packages/cli/src/record-sync.ts b/packages/cli/src/record-sync.ts
index b393c96..afab804 100644
--- a/packages/cli/src/record-sync.ts
+++ b/packages/cli/src/record-sync.ts
@@ -629,6 +629,20 @@ export async function trackedRecordFiles(root: string, env: NodeJS.ProcessEnv):
return result.stdout.toString("utf8").split("\n").filter(Boolean).length;
}
+/**
+ * True when the committed `.cogit/.gitignore` is older than the one here (an
+ * upgrade rewrote it): until it is committed, teammates and new clones see
+ * `.cogit/sessions/` as untracked, and one `git add -A` commits the record again.
+ */
+export async function cogitGitignoreChanged(
+ root: string,
+ env: NodeJS.ProcessEnv,
+): Promise<boolean> {
+ const result = await runGit(root, ["status", "--porcelain", "--", ".cogit/.gitignore"], env);
+ const line = result.stdout.toString("utf8").split("\n")[0] ?? "";
+ return line !== "" && !line.startsWith("??");
+}
+
export interface RecordSyncStatus {
sharing: boolean;
remote?: string;
diff --git a/packages/cli/test/doctor.test.ts b/packages/cli/test/doctor.test.ts
index dfe8e55..3d274d4 100644
--- a/packages/cli/test/doctor.test.ts
+++ b/packages/cli/test/doctor.test.ts
@@ -257,6 +257,21 @@ describe("doctor", () => {
`#!/bin/sh\n\n${hookBlock("prepare-commit-msg", root, "/elsewhere/cogit/dist/cli.js")}\n`,
);
expect((await check(root, "project")).status).toBe("ok");
+ // Below the user's lines (as older versions appended it), an `exit 0` skips it.
+ await writeFile(
+ join(root, ".git", "hooks", "prepare-commit-msg"),
+ `#!/bin/sh\nexit 0\n\n${hookBlock("prepare-commit-msg", root)}\n`,
+ );
+ expect((await check(root, "project")).message).toContain("prepare-commit-msg hook is outdated");
+ await writeFile(join(root, ".git", "hooks", "prepare-commit-msg"), "#!/usr/bin/env python3\n");
+ expect((await check(root, "project")).message).toContain(
+ "prepare-commit-msg hook is not a shell script",
+ );
+ await writeFile(
+ join(root, ".git", "hooks", "prepare-commit-msg"),
+ `#!/bin/sh\n${hookBlock("prepare-commit-msg", root)}\n`,
+ );
+ expect((await check(root, "project")).status).toBe("ok");
await writeFile(join(root, ".cogit", "project.json"), "{ not json");
const broken = await check(root, "project");
diff --git a/packages/cli/test/git-hook-block.test.ts b/packages/cli/test/git-hook-block.test.ts
new file mode 100644
index 0000000..d820493
--- /dev/null
+++ b/packages/cli/test/git-hook-block.test.ts
@@ -0,0 +1,185 @@
+import { execFile } from "node:child_process";
+import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ hookBlock,
+ installGitHook,
+ isShellHook,
+ withHookBlock,
+ withoutHookBlock,
+} from "../src/git-hooks.js";
+import {
+ findPushArgs,
+ isDryRun,
+ type ProcessInfo,
+ pushIsDryRun,
+ readProc,
+ readProcess,
+ readPs,
+} from "../src/push-command.js";
+import { tempDir } from "./helpers.js";
+
+const run = promisify(execFile);
+
+/**
+ * The block under a real `git push` / `git commit`, with a stub `cogit` on PATH
+ * that logs what it was given: the user's own hook lines must not be able to
+ * skip it or starve it of git's stdin.
+ */
+describe("the cogit block in a user's hook", () => {
+ let dir: string;
+ let root: string;
+ let log: string;
+ let env: NodeJS.ProcessEnv;
+
+ const git = async (...args: string[]): Promise<{ stdout: string; stderr: string }> =>
+ run("git", ["-C", root, ...args], { env });
+
+ const hook = async (event: string, userLines: string): Promise<void> => {
+ const file = join(root, ".git", "hooks", event);
+ await writeFile(file, `#!/bin/sh\n${userLines}`);
+ await chmod(file, 0o755);
+ await writeFile(
+ file,
+ withHookBlock(await readFile(file, "utf8"), hookBlock(event, root, null)),
+ );
+ };
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "repo");
+ log = join(dir, "cogit.log");
+ const bin = join(dir, "bin");
+ await mkdir(bin);
+ // Logs its arguments and stdin; for prepare-commit-msg it appends a trailer.
+ await writeFile(
+ join(bin, "cogit"),
+ [
+ "#!/bin/sh",
+ `echo "args: $*" >> '${log}'`,
+ `[ "$2" = pre-push ] && { echo "stdin: $(cat)" >> '${log}'; }`,
+ `[ "$2" = prepare-commit-msg ] && printf '\\nThought: h123456\\n' >> "$5"`,
+ "exit 0",
+ ].join("\n"),
+ );
+ await chmod(join(bin, "cogit"), 0o755);
+ env = {
+ ...process.env,
+ PATH: `${bin}:${process.env.PATH ?? ""}`,
+ GIT_CONFIG_NOSYSTEM: "1",
+ HOME: dir,
+ GIT_AUTHOR_NAME: "A",
+ GIT_AUTHOR_EMAIL: "[email protected]",
+ GIT_COMMITTER_NAME: "A",
+ GIT_COMMITTER_EMAIL: "[email protected]",
+ };
+ await run("git", ["init", "-q", "--bare", join(dir, "remote.git")], { env });
+ await run("git", ["init", "-q", "-b", "main", root], { env });
+ await git("remote", "add", "origin", join(dir, "remote.git"));
+ await writeFile(join(root, "a.txt"), "a\n");
+ await git("add", "a.txt");
+ await git("commit", "-qm", "first");
+ });
+
+ it("runs before a user pre-push hook that exits early and hands it git's stdin", async () => {
+ const seen = join(dir, "user.log");
+ await hook("pre-push", `cat > '${seen}'\nexit 0\necho never\n`);
+ await git("push", "-q", "origin", "main");
+ const sha = (await git("rev-parse", "HEAD")).stdout.trim();
+ const logged = await readFile(log, "utf8");
+ expect(logged).toContain(`args: hook pre-push --dir ${root} origin`);
+ expect(logged).toContain(`stdin: refs/heads/main ${sha} refs/heads/main`);
+ expect(await readFile(seen, "utf8")).toBe(
+ `refs/heads/main ${sha} refs/heads/main ${"0".repeat(40)}\n`,
+ );
+ });
+
+ it("keeps the user's exit status, so their hook can still stop a push", async () => {
+ await hook("pre-push", "exit 1\n");
+ await expect(git("push", "-q", "origin", "main")).rejects.toThrow();
+ expect(await readFile(log, "utf8")).toContain("args: hook pre-push");
+ });
+
+ it("adds the Thought trailer after a user prepare-commit-msg hook that rewrites and exits", async () => {
+ await hook("prepare-commit-msg", `echo "rewritten by the user" > "$1"\nexit 0\n`);
+ await writeFile(join(root, "b.txt"), "b\n");
+ await git("add", "b.txt");
+ await git("commit", "-qm", "original");
+ const message = (await git("log", "-1", "--format=%B")).stdout;
+ expect(message).toContain("rewritten by the user");
+ expect(message).toContain("Thought: h123456");
+ });
+
+ it("keeps a failing prepare-commit-msg hook failing", async () => {
+ await hook("prepare-commit-msg", "exit 3\n");
+ await writeFile(join(root, "c.txt"), "c\n");
+ await git("add", "c.txt");
+ await expect(git("commit", "-qm", "blocked")).rejects.toThrow();
+ });
+
+ it("moves a block older versions appended to the top, and takes it out cleanly", () => {
+ const user = "#!/bin/sh\necho mine\n\n";
+ const block = hookBlock("post-commit", "/p", null);
+ const appended = `${user}\n${block}\n`;
+ const moved = withHookBlock(appended, block);
+ expect(moved).toBe(`#!/bin/sh\n${block}\necho mine\n\n`);
+ expect(withHookBlock(moved, block)).toBe(moved);
+ // The user's own trailing blank line stays.
+ expect(withoutHookBlock(moved)).toBe(user);
+ });
+
+ it("leaves a hook written in another language alone", async () => {
+ const file = join(root, ".git", "hooks", "pre-push");
+ const python = "#!/usr/bin/env python3\nimport sys\n";
+ await writeFile(file, python);
+ expect(await installGitHook(root, "pre-push")).toBe(false);
+ expect(await readFile(file, "utf8")).toBe(python);
+ expect(isShellHook("#!/usr/bin/env bash\n")).toBe(true);
+ expect(isShellHook("#!/bin/sh -e\n")).toBe(true);
+ expect(isShellHook("echo no shebang\n")).toBe(true);
+ expect(isShellHook("#!/usr/bin/env node\n")).toBe(false);
+ });
+});
+
+describe("telling a dry-run push apart", () => {
+ it("reads --dry-run and -n, also bundled, but not option values or refspecs", () => {
+ expect(isDryRun(["git", "push", "--dry-run", "origin", "main"])).toBe(true);
+ expect(isDryRun(["git", "push", "-n"])).toBe(true);
+ expect(isDryRun(["git", "-c", "a=b", "push", "-fn"])).toBe(true);
+ expect(isDryRun(["/usr/libexec/git-core/git", "push", "--dry-run"])).toBe(true);
+ expect(isDryRun(["git", "push"])).toBe(false);
+ expect(isDryRun(["git", "push", "origin", "main"])).toBe(false);
+ expect(isDryRun(["git", "push", "-o", "-n"])).toBe(false);
+ expect(isDryRun(["git", "push", "-onotify"])).toBe(false);
+ expect(isDryRun(["git", "push", "--push-option", "-n"])).toBe(false);
+ expect(isDryRun(["git", "push", "--", "-n"])).toBe(false);
+ });
+
+ it("finds the git push above the hook's shell, and gives up on an unreadable tree", () => {
+ const tree: Record<number, ProcessInfo> = {
+ 30: { ppid: 20, args: ["sh", "-c", "pipeline"] },
+ 20: { ppid: 10, args: ["/bin/sh", ".git/hooks/pre-push", "origin"] },
+ 10: { ppid: 1, args: ["git", "push", "--dry-run"] },
+ };
+ expect(findPushArgs(30, (pid) => tree[pid])).toEqual(["git", "push", "--dry-run"]);
+ expect(findPushArgs(20, () => undefined)).toBeUndefined();
+ const noGit: Record<number, ProcessInfo> = { 5: { ppid: 1, args: ["bash"] } };
+ expect(findPushArgs(5, (pid) => noGit[pid])).toBeUndefined();
+ });
+
+ it("reads a real process on Linux and through ps, and nothing on other systems", () => {
+ for (const info of [readProc(process.pid), readProcess(process.pid, "darwin")]) {
+ expect(info?.ppid).toBe(process.ppid);
+ expect(info?.args.join(" ")).toContain("node");
+ }
+ expect(readPs(process.pid)?.ppid).toBe(process.ppid);
+ expect(readProc(2 ** 30)).toBeUndefined();
+ expect(readPs(2 ** 30)).toBeUndefined();
+ expect(readProcess(process.pid, "win32")).toBeUndefined();
+ // Under vitest no git push is running, so the push counts as real.
+ expect(pushIsDryRun()).toBe(false);
+ expect(pushIsDryRun(() => ({ ppid: 1, args: ["git", "push", "-n"] }))).toBe(true);
+ });
+});
diff --git a/packages/cli/test/record-sync.test.ts b/packages/cli/test/record-sync.test.ts
index 2ca1e24..f87f6d0 100644
--- a/packages/cli/test/record-sync.test.ts
+++ b/packages/cli/test/record-sync.test.ts
@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it } from "vitest";
import { doctor } from "../src/commands/doctor.js";
import { init } from "../src/commands/init.js";
import { pruneCutoff, pruneRecords } from "../src/commands/prune.js";
+import { cogitGitignore } from "../src/git.js";
import { installGitHooks, runGitHook } from "../src/git-hooks.js";
import { runHook } from "../src/hooks/run.js";
import { prepareRecords } from "../src/record-prepare.js";
@@ -361,6 +362,17 @@ describe("the record on its own refs", () => {
await hook("origin", `(delete) ${zero} refs/heads/old ${sha}\n`);
await hook("origin", "");
await runGitHook("pre-push", alice, env, ["deploy", remote], new Date(T0), spawned);
+ // `git push --dry-run` sends nothing, even with new code in the push.
+ await runGitHook(
+ "pre-push",
+ alice,
+ env,
+ ["origin", remote],
+ new Date(T0),
+ spawned,
+ async () => `refs/heads/main ${sha} refs/heads/main ${zero}\n`,
+ () => true,
+ );
} finally {
process.stderr.write = stderr;
}
@@ -547,6 +559,22 @@ describe("the record on its own refs", () => {
const check = report.checks.find((item) => item.id === "record");
expect(check?.status).toBe("warn");
expect(check?.fix).toContain("git rm -r --cached .cogit/sessions");
+ expect(check?.fix).toContain("git add .cogit/.gitignore");
+
+ // Untracked, but the rewritten .cogit/.gitignore never reached the commit.
+ const ignore = join(alice, ".cogit", ".gitignore");
+ await git(alice, "rm", "-q", "--cached", projectPaths(alice).session("old"));
+ await writeFile(ignore, "*\n!.gitignore\n!project.json\n!sessions/\n");
+ await git(alice, "add", "-f", ignore);
+ await git(alice, "commit", "-qm", "chore: stop tracking");
+ await writeFile(ignore, cogitGitignore());
+ const pending = await doctor({ dir: alice, io: fakeIo(env), json: false } as never);
+ const stale = pending.checks.find((item) => item.id === "record");
+ expect(stale?.status).toBe("warn");
+ expect(stale?.fix).toBe("git add .cogit/.gitignore, then commit");
+ await git(alice, "commit", "-qam", "chore: new ignore rules");
+ const done = await doctor({ dir: alice, io: fakeIo(env), json: false } as never);
+ expect(done.checks.find((item) => item.id === "record")?.status).toBe("ok");
});
it("reports a failed send and a failed download in doctor", async () => {
diff --git a/packages/cli/test/session-git.test.ts b/packages/cli/test/session-git.test.ts
index 15d4f0a..515bf27 100644
--- a/packages/cli/test/session-git.test.ts
+++ b/packages/cli/test/session-git.test.ts
@@ -184,8 +184,8 @@ describe("ignore files and git hooks", () => {
await chmod(file, 0o755);
expect(await installGitHook(root, "pre-commit")).toBe(true);
const text = await readFile(file, "utf8");
- expect(text.startsWith("#!/bin/sh\necho user-hook\n")).toBe(true);
- expect(text).toContain(hookBlock("pre-commit", root));
+ // Under the shebang, so an early `exit` in the user's lines cannot skip it.
+ expect(text).toBe(`#!/bin/sh\n${hookBlock("pre-commit", root)}\necho user-hook\n`);
expect(await installGitHook(root, "pre-commit")).toBe(false);
});
diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.ts
index fa5b849..5a28888 100644
--- a/packages/cli/test/thought.test.ts
+++ b/packages/cli/test/thought.test.ts
@@ -512,7 +512,7 @@ describe("the thought behind a commit (Story 9.4)", () => {
"pre-push",
]);
expect(await readFile(preCommit, "utf8")).toBe(
- `${userHook}\n${hookBlock("pre-push", root)}\n`,
+ `#!/bin/sh\n${hookBlock("pre-push", root)}\necho user-hook\n`,
);
expect(await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8")).toContain(
"cogit hook prepare-commit-msg",