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(git): make the Thought trailer follow the committing session

Eren29405f288163
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1e753b7..93ff641 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A message's details list its commits and changed files as tidy rows: each commit shows its short hash, its Conventional Commits type as a coloured badge (feat, fix, docs…), its scope and description, and each file its name in bold with its folder beside it; both headings carry a count.
### Fixed
+- The `Thought:` trailer follows the session that made the commit: when the agent names it (`CLAUDE_CODE_SESSION_ID`, set in every Bash and hook subprocess), `prepare-commit-msg` uses that session's newest message and ignores `.cogit/HEAD`, so two sessions sharing one working tree no longer stamp each other's thought on a commit; a named session with no readable transcript gets no trailer (never a HEAD fallback), and a human commit in a terminal still uses the fresh `.cogit/HEAD` as before. `docs/format.md` describes the three cases.
- A message row's commit tags wrap two to a line instead of being cut off at the row's edge, and the row grows to hold them.
- The git hooks work without a `cogit` on PATH (a plugin-only install): the hook block falls back to the CLI that installed it, run with `node`, and does nothing — no "command not found" — when neither is there; each prompt points an existing block at the current CLI, so a plugin update does not break it. `cogit hooks install` adds or refreshes the blocks by hand.
- The `Thought:` trailer is added in every project, also when the record stays out of git, so `blame` and `show <sha>` follow the exact link locally; only the record staging follows the commit policy. `init`, `cogit config git` and the rename migration install the hooks for both policies.
diff --git a/docs/format.md b/docs/format.md
index 99bf0a0..0e00fd5 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -228,7 +228,8 @@ holds one or more JSON lines:
and deletes it.
- `HEAD`: written by the `UserPromptSubmit` hook, local and ignored:
`{sessionId, transcriptPath?, at?}`. It names the session the next code commit
- carries (see the trailer below). A missing or stale `HEAD` means "no trailer".
+ from a terminal carries (see the trailer below). A missing or stale `HEAD`
+ means "no trailer".
## The `Thought:` trailer
@@ -240,12 +241,23 @@ feat(auth): add the login form
Thought: h3f9a2c1b0d4
```
-The git `prepare-commit-msg` hook adds it with `git interpret-trailers` when
-`.cogit/HEAD` is fresh (within `trailerMaxAgeHours`, default 6) and the
-transcript is readable; it uses the newest user message of that session. It is
-skipped for merge and squash commits, a local-only record (`gitPolicy: ignore`),
-and when the trailer is already present (`--amend`). A failure never blocks the
-commit.
+The git `prepare-commit-msg` hook adds it with `git interpret-trailers`, always
+naming the newest user message of the session that made the commit:
+
+1. When the agent names the session in the hook's environment (Claude Code sets
+ `CLAUDE_CODE_SESSION_ID` in every Bash and hook subprocess), that session's
+ transcript is used and `.cogit/HEAD` is ignored — two sessions in one working
+ tree each carry their own message.
+2. When the variable is set but that session has no readable transcript (a
+ `--continue` whose id moved, a session of another project), no trailer is
+ added. cogit never falls back to `.cogit/HEAD` here: it may name the other
+ session.
+3. When no session is named (a human commit in a terminal), `.cogit/HEAD` is
+ used when it is fresh (within `trailerMaxAgeHours`, default 6) and its
+ transcript is readable.
+
+It is skipped for merge and squash commits and when the trailer is already
+present (`--amend`). A failure never blocks the commit.
Readers must not trust the trailer alone: at read time cogit reads the trailers
back from `git log` (`%(trailers:key=Thought,valueonly)`) and attaches those
diff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.ts
index 49c7e6c..026504a 100644
--- a/packages/cli/src/agents/claude/index.ts
+++ b/packages/cli/src/agents/claude/index.ts
@@ -32,6 +32,7 @@ export const claude: AgentAdapter = {
projectDirEnv: "CLAUDE_PROJECT_DIR",
pluginRootEnv: "CLAUDE_PLUGIN_ROOT",
sessionIdEnv: "CLAUDE_SESSION_ID",
+ commitSessionEnv: "CLAUDE_CODE_SESSION_ID",
defaultRetention: CLAUDE_DEFAULT_RETENTION,
configDir: claudeConfigDir,
diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.ts
index 7280d6d..0f44ede 100644
--- a/packages/cli/src/agents/types.ts
+++ b/packages/cli/src/agents/types.ts
@@ -85,6 +85,12 @@ export interface AgentAdapter {
readonly pluginRootEnv: string;
/** Env var the skill and commands use for the current session id. */
readonly sessionIdEnv: string;
+ /**
+ * Env var the agent sets in a shell it starts, naming the session that shell
+ * belongs to. `prepare-commit-msg` reads it so a commit carries its own
+ * session's message even when another session shares the working tree.
+ */
+ readonly commitSessionEnv: string;
/** The agent's own default transcript retention, in days. */
readonly defaultRetention: number;
diff --git a/packages/cli/src/thought.ts b/packages/cli/src/thought.ts
index 8416556..bfc875b 100644
--- a/packages/cli/src/thought.ts
+++ b/packages/cli/src/thought.ts
@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";
import { access } from "node:fs/promises";
import { isAbsolute, resolve } from "node:path";
import { promisify } from "node:util";
-import { defaultAgent } from "./agents/index.js";
+import { type AgentAdapter, defaultAgent } from "./agents/index.js";
import { findGitRoot } from "./git.js";
import { messageHash } from "./messages.js";
import type { Session } from "./schema/session.js";
@@ -15,9 +15,10 @@ const exec = promisify(execFile);
/**
* The link between a code commit and the thought behind it (Story 9.4). A git
* `prepare-commit-msg` hook writes a `Thought: h…` trailer naming the newest user
- * message of the session in `.cogit/HEAD`; at read time the trailers are read
- * back from `git log`, so the link survives a rebase or a fresh clone and never
- * depends on the agent remembering a rule.
+ * message of the session that made the commit (Story 10.6: the session the
+ * agent's shell names, else the one in `.cogit/HEAD`); at read time the trailers
+ * are read back from `git log`, so the link survives a rebase or a fresh clone
+ * and never depends on the agent remembering a rule.
*/
/** The trailer key git and cogit share. */
@@ -54,21 +55,61 @@ function messagePath(file: string): string {
return isAbsolute(file) ? file : resolve(process.cwd(), file);
}
+/** The newest user message of a transcript, as the trailer's value. */
+async function newestThought(
+ agent: AgentAdapter,
+ transcript: string,
+ sessionId: string,
+): Promise<string | undefined> {
+ const turns = await agent.readConversation(transcript);
+ const newest = turns.at(-1);
+ return newest === undefined ? undefined : messageHash(sessionId, newest);
+}
+
+/** Writes the trailer into git's message file, keeping one an `--amend` carried. */
+async function writeTrailer(messageFile: string, value: string): Promise<void> {
+ await exec("git", [
+ "interpret-trailers",
+ "--in-place",
+ "--if-exists",
+ "doNothing",
+ "--trailer",
+ `${THOUGHT_TRAILER}: ${value}`,
+ "--",
+ messagePath(messageFile),
+ ]);
+}
+
/**
- * Adds the `Thought:` trailer to the prepared commit message (Story 9.4). Skip
- * merges and squashes, a missing or stale `.cogit/HEAD` and an unreadable
- * transcript. `--if-exists doNothing` keeps
- * a trailer an `--amend` already carried. A failure is the caller's to swallow:
- * this never blocks the commit.
+ * Adds the `Thought:` trailer to the prepared commit message (Stories 9.4, 10.6).
+ * The session that made the commit wins: when the agent names it in the
+ * environment (a shell it started, `CLAUDE_CODE_SESSION_ID`), only that
+ * session's transcript counts, so two sessions in one working tree cannot take
+ * each other's message. A named session with no readable transcript gets no
+ * trailer — never a fallback to `.cogit/HEAD`, which may be another session. With
+ * no name (a human commit in a terminal) the fresh `.cogit/HEAD` is used.
+ * Merges, squashes and an unreadable transcript are skipped, and a failure is
+ * the caller's to swallow: this never blocks the commit.
*/
export async function addThoughtTrailer(opts: TrailerOptions): Promise<boolean> {
const env = opts.env ?? process.env;
if (captureDisabled(env)) return false;
if (opts.source === "merge" || opts.source === "squash") return false;
+ const agent = defaultAgent();
+
+ const named = (env[agent.commitSessionEnv] ?? "").trim();
+ if (named !== "") {
+ const transcript = await agent.findTranscript(named, env);
+ if (transcript === null) return false;
+ const value = await newestThought(agent, transcript, named);
+ if (value === undefined) return false;
+ await writeTrailer(opts.messageFile, value);
+ return true;
+ }
+
// Every policy gets the trailer: with the ignore policy the record stays on this
// machine, but `blame` and `show <sha>` here still follow the exact link.
const root = resolve(opts.dir);
-
const head = await readSessionHead(root);
if (head === undefined || head.at === undefined) return false;
const written = Date.parse(head.at);
@@ -78,28 +119,15 @@ export async function addThoughtTrailer(opts: TrailerOptions): Promise<boolean>
// A little clock skew is fine; a cutoff that passed (or a future date) is not.
if (age > config.trailerMaxAgeHours * 3_600_000 || age < -5 * 60_000) return false;
- const agent = defaultAgent();
const transcript =
head.transcriptPath !== undefined && (await readable(head.transcriptPath))
? head.transcriptPath
: await agent.findTranscript(head.sessionId, env);
if (transcript === null) return false;
- const turns = await agent.readConversation(transcript);
- const newest = turns.at(-1);
- if (newest === undefined) return false;
-
- const file = messagePath(opts.messageFile);
- await exec("git", [
- "interpret-trailers",
- "--in-place",
- "--if-exists",
- "doNothing",
- "--trailer",
- `${THOUGHT_TRAILER}: ${messageHash(head.sessionId, newest)}`,
- "--",
- file,
- ]);
+ const value = await newestThought(agent, transcript, head.sessionId);
+ if (value === undefined) return false;
+ await writeTrailer(opts.messageFile, value);
return true;
}
diff --git a/packages/cli/test/agents.test.ts b/packages/cli/test/agents.test.ts
index 3e92ad0..a8428ce 100644
--- a/packages/cli/test/agents.test.ts
+++ b/packages/cli/test/agents.test.ts
@@ -14,6 +14,7 @@ describe("agent adapter", () => {
expect(agent.skill).toBe("/cogit:record");
expect(agent.skillRule).toBe("Skill(cogit:record)");
expect(agent.sessionIdEnv).toBe("CLAUDE_SESSION_ID");
+ expect(agent.commitSessionEnv).toBe("CLAUDE_CODE_SESSION_ID");
});
it("parses a Claude Code hook payload and refuses anything else", () => {
diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.ts
index bb2468c..fa67aad 100644
--- a/packages/cli/test/thought.test.ts
+++ b/packages/cli/test/thought.test.ts
@@ -285,6 +285,74 @@ describe("the thought behind a commit (Story 9.4)", () => {
).toBe(false);
});
+ it("follows the session the commit's shell names, not HEAD (Story 10.6)", async () => {
+ // Two sessions in one working tree: HEAD was last written by s1.
+ await writeHead();
+ await writeTranscript("s2", "other");
+ const file = await messageFile();
+ const named = { ...env, CLAUDE_CODE_SESSION_ID: "s2" };
+ expect(
+ await addThoughtTrailer({
+ dir: root,
+ messageFile: file,
+ source: "message",
+ env: named,
+ now: NOW,
+ }),
+ ).toBe(true);
+ const text = await readMessage(file);
+ expect(text).toContain(`Thought: ${thoughtOf("other", "s2")}`);
+ expect(text).not.toContain(thoughtOf());
+ });
+
+ it("works with no .cogit/HEAD at all (a headless claude -p run)", async () => {
+ await writeTranscript("s3", "headless");
+ const file = await messageFile();
+ const named = { ...env, CLAUDE_CODE_SESSION_ID: "s3" };
+ expect(
+ await addThoughtTrailer({
+ dir: root,
+ messageFile: file,
+ source: "message",
+ env: named,
+ now: NOW,
+ }),
+ ).toBe(true);
+ expect(await readMessage(file)).toContain(`Thought: ${thoughtOf("headless", "s3")}`);
+ });
+
+ it("never falls back to HEAD when the named session has no transcript", async () => {
+ await writeHead();
+ const file = await messageFile();
+ const named = { ...env, CLAUDE_CODE_SESSION_ID: "s-missing" };
+ expect(
+ await addThoughtTrailer({
+ dir: root,
+ messageFile: file,
+ source: "message",
+ env: named,
+ now: NOW,
+ }),
+ ).toBe(false);
+ expect(await readMessage(file)).toBe("feat: change the code\n");
+ });
+
+ it("uses HEAD when the variable is unset or empty (a human commit)", async () => {
+ await writeHead();
+ const file = await messageFile();
+ const blank = { ...env, CLAUDE_CODE_SESSION_ID: " " };
+ expect(
+ await addThoughtTrailer({
+ dir: root,
+ messageFile: file,
+ source: "message",
+ env: blank,
+ now: NOW,
+ }),
+ ).toBe(true);
+ expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);
+ });
+
it("runs through the CLI's prepare-commit-msg hook", async () => {
await writeHead();
const file = await messageFile();