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(doctor): stop the false hook and session warnings and make the retention fix work
Erenfd39972a3ae1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0030c33..8c848bf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- Intent, Shape and Code: a message that landed commits gets a **Shape** — numbered plain-language steps or a Mermaid diagram of what the change does — between its recorded Intent and its diff. The side panel previews it and **Open** shows the three layers with 1/2/3 tabs. The side model writes it after a commit (detached, behind its own lock) in the mixed and side modes, on the message the commit's `Thought:` trailer names; a commit that lands before its message is recorded waits for the record, the agent writes it in the record skill, and `shapes` (on by default) turns it off. Release bumps, lockfiles, CHANGELOG-only changes and changes under five lines are skipped without holding back older messages; an invalid diagram is kept as text. Mermaid ships once beside the CLI and the local server hands it to the map, so `map.html` stays about 550 kB; a map opened from `file://` shows the diagram's source instead.- `cogit why <file>:<line>` (or `--line N`) shows only the thought behind that line: git blames the line to its commit, the commit's `Thought:` trailer names the message, and `why` prints that message's decision and rejected options. When the commit carries no thought it says so and lists the file's other thoughts; a line past the end of the file is an error.-- `cogit doctor` explains why the map may stay empty: read-only checks for Node, the Claude Code plugin and its version, git identity, the project and its hooks, the skill permission, transcripts and their retention, recorded sessions and the unrecorded tail, the map server and the close-pass log. Each line says `ok`, `warn` or `fail` with the command that fixes it; `--json` prints the report, and a failed check exits 1.+- `cogit doctor` explains why the map may stay empty: read-only checks for Node, the Claude Code plugin and its version, git identity, the project and its hooks, the skill permission, transcripts and their retention, recorded sessions and the unrecorded tail (headless runs such as `claude -p` are left out unless `recordHeadless` is on), the map server and the close-pass log. Each line says `ok`, `warn` or `fail` with the command that fixes it; `--json` prints the report, and a failed check exits 1.+- `cogit init --retention <days>` also applies to a project that is already set up, as `cogit doctor` suggests.- `cogit init` warns when git has no `user.email`, since sessions are now told apart by it.- The map tells your sessions from your teammates': a teammate's session always shows their name and yours never needs to, the side panel marks yours "(you)", and a new Everyone / You / teammate choice in the toolbar fades the other people's sessions.diff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.tsindex b6fc765..b88e289 100644--- a/packages/cli/src/agents/claude/index.ts+++ b/packages/cli/src/agents/claude/index.ts@@ -24,6 +24,7 @@ import {displayTurn,excerpt,findTranscript,+ isHeadlessTranscript,readConversation,readForkOrigin,readLastTurn,@@ -60,6 +61,7 @@ export const claude: AgentAdapter = {parseHookInput,isHeadless,+ isHeadlessTranscript,additionalContext,userNotice,diff --git a/packages/cli/src/agents/claude/transcripts.ts b/packages/cli/src/agents/claude/transcripts.tsindex 06a90e1..4f042c3 100644--- a/packages/cli/src/agents/claude/transcripts.ts+++ b/packages/cli/src/agents/claude/transcripts.ts@@ -238,6 +238,28 @@ export async function readConversation(file: string): Promise<ChatTurn[]> {});}+const ENTRYPOINT = /"entrypoint":"([^"]*)"/;++/**+ * Whether nobody typed into this transcript: `claude -p` and the SDKs write+ * `"entrypoint":"sdk-…"` on their lines, as `isHeadless` reads it from the+ * environment. The first line that names an entrypoint decides.+ */+export async function isHeadlessTranscript(file: string): Promise<boolean> {+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });+ try {+ let read = 0;+ for await (const raw of lines) {+ const entrypoint = ENTRYPOINT.exec(raw)?.[1];+ if (entrypoint !== undefined) return entrypoint.startsWith("sdk");+ if ((read += 1) >= 50) break;+ }+ return false;+ } finally {+ lines.close();+ }+}+/** Where a forked transcript came from; null for a session of its own. */export async function readForkOrigin(file: string): Promise<ForkOrigin | null> {return forkOrigin(file, await readAllTurns(file), readTranscriptTurns, isMessageLine);diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.tsindex a3f22c3..e23d5a4 100644--- a/packages/cli/src/agents/types.ts+++ b/packages/cli/src/agents/types.ts@@ -161,6 +161,8 @@ export interface AgentAdapter {parseHookInput(stdin: string): HookInput | undefined;/** Whether the hook runs in a session started without a person (`claude -p`, an SDK). */isHeadless(env: NodeJS.ProcessEnv): boolean;+ /** The same for a transcript on disk: whether a headless run wrote it. */+ isHeadlessTranscript(file: string): Promise<boolean>;/** Hook output that adds context for the agent, in the agent's own protocol. */additionalContext(event: string, text: string): Record<string, unknown>;/** A hook answer that shows one line to the user, not to the agent. */diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.tsindex 4c360bd..7e07700 100644--- a/packages/cli/src/commands/doctor.ts+++ b/packages/cli/src/commands/doctor.ts@@ -91,18 +91,26 @@ export async function projectTranscripts(return new Map([...all].filter(([, file]) => names.has(basename(dirname(file)))));}-/** The transcript with the latest modification time, if there is one. */+/**+ * The transcript with the latest modification time that `skip` lets through,+ * if there is one. Headless runs (Ralph, `claude -p`, other plugins' background+ * sessions) are skipped unless they are recorded, so they never read as a tail+ * someone forgot to record.+ */async function newestTranscript(transcripts: ReadonlyMap<string, string>,+ skip: (file: string) => Promise<boolean>,): Promise<{ id: string; file: string } | undefined> {- let newest: { id: string; file: string; mtime: number } | undefined;+ const dated: { id: string; file: string; mtime: number }[] = [];for (const [id, file] of transcripts) {const info = await stat(file).catch(() => undefined);- if (info === undefined) continue;- if (newest === undefined || info.mtimeMs > newest.mtime)- newest = { id, file, mtime: info.mtimeMs };+ if (info !== undefined) dated.push({ id, file, mtime: info.mtimeMs });+ }+ dated.sort((a, b) => b.mtime - a.mtime);+ for (const { id, file } of dated) {+ if (!(await skip(file))) return { id, file };}- return newest === undefined ? undefined : { id: newest.id, file: newest.file };+ return undefined;}/** The user messages in this transcript that the record has no node for. */@@ -282,7 +290,7 @@ const CHECK_SPECS: CheckSpec[] = [id: "project",status: "warn",message: `initialized, but ${hooks.join(", ")}`,- fix: "cogit init",+ fix: "cogit hooks install",};return {id: "project",@@ -357,7 +365,10 @@ const CHECK_SPECS: CheckSpec[] = [run: async (ctx) => {const sessions = await ctx.sessions();const transcripts = await ctx.transcripts();- const newest = await newestTranscript(transcripts);+ const { recordHeadless } = await ctx.config();+ const newest = await newestTranscript(transcripts, (file) =>+ recordHeadless ? Promise.resolve(false) : ctx.agent.isHeadlessTranscript(file),+ );const tail =newest === undefined? undefined@@ -432,7 +443,12 @@ const CHECK_SPECS: CheckSpec[] = [},];-/** Hook files that are missing or carry a block an earlier CLI wrote. */+/**+ * Hook files that are missing or carry a block for another project or an+ * earlier hook command. Only the `cogit hook …` line is compared: the fallback+ * CLI path in the block names whichever CLI installed it (the plugin cache, a+ * global install), which differs between runs and is refreshed by the plugin.+ */async function hookProblems(ctx: DoctorContext): Promise<string[]> {const gitRoot = await ctx.gitRoot();if (gitRoot === undefined) return ["the git hooks are not installed"];@@ -445,8 +461,9 @@ async function hookProblems(ctx: DoctorContext): Promise<string[]> {problems.push(`the ${event} hook is missing`);continue;}- const block = /# >>> cogit[\s\S]*?# <<< cogit/.exec(text)?.[0];- if (block !== hookBlock(event, ctx.root)) problems.push(`the ${event} hook is outdated`);+ 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`);}return problems;}diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex d3272ee..a2e4ffc 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -208,6 +208,8 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<voidif (!existing.ok) throw new CliError(`${projectPaths(root).project}: ${existing.error}`);await register(io, root, existing.data.name);if (opts.allowSkill !== undefined) await askSkillPermission(io, opts);+ // `cogit doctor` suggests `init --retention 90` for a set-up project too.+ if (opts.retention !== undefined) await askRetention(io, opts);if (opts.projectSettings !== undefined) await askProjectSettings(io, root, opts);await bestEffort(io, "could not refresh the project's Claude Code settings", async () => {const file = await agent.refreshProjectSetup(root);diff --git a/packages/cli/test/doctor.test.ts b/packages/cli/test/doctor.test.tsindex b726b12..4953466 100644--- a/packages/cli/test/doctor.test.ts+++ b/packages/cli/test/doctor.test.ts@@ -1,5 +1,5 @@import { execFile } from "node:child_process";-import { mkdir, rm, writeFile } from "node:fs/promises";+import { mkdir, readFile, rm, utimes, writeFile } from "node:fs/promises";import { join } from "node:path";import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";@@ -15,6 +15,7 @@ import {transcriptDirName,} from "../src/commands/doctor.js";import { init } from "../src/commands/init.js";+import { hookBlock } from "../src/git-hooks.js";import { hashTurns } from "../src/messages.js";import { createProgram } from "../src/program.js";import { startMapServer } from "../src/server.js";@@ -131,6 +132,20 @@ describe("doctor's building blocks", () => {);});+ it("tells a headless transcript by its entrypoint", async () => {+ const file = join(dir, "t.jsonl");+ const agent = defaultAgent();+ await writeFile(file, '{"type":"user","entrypoint":"sdk-cli"}\n');+ expect(await agent.isHeadlessTranscript(file)).toBe(true);+ await writeFile(file, '{"type":"system"}\n{"type":"user","entrypoint":"cli"}\n');+ expect(await agent.isHeadlessTranscript(file)).toBe(false);+ // Only the first lines are read; a file that names no entrypoint is a person's.+ await writeFile(file, `${'{"type":"system"}\n'.repeat(60)}{"entrypoint":"sdk-cli"}\n`);+ expect(await agent.isHeadlessTranscript(file)).toBe(false);+ await writeFile(file, "");+ expect(await agent.isHeadlessTranscript(file)).toBe(false);+ });+it("finds an error only in the last close pass", () => {const log = ["--- 2026-10-30T10:00:00.000Z backfill s1 --tail -C /p",@@ -234,6 +249,14 @@ describe("doctor", () => {const stale = await check(root, "project");expect(stale.status).toBe("warn");expect(stale.message).toContain("prepare-commit-msg hook is outdated");+ expect(stale.fix).toBe("cogit hooks install");++ // A block another CLI installed (the plugin cache, a global install) is current.+ await writeFile(+ join(root, ".git", "hooks", "prepare-commit-msg"),+ `#!/bin/sh\n\n${hookBlock("prepare-commit-msg", root, "/elsewhere/cogit/dist/cli.js")}\n`,+ );+ expect((await check(root, "project")).status).toBe("ok");await writeFile(join(root, ".cogit", "project.json"), "{ not json");const broken = await check(root, "project");@@ -272,6 +295,19 @@ describe("doctor", () => {expect(ok.status).toBe("ok");expect(ok.message).toContain("1 session(s) recorded");+ // A headless run (Ralph, `claude -p`) is newer, but nobody records it.+ const headless = await transcript(root, "h1", ["ralph"]);+ await writeFile(+ headless,+ `{"type":"system","entrypoint":"sdk-cli"}\n${await readFile(headless, "utf8")}`,+ );+ const later = new Date(Date.now() + 60_000);+ await utimes(headless, later, later);+ expect((await check(root, "sessions")).status).toBe("ok");+ await updateConfig((config) => ({ ...config, recordHeadless: true }), env);+ expect((await check(root, "sessions")).fix).toBe("cogit backfill h1 --tail");+ await updateConfig((config) => ({ ...config, recordHeadless: false }), env);+await transcript(root, "s2", ["new one"]);const newer = await check(root, "sessions");expect(newer.status).toBe("warn");diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.tsindex 236d6d2..7a8318d 100644--- a/packages/cli/test/init.test.ts+++ b/packages/cli/test/init.test.ts@@ -210,6 +210,19 @@ describe("init", () => {expect(io.lines.some((l) => l.includes("cleanupPeriodDays"))).toBe(false);});+ it("applies a retention option to a project that is already set up", async () => {+ const options = {+ name: "p",+ git: "commit",+ allowSkill: false,+ projectSettings: false,+ language: "auto",+ } as const;+ await init(root, { ...options, retention: "keep" }, fakeIo(env, [], true));+ await init(root, { ...options, retention: 90 }, fakeIo(env, [], true));+ expect(await readRetention(env)).toBe(90);+ });+it("warns and moves on when Claude Code settings are unreadable", async () => {await mkdir(join(dir, "claude"));await writeFile(settingsFile(), "{oops");