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
feat(git): link code commits to the thought behind them
Eren12c49dedaf51
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 31f99a3..670f63d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- The link from code back to the thought: a git `prepare-commit-msg` hook adds a `Thought: h…` trailer naming the newest message of the session in `.cogit/HEAD` (written by the `UserPromptSubmit` hook), so every commit carries the message it came out of. It skips merges and squashes, a `.cogit/HEAD` older than the new `trailerMaxAgeHours` setting (6 hours by default), a project whose records stay out of git and an unreadable transcript, keeps a trailer an `--amend` already had, and never blocks a commit. Build, `log`, `blame` and the Files view read the trailers back with `git log` and attach those commits to their message nodes (a trailer wins over a hash the agent listed elsewhere); `cogit show <commit-sha>` opens the thought behind a commit. `init` and `cogit config git commit` install both hooks into the directory git really uses, and `cogit hooks uninstall` removes only cogit's marked block, leaving the user's own hook lines untouched.- The record travels with the repo: `init` now answers **yes** to committing the session records, which puts `.cogit/sessions/` and `project.json` in git while a generated `.cogit/.gitignore` keeps the local state (conversations, hooks state, locks, inbox, map, `HEAD`, backups) out; `cogit config git commit|ignore` switches an existing project without deleting anything. A git `pre-commit` hook stages the current session's record files (`.cogit/HEAD`, written by a new `UserPromptSubmit` hook) with the next code commit, but never creates a record-only commit and works with `git commit -a` and `git commit <paths>`. Each session gets an `author` (git `user.name`, else the OS user) on its first write, shown on the map's session row and in `log`, and `project.json` is written with sorted keys and one epoch per line so git merges it. New settings `shareConversations` (commit the raw chat too, off by default) and `recordCommit` (`ask`, `auto` or `off`: what to do with the messages recorded after the last code commit) are in Settings → Recording; a clone without the chat says "This conversation is not on this machine".### Changeddiff --git a/packages/cli/src/commands/blame.ts b/packages/cli/src/commands/blame.tsindex 4171101..241a2d7 100644--- a/packages/cli/src/commands/blame.ts+++ b/packages/cli/src/commands/blame.ts@@ -6,6 +6,7 @@ import { CliError, type Io } from "../io.js";import { projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";import { loadAllSessions, loadProject } from "../store/stores.js";+import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";import { buildMessages } from "../view/lineage.js";/**@@ -95,9 +96,16 @@ export async function blame(opts: BlameOptions): Promise<BlameHit[]> {throw new CliError(`git could not read ${opts.target}: ${gitMessage(err)}`);}- const sessions = [...(await loadAllSessions(root, io.warn))].sort(+ const loaded = [...(await loadAllSessions(root, io.warn))].sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.sessionId.localeCompare(b.sessionId),);+ // A commit whose message carries a `Thought:` trailer (Story 9.4) belongs to+ // that message even when the agent's record did not list the hash.+ const trailers = await readThoughtTrailers(root, {+ env: io.env,+ since: earliestSessionStart(loaded),+ });+ const sessions = attachThoughtTrailers(loaded, trailers);const mapUrl = pathToFileURL(projectPaths(root).html).href;const hits: BlameHit[] = [];const seen = new Set<string>();diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex c5ce126..192dab1 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -26,6 +26,7 @@ import { withLock } from "../store/lock.js";import { projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";+import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";import { type ChatTurn, displayTurn, excerpt, readConversation } from "../transcript.js";import { buildFileHistory, modelSessions } from "../view/files.js";import { buildViewModel, embedViewModel } from "../view/lineage.js";@@ -268,10 +269,18 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelconst sessions = await loadAllSessions(root, io.warn);const transcripts = await collectTranscripts(io.env);const views = await readTranscriptViews(sessions, transcripts, root, io);- const commits = await commitInfo(root, views.sessions);+ // The `Thought:` trailers git holds (Story 9.4) attach commits to the+ // message they carry out, so the map, the file history and `blame` agree+ // even when the agent's record did not list the hash.+ const trailers = await readThoughtTrailers(root, {+ env: io.env,+ since: earliestSessionStart(views.sessions),+ });+ const withThoughts = attachThoughtTrailers(views.sessions, trailers);+ const commits = await commitInfo(root, withThoughts);const built = buildViewModel({project: project.data,- sessions: views.sessions,+ sessions: withThoughts,path: root,generatedAt,transcripts: new Set(transcripts.keys()),diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.tsindex 319a7b1..3ae43f9 100644--- a/packages/cli/src/commands/config.ts+++ b/packages/cli/src/commands/config.ts@@ -1,5 +1,5 @@import { ensureCogitGitignore, ensureGitignore, findGitRoot, type GitPolicy } from "../git.js";-import { installGitHook } from "../git-hooks.js";+import { installGitHooks } from "../git-hooks.js";import { CliError, type Io } from "../io.js";import { Config, type RegistryEntry } from "../schema/config.js";import { refreshShareConversations } from "../share.js";@@ -79,7 +79,7 @@ export async function configGit(dir: string, policy: GitPolicy, io: Io): Promiseconst added = await ensureGitignore(root, policy);const config = await loadConfig(io.env);await ensureCogitGitignore(root, policy, config.shareConversations);- if (policy === "commit") await installGitHook(root, "pre-commit");+ if (policy === "commit") await installGitHooks(root);io.out(`Git policy for ${project.data.name}: ${policy}`);if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);}diff --git a/packages/cli/src/commands/hooks.ts b/packages/cli/src/commands/hooks.tsnew file mode 100644index 0000000..6d942ec--- /dev/null+++ b/packages/cli/src/commands/hooks.ts@@ -0,0 +1,22 @@+import { uninstallGitHooks } from "../git-hooks.js";+import { CliError, type Io } from "../io.js";+import { resolveProjectRoot } from "../store/root.js";+import { loadProject } from "../store/stores.js";++/**+ * `cogit hooks uninstall` (Story 9.4): removes only the marked block cogit added+ * to a git hook, so a user who wants their hooks back exactly as they were can+ * get them without editing files by hand. No record and no setting changes.+ */+export async function hooksUninstall(dir: string, io: Io): Promise<void> {+ const { root } = await resolveProjectRoot(dir);+ const project = await loadProject(root);+ if (!project.found) throw new CliError(`${root} is not initialized; run \`cogit init\` first`);+ if (!project.ok) throw new CliError(project.error);+ const removed = await uninstallGitHooks(root);+ io.out(+ removed.length === 0+ ? "No cogit hook blocks to remove."+ : `Removed the cogit block from: ${removed.join(", ")}`,+ );+}diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 571f2fc..c408cb8 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -16,7 +16,7 @@ import {type GitPolicy,refreshCogitGitignore,} from "../git.js";-import { installGitHook } from "../git-hooks.js";+import { installGitHooks } from "../git-hooks.js";import { CliError, type Io } from "../io.js";import { readJson } from "../store/fs.js";import { migrateProject } from "../store/migrate.js";@@ -141,9 +141,9 @@ export async function register(io: Io, root: string, name: string): Promise<void/*** Applies a policy to the two ignore files and, under `commit`, installs the git- * pre-commit hook that carries the current session's record (Story 9.3). Each- * step is best-effort: a read-only `.gitignore` or a repository git will not- * report hooks for must never fail setup.+ * hooks that carry the current session's record and link it to the commit+ * (Stories 9.3, 9.4). Each step is best-effort: a read-only `.gitignore` or a+ * repository git will not report hooks for must never fail setup.*/async function applyGitPolicy(io: Io,@@ -160,14 +160,12 @@ async function applyGitPolicy(ensureCogitGitignore(root, policy, shareConversations),);if (policy === "commit")- await bestEffort(io, "could not install the pre-commit hook", () =>- installGitHook(root, "pre-commit"),- );+ await bestEffort(io, "could not install the git hooks", () => installGitHooks(root));}/*** Brings an already initialized project up to date: a repository that commits- * its records gets the new `.cogit/.gitignore` and the hook, without changing the+ * its records gets the new `.cogit/.gitignore` and the hooks, without changing the* policy the user chose at setup.*/async function refreshGitIntegration(io: Io, root: string): Promise<void> {@@ -175,7 +173,7 @@ async function refreshGitIntegration(io: Io, root: string): Promise<void> {await bestEffort(io, "could not refresh the git integration", async () => {if (await cogitIgnored(root)) return;await refreshCogitGitignore(root, (await loadConfig(io.env)).shareConversations);- await installGitHook(root, "pre-commit");+ await installGitHooks(root);});}diff --git a/packages/cli/src/commands/log.ts b/packages/cli/src/commands/log.tsindex 90c22f8..4e5bb81 100644--- a/packages/cli/src/commands/log.ts+++ b/packages/cli/src/commands/log.ts@@ -5,6 +5,7 @@ import type { LineageNode, Session } from "../schema/session.js";import { applyEvents, readEvents } from "../store/events.js";import { resolveProjectRoot } from "../store/root.js";import { loadAllSessions, loadProject } from "../store/stores.js";+import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";import { buildFileHistory, type FileSourceSession } from "../view/files.js";import { buildMessages } from "../view/lineage.js";import type { ViewFile, ViewNode } from "../view/model.js";@@ -34,7 +35,13 @@ export interface EffectiveSession {/** Every valid session of the project, with the ids and structure the map draws. */export async function loadEffectiveSessions(root: string, io: Io): Promise<EffectiveSession[]> {const sessions = await loadAllSessions(root, io.warn);- const out: EffectiveSession[] = [];+ // The `Thought:` trailers git already holds (Story 9.4): a commit whose message+ // names a message belongs to it even when the agent's record left it out.+ const trailers = await readThoughtTrailers(root, {+ env: io.env,+ since: earliestSessionStart(sessions),+ });+ const loaded: EffectiveSession[] = [];for (const session of sessions) {// The transcript (or the conversation store) names old `m1` nodes and holds// the hash of each message; a session without either keeps its stored ids.@@ -42,8 +49,18 @@ export async function loadEffectiveSessions(root: string, io: Io): Promise<Effecconst upgraded = turns ? upgradeSessionIds(session, turns) : session;const events = await readEvents(root, session.sessionId);const effective: Session = { ...upgraded, nodes: applyEvents(upgraded.nodes, events) };- out.push({ session: effective, messages: buildMessages(effective.nodes), turns });+ loaded.push({ session: effective, messages: buildMessages(effective.nodes), turns });}+ const withThoughts = attachThoughtTrailers(+ loaded.map((entry) => entry.session),+ trailers,+ );+ const out = loaded.map((entry, index) => {+ const session = withThoughts[index] as Session;+ return session === entry.session+ ? entry+ : { ...entry, session, messages: buildMessages(session.nodes) };+ });return out.sort((a, b) =>a.session.startedAt.localeCompare(b.session.startedAt) ||@@ -331,6 +348,13 @@ export type RefResult =const HASH_REF = /^h[0-9a-f]{6,12}$/;const SESSION_LABEL_REF = /^([A-Za-z0-9][A-Za-z0-9_.-]{0,127}):m([1-9][0-9]*)$/;+/** A raw git commit hash: 7–40 lowercase hex, no `h` prefix (`h…` is a message). */+const COMMIT_REF = /^[0-9a-f]{7,40}$/;++/** A record may hold seven characters of a hash and git forty; either direction matches. */+function sameCommit(recorded: string, commit: string): boolean {+ return commit.startsWith(recorded) || recorded.startsWith(commit);+}/*** Resolves a `<ref>` against every session. Errors stay data, so the command can@@ -362,11 +386,40 @@ export function resolveRef(sessions: readonly EffectiveSession[], ref: string):};}+ // A commit the `Thought:` trailer (Story 9.4) attached to a message opens that+ // message: `cogit show <commit-sha>` is the way from code back to the why.+ if (COMMIT_REF.test(ref)) {+ const hits = sessions.flatMap((entry) =>+ entry.messages+ .filter((message) => (message.commits ?? []).some((hash) => sameCommit(hash, ref)))+ .map((message) => ({ entry, message })),+ );+ if (hits.length === 0)+ return { kind: "unknown", reason: `no recorded thought for commit ${ref}` };+ if (hits.length > 1) {+ return {+ kind: "ambiguous",+ candidates: hits.map(({ entry, message }) => ({+ sessionId: entry.session.sessionId,+ id: message.id,+ label: message.label ?? message.id,+ title: message.title,+ })),+ };+ }+ const hit = hits[0] as { entry: EffectiveSession; message: ViewNode };+ return {+ kind: "ok",+ hit: { session: hit.entry.session, messages: hit.entry.messages, message: hit.message },+ };+ }+const sessionLabel = SESSION_LABEL_REF.exec(ref);if (sessionLabel === null)return {kind: "invalid",- reason: "use a message hash (h + 6..12 hex) or <session-id-prefix>:mN",+ reason:+ "use a message hash (h + 6..12 hex), <session-id-prefix>:mN, or a commit hash (7..40 hex)",};const prefix = sessionLabel[1] as string;diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.tsindex 6b01013..5d3d035 100644--- a/packages/cli/src/git-hooks.ts+++ b/packages/cli/src/git-hooks.ts@@ -1,8 +1,9 @@-import { chmod, mkdir, readFile, stat } from "node:fs/promises";+import { chmod, mkdir, readFile, rm, stat } from "node:fs/promises";import { join } from "node:path";import { findGitRoot, gitHooksDir } from "./git.js";import { stageSessionFiles } from "./session-git.js";import { atomicWrite } from "./store/fs.js";+import { addThoughtTrailer } from "./thought.js";/*** Git hook installation (Story 9.3). cogit never owns a hook file: it adds a@@ -37,6 +38,17 @@ export function withHookBlock(text: string, block: string): string {return `${text}${sep}\n${block}\n`;}+/** Removes the marked block and the blank separator `withHookBlock` added. */+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;+}++/** True when what is left is only the shebang `installGitHook` wrote itself. */+function onlyGeneratedShebang(text: string): boolean {+ return text.split("\n").every((line) => line.trim() === "" || line.trim() === "#!/bin/sh");+}+/*** Installs the block into the hook file git actually uses. Returns true when the* file changed, false when the block was already current or the repository does@@ -63,24 +75,74 @@ export async function installGitHook(root: string, event: string): Promise<boole}/**- * The git-side events cogit answers (Story 9.3). A git hook's stdin is not the- * Claude Code hook JSON, so these never go through `runHook`.+ * The git-side events cogit answers (Stories 9.3, 9.4). A git hook's stdin is+ * not the Claude Code hook JSON, so these never go through `runHook`.+ * `pre-commit` carries the session record with a code commit; `prepare-commit-msg`+ * adds the `Thought:` trailer that names the message behind it.*/-export const GIT_HOOK_EVENTS = ["pre-commit"] as const;+export const GIT_HOOK_EVENTS = ["pre-commit", "prepare-commit-msg"] as const;export type GitHookEvent = (typeof GIT_HOOK_EVENTS)[number];export function isGitHookEvent(event: string): event is GitHookEvent {return (GIT_HOOK_EVENTS as readonly string[]).includes(event);}+/** Installs the cogit block into every hook git would run; returns the events added. */+export async function installGitHooks(root: string): Promise<GitHookEvent[]> {+ const installed: GitHookEvent[] = [];+ for (const event of GIT_HOOK_EVENTS) {+ if (await installGitHook(root, event)) installed.push(event);+ }+ return installed;+}++/**+ * Removes only cogit's block from the hooks it installed (Story 9.4): the user's+ * own lines stay, and a file that held nothing but the shebang cogit wrote is+ * deleted. Returns the events that changed.+ */+export async function uninstallGitHooks(root: string): Promise<GitHookEvent[]> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return [];+ const dir = await gitHooksDir(gitRoot);+ if (dir === undefined) return [];+ const removed: GitHookEvent[] = [];+ for (const event of GIT_HOOK_EVENTS) {+ const file = join(dir, event);+ const current = await readFile(file, "utf8").catch(() => undefined);+ if (current === undefined || !current.includes(BLOCK_START)) continue;+ const next = withoutHookBlock(current);+ if (onlyGeneratedShebang(next)) await rm(file, { force: true });+ else await atomicWrite(file, next);+ removed.push(event);+ }+ return removed;+}+/*** Runs one git hook. A git hook that fails would block the user's commit, so the- * CLI calls this inside its own silence: nothing here throws or prints.+ * CLI calls this inside its own silence: nothing here throws or prints. `args`+ * are what the hook script was given (`$@`): for `prepare-commit-msg` the message+ * file and the commit source.*/export async function runGitHook(event: GitHookEvent,dir: string,env: NodeJS.ProcessEnv = process.env,+ args: readonly string[] = [],+ now: Date = new Date(),): Promise<void> {- if (event === "pre-commit") await stageSessionFiles(dir, env);+ if (event === "pre-commit") {+ await stageSessionFiles(dir, env);+ return;+ }+ const [messageFile, source] = args;+ if (messageFile === undefined || messageFile === "") return;+ await addThoughtTrailer({+ dir,+ messageFile,+ ...(source === undefined ? {} : { source }),+ env,+ now,+ });}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex e1f40de..ef20545 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -12,6 +12,7 @@ import {configSet,} from "./commands/config.js";import { epochAdd } from "./commands/epoch.js";+import { hooksUninstall } from "./commands/hooks.js";import { type InitOptions, init } from "./commands/init.js";import { formatShow, log, logFile, show } from "./commands/log.js";import { migrateIds } from "./commands/migrate.js";@@ -161,8 +162,8 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =program.command("show")- .description("print one recorded message by hash or <session-id>:mN")- .argument("<ref>", "message hash or <session-id-prefix>:mN")+ .description("print one recorded message by hash, <session-id>:mN or commit hash")+ .argument("<ref>", "message hash, <session-id-prefix>:mN, or a commit hash").argument("[dir]", "project directory", ".").option("-C, --dir <dir>", "project directory (same as the positional)").option("--no-chat", "leave out the conversation turn")@@ -372,17 +373,28 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =}),);+ const hooks = program+ .command("hooks")+ .description("manage the git hooks cogit adds to a project");+ hooks+ .command("uninstall")+ .description("remove only the cogit block from the git hooks it installed")+ .argument("[dir]", "project directory", ".")+ .action(run(async (dir: string) => hooksUninstall(dir, makeIo(false))));+// Called by the plugin's hooks.json with the hook input on stdin, and by the- // git hooks cogit installs (Story 9.3) with git's arguments. Never fails.+ // git hooks cogit installs (Stories 9.3, 9.4) with git's arguments. Never fails.program.command("hook", { hidden: true }).argument("<event>", "hook event, e.g. stop, sessionstart, pre-commit")+ .argument("[args...]", "arguments git passed to its hook: $1, $2, …").option("-C, --dir <dir>", "project directory (git hooks pass theirs)")- .action(async (event: string, opts: { dir?: string }) => {+ .allowExcessArguments(true)+ .action(async (event: string, args: string[], opts: { dir?: string }) => {const io = makeIo(false);if (isGitHookEvent(event)) {try {- await runGitHook(event, opts.dir ?? process.cwd(), io.env);+ await runGitHook(event, opts.dir ?? process.cwd(), io.env, args, new Date(io.now()));} catch {// A hook must never block the commit or the session.}diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsindex 0776dae..96b3e11 100644--- a/packages/cli/src/schema/config.ts+++ b/packages/cli/src/schema/config.ts@@ -35,6 +35,11 @@ export const Config = z.object({* user at the next session start, commit them at session end, or do nothing.*/recordCommit: z.enum(["ask", "auto", "off"]).default("ask"),+ /**+ * How long `.cogit/HEAD` stays fresh for the `Thought:` trailer (Story 9.4).+ * A commit made hours after the last message is probably not that message.+ */+ trailerMaxAgeHours: z.int().min(1).max(8760).default(6),agents: z.array(z.string().min(1)).default(["claude-code"]),/** Project roots ("don't ask again" in this project) where the setup hint stays silent. */setupHintOff: z.array(z.string().min(1)).default([]),diff --git a/packages/cli/src/store/migrate.ts b/packages/cli/src/store/migrate.tsindex 5323b24..f667b19 100644--- a/packages/cli/src/store/migrate.ts+++ b/packages/cli/src/store/migrate.ts@@ -1,6 +1,7 @@import { existsSync } from "node:fs";import { readFile, rename, stat } from "node:fs/promises";import { join, resolve, sep } from "node:path";+import { cogitIgnored } from "../git.js";import { atomicWrite, atomicWriteJson } from "./fs.js";import {CONFIG_DIR_NAME,@@ -88,6 +89,13 @@ export async function migrateProject(root: string): Promise<boolean> {const next = renameGitignoreLines(text);if (next !== text) await atomicWrite(gitignore, next).catch(() => undefined);}+ // A project that commits its record gets the git hooks the rename arrived with+ // (Story 9.4: the `Thought:` trailer). Dynamic import keeps this module — which+ // every command loads — free of the hook stack; a failure is silence.+ if (!(await cogitIgnored(dir))) {+ const { installGitHooks } = await import("../git-hooks.js");+ await installGitHooks(dir).catch(() => undefined);+ }return true;}diff --git a/packages/cli/src/thought.ts b/packages/cli/src/thought.tsnew file mode 100644index 0000000..12a5484--- /dev/null+++ b/packages/cli/src/thought.ts@@ -0,0 +1,220 @@+import { execFile } from "node:child_process";+import { access } from "node:fs/promises";+import { isAbsolute, resolve } from "node:path";+import { promisify } from "node:util";+import { cogitIgnored, findGitRoot } from "./git.js";+import { messageHash } from "./messages.js";+import type { Session } from "./schema/session.js";+import { readSessionHead } from "./session-git.js";+import { captureDisabled } from "./store/paths.js";+import { loadConfig } from "./store/stores.js";+import { findTranscript, readConversation } from "./transcript.js";++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.+ */++/** The trailer key git and cogit share. */+export const THOUGHT_TRAILER = "Thought";++/** A message id (`h` plus 12 hex, `messages.ts`). */+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}$/;++export interface TrailerOptions {+ /** The project root (where `.cogit/` lives). */+ dir: string;+ /** Git's `$1`: the file holding the proposed commit message. */+ messageFile: string;+ /** Git's `$2`: `message`, `template`, `merge`, `squash` or `commit`. */+ source?: string;+ env?: NodeJS.ProcessEnv;+ /** The clock used for the freshness check; defaults to now. */+ now?: Date;+}++/** True when the transcript file can be read. */+async function readable(path: string): Promise<boolean> {+ return access(path).then(+ () => true,+ () => false,+ );+}++/** Git resolves the message file from the working-tree root, which is its cwd. */+function messagePath(file: string): string {+ return isAbsolute(file) ? file : resolve(process.cwd(), file);+}++/**+ * Adds the `Thought:` trailer to the prepared commit message (Story 9.4). Skip+ * merges and squashes, a missing or stale `.cogit/HEAD`, an unreadable transcript+ * and a project whose records are kept out of git. `--if-exists doNothing` keeps+ * a trailer an `--amend` already carried. 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 root = resolve(opts.dir);+ // A record that stays local cannot explain a commit to anyone else.+ if (await cogitIgnored(root)) return false;++ const head = await readSessionHead(root);+ if (head === undefined || head.at === undefined) return false;+ const written = Date.parse(head.at);+ if (!Number.isFinite(written)) return false;+ const config = await loadConfig(env);+ const age = (opts.now ?? new Date()).getTime() - written;+ // 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 transcript =+ head.transcriptPath !== undefined && (await readable(head.transcriptPath))+ ? head.transcriptPath+ : await findTranscript(head.sessionId, env);+ if (transcript === null) return false;++ const turns = await 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,+ ]);+ return true;+}++/**+ * Parses `%H%x00%(trailers:key=Thought,valueonly)` lines into commit → message.+ * A commit with several Thought values keeps the first valid one.+ */+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");+ if (separator === -1) continue;+ const commit = line.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;+ }+ }+ }+ return out;+}++export interface ReadTrailerOptions {+ env?: NodeJS.ProcessEnv;+ /** Skip commits older than this ISO date; a session cannot explain them. */+ since?: string | undefined;+}++/**+ * The `Thought:` trailers 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>> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return new Map();+ const args = [+ "-C",+ gitRoot,+ "log",+ "--format=%H%x00%(trailers:key=Thought,valueonly)",+ ...(opts.since === undefined ? [] : [`--since=${opts.since}`]),+ ];+ try {+ const { stdout } = await exec(+ "git",+ args,+ opts.env === undefined ? undefined : { env: opts.env },+ );+ return parseThoughtTrailers(String(stdout));+ } catch {+ return new Map();+ }+}++/** The earliest session start, so the trailer read stops at the record's horizon. */+export function earliestSessionStart(sessions: readonly Session[]): string | undefined {+ let earliest: string | undefined;+ for (const session of sessions) {+ if (earliest === undefined || session.startedAt < earliest) earliest = session.startedAt;+ }+ return earliest;+}++/** Both directions, since a record may hold seven characters and git forty. */+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;+ }+ return undefined;+}++/**+ * 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+ * summarized has nowhere to land and is left for a later build.+ */+export function attachThoughtTrailers(+ sessions: readonly Session[],+ trailers: ReadonlyMap<string, 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);+ }++ return sessions.map((session) => {+ let changed = false;+ const nodes = session.nodes.map((node) => {+ 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 claimed = (byThought.get(node.id) ?? []).filter(+ (commit) => !kept.some((hash) => sameCommit(hash, commit)),+ );+ if (kept.length === current.length && claimed.length === 0) return node;+ changed = true;+ return { ...node, commits: [...kept, ...claimed] };+ });+ return changed ? { ...session, nodes } : session;+ });+}diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.tsnew file mode 100644index 0000000..bff9c5e--- /dev/null+++ b/packages/cli/test/thought.test.ts@@ -0,0 +1,503 @@+import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";+import { dirname, join, relative } from "node:path";+import { promisify } from "node:util";+import { beforeEach, describe, expect, it } from "vitest";+import { blame } from "../src/commands/blame.js";+import { buildProject } from "../src/commands/build.js";+import { configSet } from "../src/commands/config.js";+import { hooksUninstall } from "../src/commands/hooks.js";+import { init } from "../src/commands/init.js";+import {+ type EffectiveSession,+ loadEffectiveSessions,+ resolveRef,+ show,+} from "../src/commands/log.js";+import { ensureGitignore } from "../src/git.js";+import {+ hookBlock,+ installGitHooks,+ runGitHook,+ uninstallGitHooks,+ withHookBlock,+ withoutHookBlock,+} from "../src/git-hooks.js";+import { messageHash } from "../src/messages.js";+import { createProgram } from "../src/program.js";+import type { Session } from "../src/schema/session.js";+import { projectPaths } from "../src/store/paths.js";+import { projectJson } from "../src/store/stores.js";+import {+ addThoughtTrailer,+ attachThoughtTrailers,+ earliestSessionStart,+ parseThoughtTrailers,+ readThoughtTrailers,+} from "../src/thought.js";+import { buildMessages } from "../src/view/lineage.js";+import { DATA_ELEMENT_ID } from "../src/view/model.js";+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";++const run = promisify(execFile);++const NOW = new Date(T0);+const NEWEST_AT = "2026-10-21T10:05:00.000Z";++const TEMPLATE = `<!doctype html><html><body><div id="root"></div>+ <script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;+const DATA_PREFIX = `<script id="${DATA_ELEMENT_ID}" type="application/json">`;++function embedded(html: string): {+ unassigned: { messages: { commits?: string[] }[] }[];+} {+ const start = html.indexOf(DATA_PREFIX);+ const end = html.indexOf("</script>", start);+ return JSON.parse(html.slice(start + DATA_PREFIX.length, end));+}++function session(nodes: Session["nodes"], id = "s1"): Session {+ return {+ schema: 1,+ sessionId: id,+ agent: "claude-code",+ title: "Ship it",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes,+ };+}++describe("the thought behind a commit (Story 9.4)", () => {+ let dir: string;+ let root: string;+ let env: NodeJS.ProcessEnv;+ let io: FakeIo;+ let transcript: string;++ const git = async (...args: string[]): Promise<string> =>+ (+ await run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir },+ })+ ).stdout;++ const writeProject = async (nodes: Session["nodes"]): Promise<void> => {+ const paths = projectPaths(root);+ await mkdir(paths.sessions, { recursive: true });+ await writeFile(paths.project, projectJson({ schema: 1, name: "proj", epochs: [] }));+ await writeFile(paths.session("s1"), JSON.stringify(session(nodes)));+ };++ const writeTranscript = async (id = "s1", text = "second"): Promise<string> => {+ const file = join(dir, "claude", "projects", "proj", `${id}.jsonl`);+ await mkdir(dirname(file), { recursive: true });+ await writeFile(+ file,+ [+ { type: "user", uuid: "u1", timestamp: T0, message: { content: "first" } },+ { type: "user", uuid: "u2", timestamp: NEWEST_AT, message: { content: text } },+ ]+ .map((line) => JSON.stringify(line))+ .join("\n") + "\n",+ );+ return file;+ };++ const thoughtOf = (text = "second", id = "s1"): string =>+ messageHash(id, { uuid: "u2", at: NEWEST_AT, text });++ const writeHead = async (at = T0, path: string | undefined = transcript): Promise<void> => {+ await writeFile(+ projectPaths(root).head,+ JSON.stringify({+ sessionId: "s1",+ ...(path === undefined ? {} : { transcriptPath: path }),+ at,+ }),+ );+ };++ /** A message file git would hand `prepare-commit-msg`; returns its path. */+ const messageFile = async (body = "feat: change the code\n"): Promise<string> => {+ const file = join(dir, "COMMIT_EDITMSG");+ await writeFile(file, body);+ return file;+ };++ const readMessage = (file: string): Promise<string> => readFile(file, "utf8");++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ await mkdir(projectPaths(root).base, { recursive: true });+ env = envFor(dir);+ io = fakeIo(env);+ transcript = await writeTranscript();+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await writeFile(join(root, "a.txt"), "one\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "feat: base");+ });++ describe("addThoughtTrailer", () => {+ it("writes the newest message's id as the Thought trailer, once", async () => {+ await writeHead();+ const file = await messageFile();+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(true);+ expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);++ // Running the hook twice (a hook re-run, an amend) never duplicates it.+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW });+ const text = await readMessage(file);+ expect(text.match(/^Thought:/gm)).toHaveLength(1);+ });++ it("resolves a message file relative to git's working directory", async () => {+ await writeHead();+ const file = await messageFile();+ const rel = relative(process.cwd(), file);+ expect(+ await addThoughtTrailer({ dir: root, messageFile: rel, source: "message", env, now: NOW }),+ ).toBe(true);+ expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);+ });++ it("keeps a trailer the amended message already carried", async () => {+ await writeHead();+ const file = await messageFile(`feat: change\n\nThought: h999999999999\n`);+ await addThoughtTrailer({ dir: root, messageFile: file, source: "commit", env, now: NOW });+ const text = await readMessage(file);+ expect(text).toContain("Thought: h999999999999");+ expect(text).not.toContain(thoughtOf());+ });++ it("skips merges, squashes and an empty message-file argument", async () => {+ await writeHead();+ for (const source of ["merge", "squash"]) {+ const file = await messageFile();+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source, env, now: NOW }),+ ).toBe(false);+ expect(await readMessage(file)).toBe("feat: change the code\n");+ }+ await expect(runGitHook("prepare-commit-msg", root, env, [], NOW)).resolves.toBeUndefined();+ });++ it("skips a stale HEAD and honours trailerMaxAgeHours", async () => {+ await writeHead();+ const stale = new Date(NOW.getTime() + 7 * 3_600_000);+ const file = await messageFile();+ expect(+ await addThoughtTrailer({+ dir: root,+ messageFile: file,+ source: "message",+ env,+ now: stale,+ }),+ ).toBe(false);++ await configSet("trailerMaxAgeHours", "12", io);+ expect(+ await addThoughtTrailer({+ dir: root,+ messageFile: file,+ source: "message",+ env,+ now: stale,+ }),+ ).toBe(true);+ expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);+ });++ it("skips a HEAD without a time, in the future, or with no readable transcript", async () => {+ const file = await messageFile();+ await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1" }));+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(false);++ await writeHead("not a date");+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(false);++ // Far enough ahead that a little clock skew no longer explains it.+ await writeHead(new Date(NOW.getTime() + 3_600_000).toISOString());+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(false);++ // Another session with no transcript anywhere: there is no message to name.+ await writeFile(+ projectPaths(root).head,+ JSON.stringify({ sessionId: "s2", transcriptPath: join(dir, "missing.jsonl"), at: T0 }),+ );+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(false);+ expect(await readMessage(file)).toBe("feat: change the code\n");+ });++ it("finds the transcript through CLAUDE_CONFIG_DIR when HEAD has no path", async () => {+ await writeHead(T0, undefined);+ const file = await messageFile();+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(true);+ expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);+ });++ it("skips an empty transcript and a project that keeps its record out of git", async () => {+ await writeHead();+ await writeFile(transcript, "");+ const file = await messageFile();+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(false);++ await writeTranscript();+ await ensureGitignore(root, "ignore");+ expect(+ await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),+ ).toBe(false);++ expect(+ await addThoughtTrailer({+ dir: root,+ messageFile: file,+ source: "message",+ env: { ...env, COGIT_DISABLE: "1" },+ now: NOW,+ }),+ ).toBe(false);+ });++ it("runs through the CLI's prepare-commit-msg hook", async () => {+ await writeHead();+ const file = await messageFile();+ const program = createProgram(() => io);+ program.exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });+ await program.parseAsync(["hook", "prepare-commit-msg", "--dir", root, file, "message"], {+ from: "user",+ });+ expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);+ });+ });++ describe("reading trailers", () => {+ it("parses one commit line per commit, keeping the first valid id", () => {+ const a = "a".repeat(40);+ const b = "b".repeat(40);+ const parsed = parseThoughtTrailers(+ [+ `${a}\0h111111111111, h222222222222`,+ `${b}\0not-a-thought`,+ "no separator",+ `${a}\0`,+ ].join("\n"),+ );+ expect(parsed.get(a)).toBe("h111111111111");+ expect(parsed.has(b)).toBe(false);+ });++ it("reads the trailers git holds, and only since a date", async () => {+ await writeProject([]);+ const thought = thoughtOf();+ await git(+ "commit",+ "-q",+ "--allow-empty",+ "-m",+ "feat: code",+ "--trailer",+ `Thought: ${thought}`,+ );+ const full = (await git("rev-parse", "HEAD")).trim();+ expect((await readThoughtTrailers(root, { env })).get(full)).toBe(thought);+ expect(await readThoughtTrailers(root, { env, since: "2030-01-01T00:00:00.000Z" })).toEqual(+ new Map(),+ );+ // Outside a repository, or with a git that cannot run: no links, no error.+ expect(await readThoughtTrailers(dir)).toEqual(new Map());+ expect(await readThoughtTrailers(root, { env: { PATH: "/nonexistent" } })).toEqual(new Map());+ });++ it("unions trailer commits with the record and lets the trailer win a conflict", () => {+ const conflict = "a".repeat(40);+ const attached = "b".repeat(40);+ const untrailed = "f".repeat(40);+ const sessions = [+ session([+ {+ id: "h111111111111",+ parent: null,+ kind: "message",+ title: "A",+ commits: [conflict, untrailed],+ },+ { id: "h222222222222", parent: null, kind: "message", title: "B", commits: [] },+ { id: "phase", parent: null, kind: "phase", title: "Not a message", commits: [conflict] },+ ]),+ ];+ const [next] = attachThoughtTrailers(+ sessions,+ new Map([+ [conflict, "h222222222222"],+ [attached, "h222222222222"],+ ["c".repeat(40), "h999999999999"],+ ]),+ );+ const [a, b, phase] = next?.nodes ?? [];+ // The conflict moves to B; the commit no trailer names stays where it was.+ expect(a?.commits).toEqual([untrailed]);+ expect(b?.commits).toEqual([conflict, attached]);+ // Non-message nodes are not touched, and an unknown message is ignored.+ expect(phase?.commits).toEqual([conflict]);+ expect(attachThoughtTrailers(sessions, new Map())[0]).toBe(sessions[0]);+ expect(earliestSessionStart(sessions)).toBe(T0);+ expect(earliestSessionStart([])).toBeUndefined();+ });+ });++ describe("hook installation", () => {+ const userHook = "#!/bin/sh\necho user-hook\n";++ it("installs both events, keeps the user's lines, and uninstalls only its block", async () => {+ const preCommit = join(root, ".git", "hooks", "pre-commit");+ await writeFile(preCommit, userHook);+ await chmod(preCommit, 0o755);+ expect(await installGitHooks(root)).toEqual(["pre-commit", "prepare-commit-msg"]);+ expect(await readFile(preCommit, "utf8")).toBe(+ `${userHook}\n${hookBlock("pre-commit", root)}\n`,+ );+ expect(await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8")).toContain(+ "cogit hook prepare-commit-msg",+ );+ expect(await installGitHooks(root)).toEqual([]);++ expect(await uninstallGitHooks(root)).toEqual(["pre-commit", "prepare-commit-msg"]);+ expect(await readFile(preCommit, "utf8")).toBe(userHook);+ // The file held nothing but cogit's shebang and block, so it is gone.+ expect(existsSync(join(root, ".git", "hooks", "prepare-commit-msg"))).toBe(false);+ expect(await uninstallGitHooks(root)).toEqual([]);+ });++ it("follows core.hooksPath and leaves a hook without the block alone", async () => {+ await git("config", "core.hooksPath", ".husky");+ await mkdir(join(root, ".husky"), { recursive: true });+ await writeFile(join(root, ".husky", "pre-commit"), userHook);+ await installGitHooks(root);+ expect(await readFile(join(root, ".husky", "prepare-commit-msg"), "utf8")).toContain(+ "cogit hook prepare-commit-msg",+ );+ expect(await uninstallGitHooks(root)).toEqual(["pre-commit", "prepare-commit-msg"]);+ expect(await readFile(join(root, ".husky", "pre-commit"), "utf8")).toBe(userHook);++ // No repository and no block: nothing to do.+ expect(await uninstallGitHooks(dir)).toEqual([]);+ expect(await uninstallGitHooks(root)).toEqual([]);+ });++ it("keeps the repository's own Conventional Commits hook intact", () => {+ // A copy of `.git/hooks/commit-msg` in this repository (the start-project one).+ const own =+ "#!/bin/sh\n# >>> start-project: commit-msg (Conventional Commits) >>>\n" ++ '_first="$(grep -vE \'^#\' "$1" | head -1)"\n' ++ 'case "$_first" in\n ""|"Merge "*) exit 0 ;;\nesac\nexit 0\n';+ const installed = withHookBlock(own, hookBlock("prepare-commit-msg", "/p"));+ expect(installed).toContain("start-project: commit-msg");+ expect(installed).toContain("cogit hook prepare-commit-msg");+ expect(withoutHookBlock(installed)).toBe(own);+ });++ it("removes nothing from a user hook without a block", () => {+ expect(withoutHookBlock("#!/bin/sh\necho mine\n")).toBe("#!/bin/sh\necho mine\n");+ });++ it("uninstalls through the CLI", async () => {+ await writeProject([]);+ await installGitHooks(root);+ const program = createProgram(() => io);+ program.exitOverride().configureOutput({ writeOut: () => {}, writeErr: () => {} });+ await program.parseAsync(["hooks", "uninstall", root], { from: "user" });+ expect(io.lines.at(-1)).toBe("Removed the cogit block from: pre-commit, prepare-commit-msg");++ await program.parseAsync(["hooks", "uninstall", root], { from: "user" });+ expect(io.lines.at(-1)).toBe("No cogit hook blocks to remove.");++ await hooksUninstall(root, io);+ expect(io.lines.at(-1)).toBe("No cogit hook blocks to remove.");+ });+ });++ it("init installs both hooks under the commit policy", async () => {+ await init(+ root,+ { name: "proj", retention: "keep", language: "auto", git: "commit" },+ fakeIo(env),+ );+ expect(await readFile(join(root, ".git", "hooks", "pre-commit"), "utf8")).toContain(+ "cogit hook pre-commit",+ );+ expect(await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8")).toContain(+ "cogit hook prepare-commit-msg",+ );+ });++ it("attaches a trailer commit at build time, in log and in blame", async () => {+ const thought = thoughtOf();+ await writeProject([+ { id: thought, parent: null, kind: "message", title: "Ship the parser", at: T0 },+ ]);+ await writeFile(join(root, "a.txt"), "two\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "feat: parser", "--trailer", `Thought: ${thought}`);+ const full = (await git("rev-parse", "HEAD")).trim();++ await buildProject({ dir: root, io, templateHtml: TEMPLATE });+ const html = await readFile(projectPaths(root).html, "utf8");+ expect(embedded(html).unassigned[0]?.messages[0]?.commits).toContain(full);++ const effective = await loadEffectiveSessions(root, io);+ const commits = effective[0]?.messages[0]?.commits ?? [];+ expect(commits).toContain(full);++ // The read verb from code back to the why, by short hash.+ const model = await show({ dir: root, ref: full.slice(0, 7), io, chat: false });+ expect(model.title).toBe("Ship the parser");++ const hits = await blame({ dir: root, target: "a.txt", io });+ expect(hits.map((hit) => hit.messageId)).toEqual([thought]);+ });++ it("resolves a commit ref and reports one it cannot place", () => {+ const commit = "d".repeat(40);+ const nodes = buildMessages([+ { id: "h111111111111", parent: null, kind: "message", title: "One", commits: [commit] },+ { id: "h222222222222", parent: null, kind: "message", title: "Two", commits: [commit] },+ ]);+ const entry: EffectiveSession = {+ session: session([]),+ messages: nodes,+ turns: null,+ };+ expect(resolveRef([entry], "d".repeat(7))).toMatchObject({ kind: "ambiguous" });+ expect(resolveRef([entry], "e".repeat(7))).toMatchObject({+ kind: "unknown",+ reason: "no recorded thought for commit eeeeeee",+ });+ expect(+ resolveRef([{ ...entry, messages: [nodes[0] as (typeof nodes)[number]] }], "d".repeat(7)),+ ).toMatchObject({ kind: "ok" });+ });+});