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(thought): keep the link through a squash and off replayed commits
Eren506e56e77446
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f3d8a29..ec8485b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A saved map can carry its diffs: when the page embeds patches, the Code rows open them without the local server, and the "open the map with `cogit open`" notice gives way. The demo page under `docs/demo/` is built this way.### Fixed+- A rebase or cherry-pick during a session no longer links old commits that had no `Thought:` trailer to the session's newest message.+- A squashed commit keeps the link to every message it folded in, including commits already squashed: `cogit why`, `blame`, `pr` and the map read every `Thought:` line of the message, not only the last block. In `cogit pr --json`, a commit's `thought` is now `thoughts`, a list.- The diagram script is loaded relative to the page, so a map published under a subpath (the demo on GitHub Pages) draws its Shapes instead of falling back to the diagram's source.## [0.30.0] - 2026-11-01diff --git a/docs/guide/teams-and-git.md b/docs/guide/teams-and-git.mdindex f071639..338cc9a 100644--- a/docs/guide/teams-and-git.md+++ b/docs/guide/teams-and-git.md@@ -29,12 +29,24 @@ Switching never deletes a record; switching to ignore leaves what git already trsetups work). The block never fails a commit.- **`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, and- when the last message is older than `trailerMaxAgeHours` (6 hours), since such a commit is- probably not about that message.+ 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.- **`pre-commit`** stages the current session's record with your code commit. It never createsa record-only commit.+### Rebase and squash++The link names a message, not a commit hash, so it follows the commit message:++- **Rebase, cherry-pick:** the link stays, though the hash changes.+- **`git merge --squash`, a squash in `rebase -i`:** the commit links to every message it folded+ in, and `cogit why`, `blame` and the map show them all.+- **GitHub's squash button:** depends on the commit message it writes. A pull request with one+ commit keeps its message by default. With several, choose "Pull request title and commit+ details" in the repository's settings. A squash that keeps only the title has no link to read;+ the messages stay in the record, and `cogit search` still finds them.+`recordCommit` decides what happens to messages recorded after your last code commit: `ask`(the next session start offers to commit them), `auto`, or `off`.diff --git a/packages/cli/src/commands/log.ts b/packages/cli/src/commands/log.tsindex f0cc2b8..aff28f9 100644--- a/packages/cli/src/commands/log.ts+++ b/packages/cli/src/commands/log.ts@@ -558,7 +558,11 @@ export async function show(opts: ShowOptions): Promise<ShowModel> {` ${candidate.sessionId} · ${candidate.label}${candidate.id === candidate.label ? "" : ` (${candidate.id})`} ${candidate.title}`,);}- throw new CliError(`"${opts.ref}" is ambiguous; use a longer prefix`);+ throw new CliError(+ COMMIT_REF.test(opts.ref)+ ? `commit ${opts.ref} comes from several thoughts; open one by its message hash`+ : `"${opts.ref}" is ambiguous; use a longer prefix`,+ );}const { session, messages, message } = result.hit;diff --git a/packages/cli/src/commands/pr.ts b/packages/cli/src/commands/pr.tsindex 1e0e677..5ae2297 100644--- a/packages/cli/src/commands/pr.ts+++ b/packages/cli/src/commands/pr.ts@@ -38,8 +38,8 @@ export interface PrCommit {short: string;at: string;subject: string;- /** The `Thought:` trailer value, when the commit carries one. */- thought?: string;+ /** The messages the commit names; a squash can name several. */+ thoughts?: string[];/** Repository-relative paths; empty when git no longer has the commit. */files: string[];}@@ -227,53 +227,62 @@ export function buildPrModel(input: BuildPrInput): PrModel {const commitCounts = new Map<string, number>();for (const commit of input.commits) {- const id = commit.thought;- const hit = id === undefined ? undefined : index.get(id);- if (id === undefined || hit === undefined) {+ const ids = commit.thoughts ?? [];+ const known = ids.filter((id) => index.has(id));+ if (known.length === 0) {+ const named = ids[0];unlinked.push({full: commit.full,short: commit.short,subject: commit.subject,- ...(id === undefined ? {} : { thought: id }),+ ...(named === undefined ? {} : { thought: named }),});continue;}- const { session } = hit.entry;- let thought = thoughts.get(id);- if (thought === undefined) {- const message = hit.message;- thought = {- id,- shortId: shortHash(id),- label: message.label ?? id,- sessionId: session.sessionId,- shortSessionId: session.sessionId.slice(0, 8),- sessionTitle: titleOf(session.sessionId, session.title),- title: message.title,- ...(message.summary === undefined ? {} : { summary: message.summary }),- ...(message.why === undefined ? {} : { why: message.why }),- ...(message.decidedBy === undefined ? {} : { decidedBy: message.decidedBy }),- alternatives: message.alternatives ?? [],- agentDecisions: (message.agentDecisions ?? []).map((decision) => ({- title: decision.title,- why: decision.why,- alternatives: decision.alternatives ?? [],- })),- commits: [],- };- thoughts.set(id, thought);- if (!entries.has(session.sessionId)) {- sessionOrder.push(session.sessionId);- entries.set(session.sessionId, hit.entry);- labels.set(session.sessionId, []);- thoughtCounts.set(session.sessionId, 0);- commitCounts.set(session.sessionId, 0);+ // A squash names several messages, but it is still one commit in each session.+ const counted = new Set<string>();+ for (const id of known) {+ const hit = index.get(id) as { entry: EffectiveSession; message: ViewNode };+ const { session } = hit.entry;+ let thought = thoughts.get(id);+ if (thought === undefined) {+ const message = hit.message;+ thought = {+ id,+ shortId: shortHash(id),+ label: message.label ?? id,+ sessionId: session.sessionId,+ shortSessionId: session.sessionId.slice(0, 8),+ sessionTitle: titleOf(session.sessionId, session.title),+ title: message.title,+ ...(message.summary === undefined ? {} : { summary: message.summary }),+ ...(message.why === undefined ? {} : { why: message.why }),+ ...(message.decidedBy === undefined ? {} : { decidedBy: message.decidedBy }),+ alternatives: message.alternatives ?? [],+ agentDecisions: (message.agentDecisions ?? []).map((decision) => ({+ title: decision.title,+ why: decision.why,+ alternatives: decision.alternatives ?? [],+ })),+ commits: [],+ };+ thoughts.set(id, thought);+ if (!entries.has(session.sessionId)) {+ sessionOrder.push(session.sessionId);+ entries.set(session.sessionId, hit.entry);+ labels.set(session.sessionId, []);+ thoughtCounts.set(session.sessionId, 0);+ commitCounts.set(session.sessionId, 0);+ }+ thoughtCounts.set(session.sessionId, (thoughtCounts.get(session.sessionId) ?? 0) + 1);+ }+ thought.commits.push(commit);+ labels.get(session.sessionId)?.push(labelIndex(thought.label) ?? 0);+ if (!counted.has(session.sessionId)) {+ counted.add(session.sessionId);+ commitCounts.set(session.sessionId, (commitCounts.get(session.sessionId) ?? 0) + 1);}- thoughtCounts.set(session.sessionId, (thoughtCounts.get(session.sessionId) ?? 0) + 1);}- thought.commits.push(commit);- labels.get(session.sessionId)?.push(labelIndex(thought.label) ?? 0);- commitCounts.set(session.sessionId, (commitCounts.get(session.sessionId) ?? 0) + 1);}const goals: PrGoal[] = [];@@ -521,7 +530,7 @@ export async function pr(opts: PrOptions): Promise<PrModel> {const sessions = await loadEffectiveSessions(root, opts.io);const trailers =commits.length === 0- ? new Map<string, string>()+ ? new Map<string, string[]>(): await readThoughtTrailers(gitRoot, {env,since: earliestSessionStart(sessions.map((entry) => entry.session)),@@ -540,11 +549,11 @@ export async function pr(opts: PrOptions): Promise<PrModel> {policy: (await cogitIgnored(root)) ? "ignore" : "commit",sessions,commits: commits.map((commit) => {- const thought = trailers.get(commit.full);+ const thoughts = trailers.get(commit.full);return {...commit,files: files.get(commit.full) ?? [],- ...(thought === undefined ? {} : { thought }),+ ...(thoughts === undefined ? {} : { thoughts }),};}),});diff --git a/packages/cli/src/thought.ts b/packages/cli/src/thought.tsindex bfc875b..734b61d 100644--- a/packages/cli/src/thought.ts+++ b/packages/cli/src/thought.ts@@ -18,7 +18,8 @@ const exec = promisify(execFile);* 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.+ * and never depends on the agent remembering a rule. A squash folds several+ * commits' messages into one, so one commit can name several messages.*//** The trailer key git and cogit share. */@@ -30,6 +31,20 @@ const THOUGHT_VALUE = /^h[0-9a-f]{12}$/;/** A full commit hash: what `%H` prints and what the records store. */const FULL_HASH = /^[0-9a-f]{40}$/;+/**+ * A `Thought:` line anywhere in a commit message. Not only git's final trailer+ * block: `git merge --squash` quotes the commits indented inside the body, and a+ * squash can leave several blocks. The whole line has to match, so prose that+ * mentions a thought is not a link.+ */+const THOUGHT_LINE = new RegExp(`^[ \\t]*${THOUGHT_TRAILER}:[ \\t]*(h[0-9a-f]{12})[ \\t]*$`, "gim");++/** Precedes each commit in the `git log` output `parseThoughtTrailers` reads. */+const COMMIT_MARK = "\x01";++/** Commit bodies add up in a long history; execFile's 1 MB default would lose every link. */+const LOG_MAX_BUFFER = 256 * 1024 * 1024;+export interface TrailerOptions {/** The project root (where `.cogit/` lives). */dir: string;@@ -80,6 +95,25 @@ async function writeTrailer(messageFile: string, value: string): Promise<void> {]);}+/**+ * True while git replays existing commits: a rebase (`rebase-merge`,+ * `rebase-apply`, which `git am` shares) or a cherry-pick. Git runs+ * `prepare-commit-msg` for each of them, and an old commit is not about the+ * session's newest message. Unknown state counts as not replaying.+ */+async function replayingCommits(dir: string, env: NodeJS.ProcessEnv): Promise<boolean> {+ let gitDir: string;+ try {+ const { stdout } = await exec("git", ["-C", dir, "rev-parse", "--absolute-git-dir"], { env });+ gitDir = String(stdout).trim();+ } catch {+ return false;+ }+ const states = ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD"];+ const found = await Promise.all(states.map((state) => readable(resolve(gitDir, state))));+ return found.includes(true);+}+/*** 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@@ -88,13 +122,14 @@ async function writeTrailer(messageFile: string, value: string): Promise<void> {* 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.+ * Merges, squashes, replayed commits 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;+ if (await replayingCommits(opts.dir, env)) return false;const agent = defaultAgent();const named = (env[agent.commitSessionEnv] ?? "").trim();@@ -132,22 +167,19 @@ export async function addThoughtTrailer(opts: TrailerOptions): Promise<boolean>}/**- * Parses `%H%x00%(trailers:key=Thought,valueonly)` lines into commit → message.- * A commit with several Thought values keeps the first valid one.+ * Parses `%x01%H%x00%B` records into commit → the messages it names, in the order+ * the commit message lists them, each once.*/-export function parseThoughtTrailers(stdout: string): Map<string, string> {- const out = new Map<string, string>();- for (const line of stdout.split("\n")) {- const separator = line.indexOf("\0");+export function parseThoughtTrailers(stdout: string): Map<string, string[]> {+ const out = new Map<string, string[]>();+ for (const record of stdout.split(COMMIT_MARK)) {+ const separator = record.indexOf("\0");if (separator === -1) continue;- const commit = line.slice(0, separator);+ const commit = record.slice(0, separator);if (!FULL_HASH.test(commit)) continue;- for (const value of line.slice(separator + 1).split(/[,\s]+/)) {- if (THOUGHT_VALUE.test(value)) {- out.set(commit, value);- break;- }- }+ const body = record.slice(separator + 1);+ const thoughts = [...body.matchAll(THOUGHT_LINE)].map((match) => match[1] as string);+ if (thoughts.length > 0) out.set(commit, [...new Set(thoughts)]);}return out;}@@ -159,36 +191,42 @@ export interface ReadTrailerOptions {}/**- * The `Thought:` trailers of this repository (Story 9.4), keyed by full commit+ * The `Thought:` lines of this repository (Story 9.4), keyed by full commit* hash. A missing repository, an old git or an unreadable log only means no* links: the map and the read verbs keep working.*/export async function readThoughtTrailers(root: string,opts: ReadTrailerOptions = {},-): Promise<Map<string, string>> {+): Promise<Map<string, string[]>> {const gitRoot = await findGitRoot(root);if (gitRoot === undefined) return new Map();const args = ["-C",gitRoot,"log",- "--format=%H%x00%(trailers:key=Thought,valueonly)",+ "--format=%x01%H%x00%B",+ "--extended-regexp",+ "--regexp-ignore-case",+ `--grep=^[[:space:]]*${THOUGHT_TRAILER}:`,...(opts.since === undefined ? [] : [`--since=${opts.since}`]),];try {- const { stdout } = await exec(- "git",- args,- opts.env === undefined ? undefined : { env: opts.env },- );+ const { stdout } = await exec("git", args, {+ maxBuffer: LOG_MAX_BUFFER,+ ...(opts.env === undefined ? {} : { env: opts.env }),+ });return parseThoughtTrailers(String(stdout));} catch {return new Map();}}-/** The `Thought:` value of one commit, or undefined (no trailer, no such commit). */+/**+ * The one message a commit's final trailer block names, or undefined (no trailer,+ * no such commit). This is what the commit itself was made for; a squash's quoted+ * lines are not, so the Shape path never draws one from them.+ */export async function readCommitThought(root: string,ref: string,@@ -220,9 +258,12 @@ function sameCommit(recorded: string, commit: string): boolean {return commit.startsWith(recorded) || recorded.startsWith(commit);}-function thoughtOf(recorded: string, trailers: ReadonlyMap<string, string>): string | undefined {- for (const [commit, thought] of trailers) {- if (sameCommit(recorded, commit)) return thought;+function thoughtsOf(+ recorded: string,+ trailers: ReadonlyMap<string, readonly string[]>,+): readonly string[] | undefined {+ for (const [commit, thoughts] of trailers) {+ if (sameCommit(recorded, commit)) return thoughts;}return undefined;}@@ -231,19 +272,22 @@ function thoughtOf(recorded: string, trailers: ReadonlyMap<string, string>): str* Attaches trailer-carrying commits to their message nodes (Story 9.4): the* union of the commits the agent wrote and the commits git says belong to the* message. A commit the agent listed under a different message moves to the- * trailer's message — the trailer wins. A trailer for a message the record never+ * trailer's message — the trailer wins — and a squash's commit lands on every+ * message it names. A trailer for a message the record never* summarized has nowhere to land and is left for a later build.*/export function attachThoughtTrailers(sessions: readonly Session[],- trailers: ReadonlyMap<string, string>,+ trailers: ReadonlyMap<string, readonly string[]>,): Session[] {if (trailers.size === 0) return [...sessions];const byThought = new Map<string, string[]>();- for (const [commit, thought] of trailers) {- const list = byThought.get(thought);- if (list === undefined) byThought.set(thought, [commit]);- else if (!list.some((hash) => sameCommit(hash, commit))) list.push(commit);+ for (const [commit, thoughts] of trailers) {+ for (const thought of thoughts) {+ const list = byThought.get(thought);+ if (list === undefined) byThought.set(thought, [commit]);+ else if (!list.some((hash) => sameCommit(hash, commit))) list.push(commit);+ }}return sessions.map((session) => {@@ -252,8 +296,8 @@ export function attachThoughtTrailers(if (node.kind !== "message") return node;const current = node.commits ?? [];const kept = current.filter((hash) => {- const thought = thoughtOf(hash, trailers);- return thought === undefined || thought === node.id;+ const thoughts = thoughtsOf(hash, trailers);+ return thoughts === undefined || thoughts.includes(node.id);});const claimed = (byThought.get(node.id) ?? []).filter((commit) => !kept.some((hash) => sameCommit(hash, commit)),diff --git a/packages/cli/test/pr.test.ts b/packages/cli/test/pr.test.tsindex 53ec529..77024fc 100644--- a/packages/cli/test/pr.test.ts+++ b/packages/cli/test/pr.test.ts@@ -160,6 +160,28 @@ describe("cogit pr (Story 10.1)", () => {await commit({ "notes.txt": "notes\n" }, "chore: tidy notes");});+ it("lists a squashed commit under every thought it names, once per session", async () => {+ const before = await pr({ dir: root, io });+ await writeFile(join(root, "squashed.txt"), "squashed\n");+ await git("add", "squashed.txt");+ await git(+ "commit",+ "-q",+ "-m",+ "feat: squash the branch",+ "-m",+ ` one\n\n Thought: ${A}\n\n two\n\n Thought: ${D}`,+ );++ const model = await pr({ dir: root, io });+ for (const id of [A, D]) {+ const thought = model.thoughts.find((entry) => entry.id === id);+ expect(thought?.commits.map((entry) => entry.subject)).toContain("feat: squash the branch");+ }+ expect(model.sessions[0]?.commitCount).toBe((before.sessions[0]?.commitCount ?? 0) + 1);+ expect(model.unlinked.map((entry) => entry.subject)).not.toContain("feat: squash the branch");+ });+it("groups the branch's commits by thought, in commit order", async () => {const model = await pr({ dir: root, io });expect(model.base.ref).toBe("main");diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex 89dc987..259cf45 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -120,6 +120,46 @@ describe("commands through the CLI", () => {expect(io.lines.join("\n")).toContain("not: Keep the loop — It loses data.");});+ it("show names every thought of a squashed commit", async () => {+ const run = promisify(execFile);+ const git = async (...args: string[]): Promise<string> =>+ (await run("git", ["-C", root, ...args])).stdout;+ await git("init", "-q");+ await cli("init", root, "--yes", "--retention", "keep");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await git(+ "commit",+ "-q",+ "--allow-empty",+ "-m",+ "feat: squashed",+ "-m",+ " Thought: h111111111111\n\n Thought: h222222222222",+ );+ const message = (id: string, title: string) => ({+ id,+ parent: null,+ kind: "message",+ title,+ at: T0,+ });+ const record = {+ schema: 1,+ sessionId: "s1",+ agent: "claude-code",+ title: "CLI session",+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [message("h111111111111", "One"), message("h222222222222", "Two")],+ };+ await writeFile(join(root, ".cogit", "sessions", "s1.json"), JSON.stringify(record));+ const short = (await git("rev-parse", "--short=7", "HEAD")).trim();+ expect(await cli("show", short, "-C", root)).toContain("comes from several thoughts");+ expect(io.lines.join("\n")).toContain("h222222222222");+ });+it("runs config hint-off and hint-on", async () => {await cli("config", "hint-off", root);expect(io.lines.at(-1)).toBe(`Setup hint off in ${root}`);diff --git a/packages/cli/test/thought-rebase.test.ts b/packages/cli/test/thought-rebase.test.tsindex d042312..cc57b93 100644--- a/packages/cli/test/thought-rebase.test.ts+++ b/packages/cli/test/thought-rebase.test.ts@@ -1,10 +1,10 @@import { execFile } from "node:child_process";-import { mkdtemp, writeFile } from "node:fs/promises";+import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { promisify } from "node:util";import { describe, expect, it } from "vitest";-import { readCommitThought } from "../src/thought.js";+import { readCommitThought, readThoughtTrailers } from "../src/thought.js";const run = promisify(execFile);@@ -24,7 +24,7 @@ const SECOND = "h222222222222";* The link is a trailer in the commit message naming a *message*, never a* commit hash, so it has to survive the rewrites that change commit hashes.*/-describe("the Thought trailer across history rewrites", () => {+describe("the Thought link across history rewrites", () => {const git = async (dir: string, ...args: string[]): Promise<string> =>(await run("git", ["-C", dir, ...args], { env: ENV })).stdout;@@ -58,7 +58,7 @@ describe("the Thought trailer across history rewrites", () => {await git(dir, "commit", "-q", "-m", message, "-m", `Thought: ${thought}`);};- it("loses the link in a squash, whose message quotes the commits indented", async () => {+ it("keeps both links through a squash merge, whose message quotes the commits", async () => {const dir = await repo();await git(dir, "checkout", "-q", "-b", "feature");await commitFile(dir, "one.txt", "one", FIRST);@@ -69,9 +69,63 @@ describe("the Thought trailer across history rewrites", () => {// inside the body, so git reads no trailer at the end of the message.await git(dir, "commit", "-q", "--no-edit");+ const head = (await git(dir, "rev-parse", "HEAD")).trim();+ const links = await readThoughtTrailers(dir, { env: ENV });+ expect(links.get(head)).toEqual([SECOND, FIRST]);+ // The squash was not made for one message, so no Shape is drawn from it.await expect(readCommitThought(dir, "HEAD")).resolves.toBeUndefined();});+ it("keeps both links through an interactive squash, which leaves two blocks", async () => {+ const dir = await repo();+ await commitFile(dir, "one.txt", "one", FIRST);+ await commitFile(dir, "two.txt", "two", SECOND);+ await run("git", ["-C", dir, "rebase", "-q", "-i", "HEAD~2"], {+ env: { ...ENV, GIT_SEQUENCE_EDITOR: "sed -i.bak '2s/^pick/squash/'", GIT_EDITOR: "true" },+ });++ const head = (await git(dir, "rev-parse", "HEAD")).trim();+ expect((await readThoughtTrailers(dir, { env: ENV })).get(head)).toEqual([FIRST, SECOND]);+ });++ it("finds no link in a squash that keeps only a title", async () => {+ const dir = await repo();+ await git(dir, "checkout", "-q", "-b", "feature");+ await commitFile(dir, "one.txt", "one", FIRST);+ await git(dir, "checkout", "-q", "main");+ await git(dir, "merge", "-q", "--squash", "feature");+ await git(dir, "commit", "-q", "-m", "PR title (#1)");++ const head = (await git(dir, "rev-parse", "HEAD")).trim();+ expect((await readThoughtTrailers(dir, { env: ENV })).has(head)).toBe(false);+ });++ /** What git shows the hook while it replays: `addThoughtTrailer` relies on this. */+ it("marks a rebase and a cherry-pick where the commit hook can see them", async () => {+ const dir = await repo();+ await git(dir, "checkout", "-q", "-b", "feature");+ await commitFile(dir, "one.txt", "one", FIRST);+ await git(dir, "checkout", "-q", "-b", "other", "main");+ await commitFile(dir, "two.txt", "two", SECOND);+ const picked = (await git(dir, "rev-parse", "HEAD")).trim();+ await git(dir, "checkout", "-q", "main");++ const log = join(dir, ".git", "hook.log");+ const hook = join(dir, ".git", "hooks", "prepare-commit-msg");+ await writeFile(+ hook,+ `#!/bin/sh\nfor s in rebase-merge rebase-apply CHERRY_PICK_HEAD; do [ -e "$(git rev-parse --absolute-git-dir)/$s" ] && echo "$s" >> "${log}"; done; exit 0\n`,+ );+ await chmod(hook, 0o755);++ await git(dir, "cherry-pick", picked);+ expect(await readFile(log, "utf8")).toContain("CHERRY_PICK_HEAD");+ await writeFile(log, "");+ await git(dir, "checkout", "-q", "feature");+ await git(dir, "rebase", "-q", "main");+ expect(await readFile(log, "utf8")).toContain("rebase-merge");+ });+it("keeps the link a rewritten message ends with on purpose", async () => {const dir = await repo();await git(dir, "checkout", "-q", "-b", "feature");diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.tsindex cb537db..e01d2a9 100644--- a/packages/cli/test/thought.test.ts+++ b/packages/cli/test/thought.test.ts@@ -1,6 +1,6 @@import { execFile } from "node:child_process";import { existsSync } from "node:fs";-import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";+import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { dirname, join, relative } from "node:path";import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";@@ -181,6 +181,63 @@ describe("the thought behind a commit (Story 9.4)", () => {expect(text).not.toContain(thoughtOf());});+ it("lands a squashed commit on every message it names, and keeps it where it is listed", () => {+ const squashed = "a".repeat(40);+ const sessions = [+ session([+ { id: "h111111111111", parent: null, kind: "message", title: "A", commits: [squashed] },+ { id: "h222222222222", parent: null, kind: "message", title: "B", commits: [] },+ { id: "h333333333333", parent: null, kind: "message", title: "C", commits: [] },+ ]),+ ];+ const [next] = attachThoughtTrailers(+ sessions,+ new Map([[squashed, ["h111111111111", "h222222222222"]]]),+ );+ const [a, b, c] = next?.nodes ?? [];+ expect(a?.commits).toEqual([squashed]);+ expect(b?.commits).toEqual([squashed]);+ expect(c?.commits).toEqual([]);+ });++ it("leaves a replayed commit alone during a rebase or a cherry-pick", async () => {+ await writeHead();+ const gitDir = (await git("rev-parse", "--absolute-git-dir")).trim();+ for (const state of ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD"]) {+ await writeFile(join(gitDir, state), "");+ const file = await messageFile();+ expect(+ await addThoughtTrailer({+ dir: root,+ messageFile: file,+ source: "message",+ env,+ now: NOW,+ }),+ ).toBe(false);+ expect(await readMessage(file)).toBe("feat: change the code\n");+ await rm(join(gitDir, state));+ }+ const file = await messageFile();+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(true);+ });++ it("counts as no replay when it cannot ask git", async () => {+ await writeHead();+ const file = await messageFile();+ expect(+ await addThoughtTrailer({+ dir: root,+ messageFile: file,+ source: "message",+ env: { ...env, PATH: "/nonexistent" },+ now: NOW,+ }),+ ).toBe(true);+ });+it("skips merges, squashes and an empty message-file argument", async () => {await writeHead();for (const source of ["merge", "squash"]) {@@ -366,19 +423,21 @@ describe("the thought behind a commit (Story 9.4)", () => {});describe("reading trailers", () => {- it("parses one commit line per commit, keeping the first valid id", () => {+ it("reads every whole Thought line of a commit message, each once", () => {const a = "a".repeat(40);const b = "b".repeat(40);+ const c = "c".repeat(40);const parsed = parseThoughtTrailers([- `${a}\0h111111111111, h222222222222`,- `${b}\0not-a-thought`,- "no separator",- `${a}\0`,+ `\x01${a}\0squash\n\n one\n\n Thought: h111111111111\n\nThought: h222222222222\nthought: h111111111111\n`,+ `\x01${b}\0prose\n\nThis mentions Thought: h333333333333 in a sentence\nThought: not-a-thought\n`,+ "\x01no separator",+ `\x01not-a-hash\0Thought: h444444444444\n`,+ `\x01${c}\0`,].join("\n"),);- expect(parsed.get(a)).toBe("h111111111111");- expect(parsed.has(b)).toBe(false);+ expect(parsed.get(a)).toEqual(["h111111111111", "h222222222222"]);+ expect(parsed.size).toBe(1);});it("reads the trailers git holds, and only since a date", async () => {@@ -394,7 +453,7 @@ describe("the thought behind a commit (Story 9.4)", () => {`Thought: ${thought}`,);const full = (await git("rev-parse", "HEAD")).trim();- expect((await readThoughtTrailers(root, { env })).get(full)).toBe(thought);+ expect((await readThoughtTrailers(root, { env })).get(full)).toEqual([thought]);expect(await readThoughtTrailers(root, { env, since: "2030-01-01T00:00:00.000Z" })).toEqual(new Map(),);@@ -423,9 +482,9 @@ describe("the thought behind a commit (Story 9.4)", () => {const [next] = attachThoughtTrailers(sessions,new Map([- [conflict, "h222222222222"],- [attached, "h222222222222"],- ["c".repeat(40), "h999999999999"],+ [conflict, ["h222222222222"]],+ [attached, ["h222222222222"]],+ ["c".repeat(40), ["h999999999999"]],]),);const [a, b, phase] = next?.nodes ?? [];