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(why): show the thought behind one line
Eren54390a4681bb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e04da5f..d72192e 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+- `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.- The map tells your sessions from your teammates': a teammate's session always shows their name and yours never needs to, the side panel marks yours "(you)", and a new Everyone / You / teammate choice in the toolbar fades the other people's sessions.diff --git a/docs/guide/reading-the-lineage.md b/docs/guide/reading-the-lineage.mdindex 18f8eea..fd572b7 100644--- a/docs/guide/reading-the-lineage.md+++ b/docs/guide/reading-the-lineage.md@@ -12,6 +12,8 @@ cogit show h3f9c2a1b4d6e # one message: what came of it, its decisions, itscogit show a1b2c3d # the message behind a commit (through its Thought: trailer)cogit blame src/auth.ts:42 # which recorded message produced this linecogit why src/auth.ts # what earlier messages decided about this file, and rejected+cogit why src/auth.ts:42 # only the thought behind line 42+cogit why src/auth.ts --line 42 # the same lookupcogit search "refresh token" # titles, decisions, summaries and the stored conversation```@@ -34,6 +36,12 @@ each with its message hash and date.The lookup is exact, but the wording is the record's summary, so it is only as good as therecord.+Add a line — `cogit why src/auth.ts:42` or `--line 42` — and `why` asks git which commit last+touched that line and shows only the thought behind it: for a surprising line, that is the one+you wanted. When that commit carries no thought, `why` says so and lists the file's other+thoughts under a "Thoughts behind the rest of the file" heading. A line past the end of the file+is an error.+Like git, it works from any directory inside the project: the path is relative to where youare, so `cd src && cogit why auth.ts` is the same lookup.diff --git a/packages/cli/src/commands/blame.ts b/packages/cli/src/commands/blame.tsindex 241a2d7..1a6ada8 100644--- a/packages/cli/src/commands/blame.ts+++ b/packages/cli/src/commands/blame.ts@@ -8,6 +8,7 @@ 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";+import type { ViewNode } from "../view/model.js";/*** `cogit blame` (Story 8.8): git knows which commit wrote a line, the@@ -50,7 +51,7 @@ function sameCommit(recorded: string, blamed: string): boolean {}/** One readable line from git's failure; the first line carries the reason. */-function gitMessage(err: unknown): string {+export function gitMessage(err: unknown): string {const stderr = (err as { stderr?: unknown }).stderr;const text = typeof stderr === "string" && stderr.trim() !== "" ? stderr : String(err);return text.trim().split("\n")[0] ?? "unknown git error";@@ -60,6 +61,71 @@ function oneLine(text: string): string {return text.replace(/\s+/g, " ").trim();}+/** One recorded thought behind a commit. */+export interface CommitThought {+ /** The blamed commit, full hash. */+ commit: string;+ sessionId: string;+ sessionTitle: string;+ messageId: string;+ /** The `m12` label the map shows. */+ label: string;+ title: string;+ summary?: string;+ /** The message time (its session's start when the record has none). */+ at: string;+ /** The message itself, for the decisions `why` prints. */+ node: ViewNode;+}++/**+ * The recorded messages behind `commits` (Story 13.2): a commit's `Thought:`+ * trailer (Story 9.4) or a record's `commits` list links the two. `blame` and+ * `why <file>:<line>` share this walk, so line → commit → message exists once.+ */+export async function thoughtsForCommits(+ root: string,+ commits: readonly string[],+ env?: NodeJS.ProcessEnv,+ warn?: (line: string) => void,+): Promise<CommitThought[]> {+ const loaded = [...(await loadAllSessions(root, warn ?? (() => {})))].sort(+ (a, b) => a.startedAt.localeCompare(b.startedAt) || a.sessionId.localeCompare(b.sessionId),+ );+ const trailers = await readThoughtTrailers(root, {+ ...(env === undefined ? {} : { env }),+ since: earliestSessionStart(loaded),+ });+ const sessions = attachThoughtTrailers(loaded, trailers);+ const thoughts: CommitThought[] = [];+ const seen = new Set<string>();++ for (const commit of commits) {+ for (const session of sessions) {+ const sessionTitle = session.title.trim() === "" ? session.sessionId : session.title;+ for (const message of buildMessages(session.nodes)) {+ const recorded = (message.commits ?? []).find((hash) => sameCommit(hash, commit));+ if (recorded === undefined) continue;+ const key = `${commit}:${message.id}`;+ if (seen.has(key)) continue;+ seen.add(key);+ thoughts.push({+ commit,+ sessionId: session.sessionId,+ sessionTitle,+ messageId: message.id,+ label: message.label ?? message.id,+ title: message.title,+ ...(message.summary === undefined ? {} : { summary: message.summary }),+ at: message.at ?? session.startedAt,+ node: message,+ });+ }+ }+ }+ return thoughts;+}+/*** Prints every recorded message that lists a commit git blames for the target,* with the map URL that opens that message. A plain "no hit" line when the@@ -96,43 +162,22 @@ export async function blame(opts: BlameOptions): Promise<BlameHit[]> {throw new CliError(`git could not read ${opts.target}: ${gitMessage(err)}`);}- 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 thoughts = await thoughtsForCommits(root, commits, io.env, io.warn);const mapUrl = pathToFileURL(projectPaths(root).html).href;- const hits: BlameHit[] = [];- const seen = new Set<string>();-- for (const commit of commits) {- for (const session of sessions) {- for (const message of buildMessages(session.nodes)) {- const recorded = (message.commits ?? []).find((hash) => sameCommit(hash, commit));- if (recorded === undefined) continue;- const key = `${commit}:${message.id}`;- if (seen.has(key)) continue;- seen.add(key);- hits.push({- commit: commit.slice(0, 7),- sessionId: session.sessionId,- sessionTitle: session.title || session.sessionId,- messageId: message.id,- label: message.label ?? message.id,- title: message.title,- ...(message.summary === undefined ? {} : { summary: message.summary }),- url: `${mapUrl}#s=${encodeURIComponent(session.sessionId)}&m=${encodeURIComponent(- message.id,- )}`,- });- }- }- }+ const hits: BlameHit[] = thoughts.map((thought) => ({+ commit: thought.commit.slice(0, 7),+ sessionId: thought.sessionId,+ sessionTitle: thought.sessionTitle,+ messageId: thought.messageId,+ label: thought.label,+ title: thought.title,+ ...(thought.summary === undefined ? {} : { summary: thought.summary }),+ url: `${mapUrl}#s=${encodeURIComponent(thought.sessionId)}&m=${encodeURIComponent(+ thought.messageId,+ )}`,+ }));for (const hit of hits) {io.out(`${hit.commit} ${hit.sessionTitle} · ${hit.label} ${hit.title}`);diff --git a/packages/cli/src/commands/why.ts b/packages/cli/src/commands/why.tsindex 905174d..5a435bd 100644--- a/packages/cli/src/commands/why.ts+++ b/packages/cli/src/commands/why.ts@@ -5,10 +5,9 @@ import { blameCommitHashes, findGitRoot } from "../git.js";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";+import { loadProject } from "../store/stores.js";import type { ViewNode } from "../view/model.js";+import { type CommitThought, gitMessage, parseBlameTarget, thoughtsForCommits } from "./blame.js";import { shortHash, stamp } from "./log.js";/**@@ -18,6 +17,10 @@ import { shortHash, stamp } from "./log.js";* record's "considered and rejected" options — so the answer is exact, though* each summary is only as good as the record the agent wrote. No message text* is read or classified.+ *+ * `cogit why <file>:<line>` (Story 13.2) narrows the same chain to the commit+ * git blames for that line, so a surprising line gets only the thought that+ * produced it.*//** An option the record says was considered and not taken, with the reason. */@@ -67,11 +70,6 @@ function repositoryPath(gitRoot: string, root: string, file: string): string | ureturn rel.split(sep).join("/");}-/** A recorded short hash may name a full hash git printed, or the reverse. */-function sameCommit(recorded: string, blamed: string): boolean {- return blamed.startsWith(recorded) || recorded.startsWith(blamed);-}-/*** The decisions a message recorded: its own (a user-level choice with a `why`,* or rejected options) and the agent's decisions along the way. A message with@@ -94,8 +92,7 @@ function decisionsOf(message: ViewNode): WhyDecision[] {return decisions;}-/**- * The decisions of the thoughts behind `file`, newest first. `file` is relative+/** The decisions of the thoughts behind `file`, newest first. `file` is relative* to the project root. Any unreadable part (no repository, no history, no* record) is "nothing known": a hook may call this on every edit.*/@@ -103,6 +100,32 @@ export async function collectWhy(root: string,file: string,env?: NodeJS.ProcessEnv,+): Promise<WhyHit[]> {+ return collect(root, file, undefined, env, false);+}++/**+ * The decisions of the one thought behind line `line` of `file` (Story 13.2):+ * `git blame -L` names the commit that last touched the line, and the shared+ * `blame` walk turns that commit into its recorded message. Unlike+ * {@link collectWhy} a broken blame (a line past the end of the file) is an+ * error, not "nothing known": the user named the line.+ */+export async function collectWhyLine(+ root: string,+ file: string,+ line: number,+ env?: NodeJS.ProcessEnv,+): Promise<WhyHit[]> {+ return collect(root, file, line, env, true);+}++async function collect(+ root: string,+ file: string,+ line: number | undefined,+ env: NodeJS.ProcessEnv | undefined,+ strict: boolean,): Promise<WhyHit[]> {const gitRoot = await findGitRoot(root);if (gitRoot === undefined) return [];@@ -111,39 +134,35 @@ export async function collectWhy(let commits: string[];try {- commits = await blameCommitHashes(gitRoot, repoPath);- } catch {+ commits = await blameCommitHashes(gitRoot, repoPath, line);+ } catch (err) {+ if (strict) throw err;return [];}if (commits.length === 0) return [];- const sessions = await loadAllSessions(root, () => {});- const trailers = await readThoughtTrailers(root, {- ...(env === undefined ? {} : { env }),- since: earliestSessionStart(sessions),- });- const attached = attachThoughtTrailers(sessions, trailers);- const hits: WhyHit[] = [];+ return hitsFromThoughts(await thoughtsForCommits(root, commits, env));+}- for (const session of attached) {- const sessionTitle = session.title.trim() === "" ? session.sessionId : session.title;- for (const message of buildMessages(session.nodes)) {- const linked = (message.commits ?? []).some((hash) =>- commits.some((commit) => sameCommit(hash, commit)),- );- if (!linked) continue;- const decisions = decisionsOf(message);- if (decisions.length === 0) continue;- hits.push({- sessionId: session.sessionId,- sessionTitle,- messageId: message.id,- label: message.label ?? message.id,- at: message.at ?? session.startedAt,- title: message.title,- decisions,- });- }+/** One hit per message, newest first; the same message may name several commits. */+function hitsFromThoughts(thoughts: readonly CommitThought[]): WhyHit[] {+ const hits: WhyHit[] = [];+ const seen = new Set<string>();+ for (const thought of thoughts) {+ const decisions = decisionsOf(thought.node);+ if (decisions.length === 0) continue;+ const key = `${thought.sessionId}:${thought.messageId}`;+ if (seen.has(key)) continue;+ seen.add(key);+ hits.push({+ sessionId: thought.sessionId,+ sessionTitle: thought.sessionTitle,+ messageId: thought.messageId,+ label: thought.label,+ at: thought.at,+ title: thought.title,+ decisions,+ });}const time = (hit: WhyHit): number => {@@ -187,8 +206,10 @@ export interface WhyOptions {* one above it and `file` is relative to it, as with git.*/cwd?: string;- /** A file, relative to the project (or to `cwd`) or absolute. */+ /** A file, or `file:line` (Story 13.2), relative to the project (or to `cwd`) or absolute. */file: string;+ /** The line to look up, when it is not written as `file:line`. */+ line?: number;io: Io;}@@ -206,16 +227,25 @@ export async function nearestProjectDir(start: string): Promise<string | undefin/*** Prints the decisions and rejected alternatives of the thoughts behind a file,- * each with its message hash and date.+ * each with its message hash and date. With a line (Story 13.2) only the thought+ * behind that line is printed; when its commit carries none, the file-level+ * thoughts follow under a heading.*/export async function why(opts: WhyOptions): Promise<WhyHit[]> {const { io } = opts;+ if (opts.line !== undefined && (!Number.isInteger(opts.line) || opts.line < 1))+ throw new CliError("--line needs a positive line number");+let start = opts.dir ?? ".";- let file = opts.file;+ let target = opts.file;if (opts.cwd !== undefined) {start = (await nearestProjectDir(opts.cwd)) ?? opts.cwd;- file = relative(start, resolve(opts.cwd, opts.file));+ target = relative(start, resolve(opts.cwd, opts.file));}+ const parsed = parseBlameTarget(target);+ const file = parsed.file;+ const line = opts.line ?? parsed.line;+const { root } = await resolveProjectRoot(start);const project = await loadProject(root);if (!project.found) throw new CliError(`${root} is not initialized; run \`cogit init\` first`);@@ -229,15 +259,45 @@ export async function why(opts: WhyOptions): Promise<WhyHit[]> {);if (!exists) throw new CliError(`${opts.file} does not exist`);+ if (line !== undefined) {+ let lineHits: WhyHit[];+ try {+ lineHits = await collectWhyLine(root, file, line, io.env);+ } catch (err) {+ throw new CliError(`git could not read ${opts.file}: ${gitMessage(err)}`);+ }+ if (lineHits.length > 0) {+ printHits(io, lineHits);+ return lineHits;+ }++ const fileHits = await collectWhy(root, file, io.env);+ if (fileHits.length === 0) {+ io.out(`No decisions or rejected alternatives recorded for ${file}.`);+ return fileHits;+ }+ io.out(`No thought recorded for ${file}:${line}.`);+ io.out("");+ io.out("Thoughts behind the rest of the file:");+ io.out("");+ printHits(io, fileHits);+ return fileHits;+ }+const hits = await collectWhy(root, file, io.env);if (hits.length === 0) {- io.out(`No decisions or rejected alternatives recorded for ${opts.file}.`);+ io.out(`No decisions or rejected alternatives recorded for ${file}.`);return hits;}+ printHits(io, hits);+ return hits;+}++/** The hits in today's `why` format, then the pointer to `show`. */+function printHits(io: Io, hits: readonly WhyHit[]): void {for (const line of formatWhy(hits)) io.out(line);io.out("");io.out("`cogit show <hash>` opens the thought; the record is the agent's summary.");- return hits;}/** How many rejected options one PreToolUse note carries. */diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 1d3aabf..6121f77 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -98,18 +98,27 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =program.command("why")- .description("show the decisions and rejected options behind a file")+ .description("show the decisions and rejected options behind a file or a line").helpGroup("Read:")- .argument("<file>", "file to look up, relative to where you are (or to [dir])")+ .argument("<file>", "file (or file:line) to look up, relative to where you are (or to [dir])").argument("[dir]", "project directory; by default the nearest one above you").option("-C, --dir <dir>", "project directory (same as the positional)")- .addHelpText("after", examples("cogit why src/auth.ts", "cogit why src/auth.ts ../my-app"))+ .option("--line <n>", "the line to look up (same as file:line)", positiveCount)+ .addHelpText(+ "after",+ examples(+ "cogit why src/auth.ts",+ "cogit why src/auth.ts:42",+ "cogit why src/auth.ts ../my-app",+ ),+ ).action(- run(async (file: string, dir: string | undefined, opts: { dir?: string }) => {+ run(async (file: string, dir: string | undefined, opts: { dir?: string; line?: number }) => {const project = opts.dir ?? dir;await why({...(project === undefined ? { cwd: process.cwd() } : { dir: project }),file,+ ...(opts.line === undefined ? {} : { line: opts.line }),io: makeIo(false),});}),diff --git a/packages/cli/test/why.test.ts b/packages/cli/test/why.test.tsindex acec816..7c6a729 100644--- a/packages/cli/test/why.test.ts+++ b/packages/cli/test/why.test.ts@@ -7,6 +7,7 @@ import { configSet } from "../src/commands/config.js";import { init } from "../src/commands/init.js";import {collectWhy,+ collectWhyLine,formatWhy,nearestProjectDir,rejectedItems,@@ -17,6 +18,7 @@ import {why,} from "../src/commands/why.js";import { runHook } from "../src/hooks/run.js";+import { createProgram } from "../src/program.js";import type { Session } from "../src/schema/session.js";import { projectPaths } from "../src/store/paths.js";import { envFor, fakeIo, noGitDir, noGitProject, T0, tempDir } from "./helpers.js";@@ -245,6 +247,67 @@ describe("cogit why", () => {expect(await collectWhy(root, "missing.txt", env)).toEqual([]);});+ it("narrows to the thought behind one line (13.2)", async () => {+ // Line 1 came from the first commit (thought A), line 2 from the second (B).+ expect((await collectWhyLine(root, "a.txt", 1, env)).map((entry) => entry.messageId)).toEqual([+ A,+ ]);+ expect((await collectWhyLine(root, "a.txt", 2, env)).map((entry) => entry.messageId)).toEqual([+ B,+ ]);++ const io = fakeIo(env);+ expect(await why({ dir: root, file: "a.txt:1", io })).toHaveLength(1);+ const text = io.lines.join("\n");+ expect(text).toContain("decision: Parse the file — The old loop ate one line.");+ expect(text).toContain("not: Keep the loop — It loses data.");+ expect(text).not.toContain("Extend the parser");++ // `--line` takes the same path as the `:line` suffix.+ const flag = fakeIo(env);+ expect(await why({ dir: root, file: "a.txt", line: 2, io: flag })).toHaveLength(1);+ expect(flag.lines.join("\n")).toContain("Extend the parser");+ expect(flag.lines.join("\n")).not.toContain("Parse the file");++ const cliIo = fakeIo(env);+ const program = createProgram(() => cliIo);+ await program.parseAsync(["why", "a.txt", "--line", "1", "-C", root], { from: "user" });+ expect(cliIo.lines.join("\n")).toContain("h1111111 m1");+ });++ it("falls back to the file's other thoughts when the line has none (13.2)", async () => {+ await writeFile(join(root, "a.txt"), "one\ntwo\nthree\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "chore: third line");+ expect(await collectWhyLine(root, "a.txt", 3, env)).toEqual([]);++ const io = fakeIo(env);+ await why({ dir: root, file: "a.txt:3", io });+ const text = io.lines.join("\n");+ expect(io.lines[0]).toBe("No thought recorded for a.txt:3.");+ expect(text).toContain("Thoughts behind the rest of the file:");+ expect(text).toContain("h2222222 m2");+ expect(text).toContain("h1111111 m1");+ });++ it("reports a line git cannot blame (13.2)", async () => {+ await expect(why({ dir: root, file: "a.txt:99", io: fakeIo(env) })).rejects.toThrow(+ /git could not read a\.txt:99/,+ );+ await expect(why({ dir: root, file: "a.txt", line: 0, io: fakeIo(env) })).rejects.toThrow(+ /positive line number/,+ );+ });++ it("says plainly when a file has no thought for a line or anywhere else (13.2)", async () => {+ await writeFile(join(root, "plain.txt"), "x\n");+ await git("add", "plain.txt");+ await git("commit", "-q", "-m", "chore: plain");+ const io = fakeIo(env);+ await why({ dir: root, file: "plain.txt:1", io });+ expect(io.lines).toEqual(["No decisions or rejected alternatives recorded for plain.txt."]);+ });+it("writes one note per file per session and then stays quiet", async () => {const first = await edit();expect(first).toBeDefined();