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(shape): shape the message the commit's Thought trailer names
Erenba654e8fa94f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dee39c5..5e7355b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [0.25.0] - 2026-10-30### 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, 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; an invalid diagram is kept as text.+- 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.- `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 init` warns when git has no `user.email`, since sessions are now told apart by it.diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex b52d4cf..d14e911 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -6,6 +6,7 @@ import { type Author, sameAuthor, sessionIdentity, stampedIdentity } from "../auexport { sessionAuthor } from "../author.js";import { commitBetween, findGitRoot } from "../git.js";+import { currentCliPath } from "../git-hooks.js";import { CliError, type Io } from "../io.js";import {hashesToLabels,@@ -23,6 +24,7 @@ import type { SessionEvent } from "../schema/events.js";import { mergeSession } from "../schema/merge.js";import { MESSAGE_ID, type Session, SessionInput } from "../schema/session.js";import { stampShape } from "../shape.js";+import { drainShapeQueue } from "../shape-queue.js";import {appendEvents,applyEvents,@@ -167,6 +169,11 @@ export async function sessionWrite(} catch (err) {io.warn(`could not build map.html: ${(err as Error).message}`);}++ // Story 13.6: commits that landed before this message was recorded wait for+ // it; their Shape starts now, detached. Never a reason to fail the write.+ if (config.shapes && config.recorder !== "agent")+ await drainShapeQueue(root, saved, io.env, currentCliPath()).catch(() => 0);}/**diff --git a/packages/cli/src/commands/shape.ts b/packages/cli/src/commands/shape.tsindex 849af31..e914b39 100644--- a/packages/cli/src/commands/shape.ts+++ b/packages/cli/src/commands/shape.ts@@ -1,4 +1,10 @@-import { findGitRoot, readCommitChanges, readCommitPatches, readCommitSubjects } from "../git.js";+import {+ findGitRoot,+ readCommitChanges,+ readCommitPatches,+ readCommitSubjects,+ resolveCommit,+} from "../git.js";import { CliError, type Io } from "../io.js";import type { Config } from "../schema/config.js";import type { LineageNode } from "../schema/session.js";@@ -10,10 +16,12 @@ import {shapePrompt,shapeWanted,} from "../shape.js";+import { dequeueShape, enqueueShape } from "../shape-queue.js";import { LockBusyError, withLock } from "../store/lock.js";import { projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";-import { loadConfig, loadProject, loadSession } from "../store/stores.js";+import { loadAllSessions, loadConfig, loadProject, loadSession } from "../store/stores.js";+import { attachThoughtTrailers, readCommitThought, readThoughtTrailers } from "../thought.js";import { resultText, runClaude } from "./backfill.js";import { sessionWrite } from "./session.js";@@ -37,26 +45,33 @@ export function needsShape(node: LineageNode): boolean {return node.shape.commits.length < node.commits.length;}-/** The newest message waiting for a Shape, by its own time then its position. */+/** Messages waiting for a Shape, newest first (by their own time, then position). */+export function shapeCandidates(nodes: readonly LineageNode[]): LineageNode[] {+ return nodes+ .map((node, index) => {+ const parsed = Date.parse(node.at ?? node.addedAt ?? "");+ return { node, index, at: Number.isNaN(parsed) ? index : parsed };+ })+ .filter(({ node }) => needsShape(node))+ .sort((a, b) => b.at - a.at || b.index - a.index)+ .map(({ node }) => node);+}++/** The newest message waiting for a Shape. */export function nextShapeNode(nodes: readonly LineageNode[]): LineageNode | undefined {- let best: LineageNode | undefined;- let bestAt = Number.NEGATIVE_INFINITY;- nodes.forEach((node, index) => {- if (!needsShape(node)) return;- const parsed = Date.parse(node.at ?? node.addedAt ?? "");- const at = Number.isNaN(parsed) ? index : parsed;- if (best === undefined || at >= bestAt) {- best = node;- bestAt = at;- }- });- return best;+ return shapeCandidates(nodes)[0];+}++export interface ShapeOptions {+ /** Shape the message this commit's `Thought:` trailer names (the post-commit path). */+ commit?: string | undefined;}export async function shapeMessage(dir: string,sessionId: string | undefined,io: Io,+ opts: ShapeOptions = {},): Promise<void> {const { root } = await resolveProjectRoot(dir);const project = await loadProject(root);@@ -72,34 +87,109 @@ export async function shapeMessage(// the side model's modes.if (config.recorder === "agent") return;+ if (opts.commit !== undefined) {+ await shapeCommit(root, opts.commit, config, io);+ return;+ }const id = sessionId ?? (await readSessionHead(root))?.sessionId;if (id === undefined) {io.out("no session to shape");return;}+ await underLock(root, id, io, () => runShape(root, id, config, io));+}++async function underLock(+ root: string,+ sessionId: string,+ io: Io,+ fn: () => Promise<void>,+): Promise<void> {try {- await withLock(projectPaths(root).lock(`shape-${id}`), () => runShape(root, id, config, io), {- timeoutMs: 0,- });+ await withLock(projectPaths(root).lock(`shape-${sessionId}`), fn, { timeoutMs: 0 });} catch (err) {if (!(err instanceof LockBusyError)) throw err;- io.out(`a shape for ${id} is already being written`);+ io.out(`a shape for ${sessionId} is already being written`);+ }+}++/**+ * The post-commit path: the commit's `Thought:` trailer names the message, so+ * the Shape lands on the message that made the commit, whichever session last+ * wrote `.cogit/HEAD`. A message with no record yet is queued; the `session+ * write` that adds it starts this again.+ */+async function shapeCommit(root: string, ref: string, config: Config, io: Io): Promise<void> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return;+ const commit = await resolveCommit(gitRoot, ref);+ if (commit === undefined) {+ io.out(`no commit ${ref}`);+ return;+ }+ const thought = await readCommitThought(root, commit, io.env);+ if (thought === undefined) {+ io.out(`no shape for ${commit.slice(0, 7)}: no Thought trailer`);+ return;}+ const sessions = await loadAllSessions(root, () => {});+ const session = sessions.find((s) =>+ s.nodes.some((n) => n.kind === "message" && n.id === thought),+ );+ if (session === undefined) {+ await enqueueShape(root, commit, thought);+ io.out(`queued ${commit.slice(0, 7)} until ${thought} is recorded`);+ return;+ }+ await dequeueShape(root, commit);+ await underLock(root, session.sessionId, io, async () => {+ const fresh = await loadSession(root, session.sessionId);+ if (!fresh.found || !fresh.ok) return;+ const [withTrailers] = attachThoughtTrailers(+ [fresh.data],+ await readThoughtTrailers(root, { env: io.env, since: fresh.data.startedAt }),+ );+ const node = withTrailers?.nodes.find((n) => n.id === thought);+ if (node === undefined || !needsShape(node)) return;+ await shapeNode(root, gitRoot, session.sessionId, node, config, io);+ });}+/**+ * The manual path: the newest message that wants a Shape. A message the skip+ * rules turn down (a release commit, a two-line fix) is passed over, so it+ * never holds back the older ones behind it.+ */async function runShape(root: string, sessionId: string, config: Config, io: Io): Promise<void> {const loaded = await loadSession(root, sessionId);if (!loaded.found || !loaded.ok) return;- const node = nextShapeNode(loaded.data.nodes);- if (node === undefined || node.commits === undefined) return;-const gitRoot = await findGitRoot(root);if (gitRoot === undefined) return;+ // The trailers link commits the record has not listed yet.+ const [session] = attachThoughtTrailers(+ [loaded.data],+ await readThoughtTrailers(root, { env: io.env, since: loaded.data.startedAt }),+ );+ for (const node of shapeCandidates(session?.nodes ?? [])) {+ if (await shapeNode(root, gitRoot, sessionId, node, config, io)) return;+ }+}++/** Writes one message's Shape; false when the skip rules turned it down. */+async function shapeNode(+ root: string,+ gitRoot: string,+ sessionId: string,+ node: LineageNode,+ config: Config,+ io: Io,+): Promise<boolean> {+ const hashes = node.commits ?? [];const [changes, subjects] = await Promise.all([- readCommitChanges(gitRoot, node.commits),- readCommitSubjects(gitRoot, node.commits),+ readCommitChanges(gitRoot, hashes),+ readCommitSubjects(gitRoot, hashes),]);- const commits: ShapeCommitInfo[] = node.commits.flatMap((hash) => {+ const commits: ShapeCommitInfo[] = hashes.flatMap((hash) => {const change = changes.get(hash);if (change === undefined) return [];return [@@ -112,14 +202,13 @@ async function runShape(root: string, sessionId: string, config: Config, io: Io)},];});- if (commits.length === 0) return;const verdict = shapeWanted(commits);if (!verdict.wanted) {io.out(`no shape for ${node.id}: ${verdict.reason}`);- return;+ return false;}- const patches = await readCommitPatches(gitRoot, node.commits, SHAPE_DIFF_LIMIT);+ const patches = await readCommitPatches(gitRoot, hashes, SHAPE_DIFF_LIMIT);const prompt = shapePrompt({node,commits,@@ -136,9 +225,12 @@ async function runShape(root: string, sessionId: string, config: Config, io: Io)id: node.id,kind: "message",title: node.title,- shape: { tools: answer.tools, commits: node.commits },+ // The trailer-linked commits count too, so the message stops waiting+ // once its Shape covers them.+ shape: { tools: answer.tools, commits: hashes.slice(-20) },},],};await sessionWrite({ dir: root, by: "side" }, io, async () => JSON.stringify(payload));+ return true;}diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.tsindex 2bfd46f..b56491e 100644--- a/packages/cli/src/git-hooks.ts+++ b/packages/cli/src/git-hooks.ts@@ -1,9 +1,9 @@import { realpathSync } from "node:fs";import { chmod, mkdir, readFile, rm, stat } from "node:fs/promises";import { join } from "node:path";-import { findGitRoot, gitHooksDir } from "./git.js";+import { findGitRoot, gitHooksDir, resolveCommit } from "./git.js";import { spawnDetachedProcess } from "./hooks/run.js";-import { readSessionHead, stageSessionFiles } from "./session-git.js";+import { stageSessionFiles } from "./session-git.js";import { atomicWrite } from "./store/fs.js";import { captureDisabled, projectPaths } from "./store/paths.js";import { loadConfig } from "./store/stores.js";@@ -176,25 +176,28 @@ export async function uninstallGitHooks(root: string): Promise<GitHookEvent[]> {}/**- * Queues the Shape of the session that just committed (Story 13.6). Detached- * and silent: a commit never waits for a side-model run, and a failure lands in- * the detached log like the session-end pass. In `agent` mode the record skill- * writes the Shape itself, so there is nothing to queue.+ * Starts the Shape of the commit that just landed (Story 13.6). The commit's+ * `Thought:` trailer, read by the shape run, names the message, so the Shape+ * lands on the session that committed, not on whichever session wrote+ * `.cogit/HEAD` last. Detached and silent: a commit never waits for a+ * side-model run, and a failure lands in the detached log like the session-end+ * pass. In `agent` mode the record skill writes the Shape itself.*/-async function queueShape(dir: string, env: NodeJS.ProcessEnv): Promise<void> {+async function queueShape(+ dir: string,+ env: NodeJS.ProcessEnv,+ spawn: typeof spawnDetachedProcess,+): Promise<void> {if (captureDisabled(env)) return;const config = await loadConfig(env).catch(() => undefined);if (config === undefined || !config.shapes || config.recorder === "agent") return;- const head = await readSessionHead(dir);- if (head === undefined) return;+ const gitRoot = await findGitRoot(dir);+ if (gitRoot === undefined) return;+ const commit = await resolveCommit(gitRoot, "HEAD");+ if (commit === undefined) return;const cli = currentCliPath();if (cli === undefined) return;- spawnDetachedProcess(- cli,- ["shape", head.sessionId, "-C", dir],- env,- projectPaths(dir).detachedLog,- );+ spawn(cli, ["shape", "--commit", commit, "-C", dir], env, projectPaths(dir).detachedLog);}/**@@ -209,13 +212,14 @@ export async function runGitHook(env: NodeJS.ProcessEnv = process.env,args: readonly string[] = [],now: Date = new Date(),+ spawn: typeof spawnDetachedProcess = spawnDetachedProcess,): Promise<void> {if (event === "pre-commit") {await stageSessionFiles(dir, env);return;}if (event === "post-commit") {- await queueShape(dir, env);+ await queueShape(dir, env, spawn);return;}const [messageFile, source] = args;diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.tsindex ff32897..945ea09 100644--- a/packages/cli/src/git.ts+++ b/packages/cli/src/git.ts@@ -22,6 +22,24 @@ export async function findGitRoot(dir: string): Promise<string | undefined> {}}+/** The full hash `ref` names (`HEAD`, a short hash), or undefined. */+export async function resolveCommit(root: string, ref: string): Promise<string | undefined> {+ try {+ const { stdout } = await exec("git", [+ "-C",+ root,+ "rev-parse",+ "--verify",+ "--quiet",+ `${ref}^{commit}`,+ ]);+ const hash = String(stdout).trim();+ return hash === "" ? undefined : hash;+ } catch {+ return undefined;+ }+}+const HEADER = "# cogit";/** The root line that keeps the whole `.cogit/` out under the ignore policy. */diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex a9af854..9379316 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -421,11 +421,15 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =.description("write the Shape of the newest message that landed commits (side model)").helpGroup("Agent:").argument("[session-id]", "session id; defaults to the session in .cogit/HEAD")+ .option("--commit <sha>", "shape the message this commit's Thought trailer names").option("-C, --dir <dir>", "project directory", ".")- .addHelpText("after", examples("cogit shape", "cogit shape 9c32ab18"))+ .addHelpText(+ "after",+ examples("cogit shape", "cogit shape 9c32ab18", "cogit shape --commit HEAD"),+ ).action(- run(async (sessionId: string | undefined, opts: { dir: string }) =>- shapeMessage(opts.dir, sessionId, makeIo(false)),+ run(async (sessionId: string | undefined, opts: { dir: string; commit?: string }) =>+ shapeMessage(opts.dir, sessionId, makeIo(false), { commit: opts.commit }),),);diff --git a/packages/cli/src/shape-queue.ts b/packages/cli/src/shape-queue.tsnew file mode 100644index 0000000..9861a54--- /dev/null+++ b/packages/cli/src/shape-queue.ts@@ -0,0 +1,84 @@+import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { spawnDetachedProcess } from "./hooks/run.js";+import type { Session } from "./schema/session.js";+import { projectPaths } from "./store/paths.js";++/**+ * Commits whose message had no record yet when they landed (Story 13.6). A+ * commit usually lands before the Stop hook writes the message it belongs to,+ * so the post-commit Shape run leaves the commit here and the next+ * `session write` that holds the message starts the Shape. Local state: one+ * file per commit, named by its full hash, holding the `Thought:` message id.+ */++const FULL_HASH = /^[0-9a-f]{40}$/;++/** A commit whose message never got a record (a deleted session) stops waiting. */+const QUEUE_MAX_AGE_MS = 7 * 24 * 3_600_000;++export interface QueuedShape {+ commit: string;+ thought: string;+}++export async function enqueueShape(root: string, commit: string, thought: string): Promise<void> {+ const dir = projectPaths(root).shapeQueue;+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, commit), `${thought}\n`);+}++export async function dequeueShape(root: string, commit: string): Promise<void> {+ await rm(join(projectPaths(root).shapeQueue, commit), { force: true });+}++/** The waiting commits; stale entries are dropped on the way. */+export async function queuedShapes(root: string, now: Date = new Date()): Promise<QueuedShape[]> {+ const dir = projectPaths(root).shapeQueue;+ const names = await readdir(dir).catch(() => [] as string[]);+ const out: QueuedShape[] = [];+ for (const name of names) {+ if (!FULL_HASH.test(name)) continue;+ const file = join(dir, name);+ const info = await stat(file).catch(() => undefined);+ if (info === undefined) continue;+ if (now.getTime() - info.mtimeMs > QUEUE_MAX_AGE_MS) {+ await rm(file, { force: true });+ continue;+ }+ const thought = (await readFile(file, "utf8").catch(() => "")).trim();+ if (thought !== "") out.push({ commit: name, thought });+ }+ return out;+}++/** The queued commits whose message the session now holds. */+export function readyShapes(queue: readonly QueuedShape[], session: Session): QueuedShape[] {+ const ids = new Set(session.nodes.filter((n) => n.kind === "message").map((n) => n.id));+ return queue.filter((entry) => ids.has(entry.thought));+}++/**+ * Starts a detached `cogit shape --commit` for each queued commit the session+ * now explains. The shape run takes the commit off the queue; a second start+ * while one runs stops at the shape lock.+ */+export async function drainShapeQueue(+ root: string,+ session: Session,+ env: NodeJS.ProcessEnv,+ cli: string | undefined,+ spawn: typeof spawnDetachedProcess = spawnDetachedProcess,+): Promise<number> {+ if (cli === undefined) return 0;+ const ready = readyShapes(await queuedShapes(root), session);+ for (const entry of ready) {+ spawn(+ cli,+ ["shape", "--commit", entry.commit, "-C", root],+ env,+ projectPaths(root).detachedLog,+ );+ }+ return ready.length;+}diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.tsindex 968cc54..228ac43 100644--- a/packages/cli/src/store/paths.ts+++ b/packages/cli/src/store/paths.ts@@ -44,6 +44,8 @@ export function projectPaths(root: string) {mapView: join(base, "state", "map.json"),/** What the detached hook children (build, side run) printed; local, capped. */detachedLog: join(base, "state", "detached.log"),+ /** Commits waiting for their message's record before a Shape; local. */+ shapeQueue: join(base, "state", "shape-queue"),locks: join(base, "locks"),/** Where the skill drops session JSON for `session write --file`. */inbox: (id: string) => join(base, "inbox", `${id}.json`),diff --git a/packages/cli/test/shape-commit.test.ts b/packages/cli/test/shape-commit.test.tsnew file mode 100644index 0000000..d1c2326--- /dev/null+++ b/packages/cli/test/shape-commit.test.ts@@ -0,0 +1,205 @@+import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import { chmod, mkdir, readFile, utimes, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { promisify } from "node:util";+import { beforeEach, describe, expect, it } from "vitest";+import { init } from "../src/commands/init.js";+import { shapeMessage } from "../src/commands/shape.js";+import { runGitHook } from "../src/git-hooks.js";+import { createProgram } from "../src/program.js";+import type { Session } from "../src/schema/session.js";+import { drainShapeQueue, queuedShapes } from "../src/shape-queue.js";+import { withLock } from "../src/store/lock.js";+import { projectPaths } from "../src/store/paths.js";+import { loadSession } from "../src/store/stores.js";+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";++const run = promisify(execFile);++const THOUGHT = "h0123456789ab";+const OLDER = "h0000000000aa";++const ANSWER = JSON.stringify({ tools: [{ kind: "pseudo", text: "1. Read it\n2. Write it" }] });++function session(nodes: Session["nodes"], id = "s1"): Session {+ return {+ schema: 1,+ sessionId: id,+ agent: "claude-code",+ title: "Ship it",+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes,+ };+}++describe("a Shape follows the commit's Thought trailer (Story 13.6)", () => {+ let dir: string;+ let root: string;+ let env: NodeJS.ProcessEnv;++ const git = async (...args: string[]): Promise<string> =>+ String(+ (+ await run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir },+ })+ ).stdout,+ ).trim();++ /** Commits `lines` new lines to `file`, with an optional Thought trailer. */+ const commit = async (file: string, lines: number, thought?: string): Promise<string> => {+ const body = Array.from({ length: lines }, (_, i) => `line ${i}`).join("\n");+ await writeFile(join(root, file), `${body}\n`);+ await git("add", file);+ const message = thought === undefined ? "feat: work" : `feat: work\n\nThought: ${thought}`;+ await git("commit", "-q", "--no-verify", "-m", message);+ return git("rev-parse", "HEAD");+ };++ const writeRecord = async (nodes: Session["nodes"]): Promise<void> => {+ await writeFile(projectPaths(root).session("s1"), JSON.stringify(session(nodes)));+ };++ /** A fake `claude` that prints one Shape answer and keeps how often it ran. */+ const fakeClaude = async (): Promise<NodeJS.ProcessEnv> => {+ const bin = join(dir, "bin");+ await mkdir(bin, { recursive: true });+ const file = join(bin, "claude");+ const count = JSON.stringify(join(dir, "runs.txt"));+ await writeFile(+ file,+ `#!/usr/bin/env node+process.stdin.resume();+process.stdin.on("end", () => {+ require("node:fs").appendFileSync(${count}, "x");+ process.stdout.write(JSON.stringify({ type: "result", subtype: "success", result: ${JSON.stringify(ANSWER)} }));+});+`,+ );+ await chmod(file, 0o755);+ return { ...env, PATH: `${bin}:${process.env.PATH ?? ""}` };+ };++ const shapeOf = async (id: string) => {+ const loaded = await loadSession(root, "s1");+ if (!loaded.found || !loaded.ok) return undefined;+ return loaded.data.nodes.find((node) => node.id === id)?.shape;+ };++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ env = envFor(dir);+ await mkdir(root, { recursive: true });+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await init(+ root,+ { name: "proj", retention: "keep", language: "auto", allowSkill: false },+ fakeIo(env),+ );+ });++ it("queues a commit whose message is not recorded yet", async () => {+ const sha = await commit("a.txt", 12, THOUGHT);+ const io = fakeIo(env);+ await shapeMessage(root, undefined, io, { commit: "HEAD" });+ expect(io.lines).toContain(`queued ${sha.slice(0, 7)} until ${THOUGHT} is recorded`);+ expect(await queuedShapes(root)).toEqual([{ commit: sha, thought: THOUGHT }]);+ });++ it("starts the queued Shape once the record holds the message", async () => {+ const sha = await commit("a.txt", 12, THOUGHT);+ await shapeMessage(root, undefined, fakeIo(env), { commit: sha });+ const started: string[][] = [];+ const spawn = (_cli: string, args: string[]) => {+ started.push(args);+ };++ const before = session([{ id: OLDER, kind: "message", title: "Other", parent: null }]);+ expect(await drainShapeQueue(root, before, env, "/cli.js", spawn)).toBe(0);++ const after = session([{ id: THOUGHT, kind: "message", title: "Work", parent: null }]);+ expect(await drainShapeQueue(root, after, env, "/cli.js", spawn)).toBe(1);+ expect(started).toEqual([["shape", "--commit", sha, "-C", root]]);+ });++ it("drops a queued commit after a week", async () => {+ const sha = await commit("a.txt", 12, THOUGHT);+ await shapeMessage(root, undefined, fakeIo(env), { commit: sha });+ const file = join(projectPaths(root).shapeQueue, sha);+ const old = new Date(Date.now() - 8 * 24 * 3_600_000);+ await utimes(file, old, old);+ expect(await queuedShapes(root)).toEqual([]);+ expect(existsSync(file)).toBe(false);+ });++ it("shapes the trailer's message even before the record lists the commit", async () => {+ const sha = await commit("a.txt", 12, THOUGHT);+ await writeRecord([{ id: THOUGHT, kind: "message", title: "Work", parent: null }]);+ await shapeMessage(root, undefined, fakeIo(await fakeClaude()), { commit: sha });+ expect(await queuedShapes(root)).toEqual([]);+ const shape = await shapeOf(THOUGHT);+ expect(shape?.by).toBe("side");+ expect(shape?.commits).toEqual([sha]);+ expect(shape?.tools[0]?.kind).toBe("pseudo");+ });++ it("does nothing for a commit with no Thought trailer", async () => {+ await commit("a.txt", 12);+ const io = fakeIo(env);+ await shapeMessage(root, undefined, io, { commit: "HEAD" });+ expect(io.lines.at(-1)).toMatch(/no Thought trailer/);+ expect(await queuedShapes(root)).toEqual([]);+ });++ it("passes over a skipped message so an older one still gets its Shape", async () => {+ const big = await commit("a.txt", 12, OLDER);+ const tiny = await commit("b.txt", 1, THOUGHT);+ await writeRecord([+ { id: OLDER, kind: "message", title: "Big", parent: null, at: T0, commits: [big] },+ {+ id: THOUGHT,+ kind: "message",+ title: "Tiny",+ parent: null,+ at: "2026-10-21T11:00:00.000Z",+ commits: [tiny],+ },+ ]);+ const io = fakeIo(await fakeClaude());+ await shapeMessage(root, "s1", io);+ expect(io.lines).toContain(`no shape for ${THOUGHT}: only 1 changed line`);+ expect((await shapeOf(OLDER))?.commits).toEqual([big]);+ expect(await shapeOf(THOUGHT)).toBeUndefined();+ expect(await readFile(join(dir, "runs.txt"), "utf8")).toBe("x");+ });++ it("starts from the post-commit hook with the new commit", async () => {+ const sha = await commit("a.txt", 12, THOUGHT);+ const started: string[][] = [];+ await runGitHook("post-commit", root, env, [], new Date(), (_cli, args) => {+ started.push(args);+ });+ expect(started).toEqual([["shape", "--commit", sha, "-C", root]]);+ });++ it("says so for a commit git does not know, and runs through the CLI", async () => {+ await commit("a.txt", 12);+ const io = fakeIo(env);+ const program = createProgram(() => io);+ program.exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });+ await program.parseAsync(["shape", "--commit", "nope", "-C", root], { from: "user" });+ expect(io.lines).toEqual(["no commit nope"]);+ });++ it("leaves a Shape that is already being written alone", async () => {+ const io = fakeIo(env);+ await withLock(projectPaths(root).lock("shape-s1"), () => shapeMessage(root, "s1", io));+ expect(io.lines).toEqual(["a shape for s1 is already being written"]);+ });+});