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(map): show a commit's diff in the message details
Eren2d9e79ea7d9d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c275613..1e753b7 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+- A message's details show the change itself: every commit row and every changed-file row opens git's own patch (`GET /api/diff` runs `git show --format= --patch --no-color`, registered projects only, capped at about 400 KB), unified by default with line numbers on both sides, removed lines red and added lines green, and a "Side by side" toggle remembered for that viewer. Binary files read "binary file changed", a commit git no longer has stays a plain greyed row, and a map opened as a file (`file://`) says to use `cogit open` instead of failing on every click.- `cogit why <file>` follows file → the commits that touched it → their `Thought:` messages → the decisions and rejected alternatives those thoughts recorded, newest first, each with its message hash and date. A Claude Code `PreToolUse` hook on Edit/Write/MultiEdit adds the same information to the agent's context before it writes a file: once per file per session, at most five options and about 600 characters, the rest pointing at `cogit why`; the note never blocks or changes the call, and any failure is silent (`tryBeforeNotes`, on by default, off in Settings). The lookup is exact; the wording is the record's summary.- The map shows how much code landed after a message: each row with linked commits carries a `+1 240 −80 · 14 files` chip from `git diff --numstat` (the `Thought:` trailer union with the recorded commits, a commit counted once), the details panel states the same numbers and offers a read toggle, and rows you have not marked read above `bigChangeLines` (default 300) get a quiet highlight. The map head gains an "Unread" filter listing unread messages most code first, `cogit log --unread` prints the same list, and the panel card counts a project's unread big changes. The marks live in `.cogit/state/read.json` (local, never committed or shared) and are written by the local map server; nothing reads or classifies message text.- `cogit pr [base]` turns a branch into a review-ready Markdown description from the thoughts behind its commits: the sessions' goals, each thought's title, summary, decisions and rejected options, its commits and changed files, and the commits with no recorded thought (`thought h… not recorded yet` when the record has not caught up). The base is the upstream's merge base, else `main`, else `master`, with a clear error when none resolves; `--json` prints the same content as data and `--copy` puts the Markdown on the clipboard. It reads only the record — never the conversation text or the user's prompts — and stays under GitHub's body limit by dropping file lists first, then summaries, saying what was left out. The record skill hands its output over instead of writing a PR description itself.diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex 988e07d..4361bb4 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -298,6 +298,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelchats: views.chats,pending: views.pending,commitSubjects: commits.subjects,+ commitFiles: commits.files,// Over `file://` the settings modal shows these; a server page reads the// live values instead, so a map built before a change still agrees.settings: panelSettings(config),diff --git a/packages/cli/src/diff.ts b/packages/cli/src/diff.tsnew file mode 100644index 0000000..fef752b--- /dev/null+++ b/packages/cli/src/diff.ts@@ -0,0 +1,117 @@+import { execFile } from "node:child_process";+import { relative, resolve, sep } from "node:path";+import { promisify } from "node:util";+import { findGitRoot, projectFiles } from "./git.js";++const exec = promisify(execFile);++/**+ * The biggest diff the map shows (Story 10.5). GitHub-sized reading, not a+ * memory guard: past this the page says to run `git show` instead.+ */+export const DIFF_MAX_BYTES = 400 * 1024;++/** A reader must get an answer in a moment; a huge commit must not hang the page. */+const DIFF_TIMEOUT_MS = 10_000;++/** `git show` may print more than the cap so the cap can be detected, not crash. */+const READ_MAX_BUFFER = DIFF_MAX_BYTES * 8;++/** A commit as the URL may name it: 7–40 hex characters, never an option. */+export function isDiffSha(value: string): boolean {+ return /^[0-9a-f]{7,40}$/i.test(value);+}++/** What the page says when the diff is past the cap. */+export function diffTooLarge(sha: string): string {+ return `diff too large, run \`git show ${sha}\``;+}++/**+ * Git prints a placeholder for binary files. The map has no renderer for the+ * bytes, so it says the same thing for every binary file (Story 10.5).+ */+export function normalizeDiff(text: string): { text: string; binary: boolean } {+ let binary = false;+ const normalized = text+ .split("\n")+ .map((line) => {+ if (/^Binary files .+ and .+ differ$/.test(line)) {+ binary = true;+ return "binary file changed";+ }+ return line;+ })+ .join("\n");+ return { text: normalized, binary };+}++export type CommitDiffResult =+ | { ok: true; text: string }+ | { ok: false; reason: "no-git" | "unknown-commit" | "file-not-in-commit" | "too-large" };++/** Files a commit touched, relative to the repository root. */+async function commitFiles(gitRoot: string, sha: string): Promise<string[]> {+ const { stdout } = await exec("git", ["-C", gitRoot, "show", "--format=", "--name-only", sha], {+ maxBuffer: READ_MAX_BUFFER,+ timeout: DIFF_TIMEOUT_MS,+ });+ return stdout+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line !== "");+}++/**+ * One commit's patch for the map (Story 10.5): `git show --format= --patch+ * --no-color`, optionally limited to a file the commit touched. `root` is the+ * project directory; git may sit above it. No shell: the hash is checked to be+ * hex and the file is passed after `--`.+ */+export async function readCommitDiff(+ root: string,+ input: string,+ file?: string,+): Promise<CommitDiffResult> {+ if (!isDiffSha(input)) return { ok: false, reason: "unknown-commit" };+ const sha = input.toLowerCase();+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return { ok: false, reason: "no-git" };++ try {+ // Resolve first, so an unknown hash is a 404 and never a git error page.+ await exec("git", ["-C", gitRoot, "rev-parse", "--verify", "--quiet", `${sha}^{commit}`], {+ maxBuffer: READ_MAX_BUFFER,+ timeout: DIFF_TIMEOUT_MS,+ });+ } catch {+ return { ok: false, reason: "unknown-commit" };+ }++ const files = await commitFiles(gitRoot, sha);++ let repoFile: string | undefined;+ if (file !== undefined) {+ // The page holds project-relative paths; git wants repository-relative ones.+ const wanted = file.split("\\").join("/").replace(/^\.\//, "");+ repoFile = relative(gitRoot, resolve(root, wanted)).split(sep).join("/");+ const kept = projectFiles(gitRoot, root, new Map([[sha, files]])).get(sha) ?? [];+ if (!kept.includes(wanted)) return { ok: false, reason: "file-not-in-commit" };+ }++ const args = ["-C", gitRoot, "show", "--format=", "--patch", "--no-color", sha];+ if (repoFile !== undefined) args.push("--", repoFile);+ try {+ const { stdout } = await exec("git", args, {+ maxBuffer: READ_MAX_BUFFER,+ timeout: DIFF_TIMEOUT_MS,+ });+ if (Buffer.byteLength(stdout, "utf8") > DIFF_MAX_BYTES) {+ return { ok: false, reason: "too-large" };+ }+ return { ok: true, text: normalizeDiff(stdout).text };+ } catch {+ // maxBuffer or the timeout: either way the patch is not worth sending.+ return { ok: false, reason: "too-large" };+ }+}diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex 698857e..3231d44 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -13,6 +13,7 @@ import { fileURLToPath } from "node:url";import pkg from "../package.json" with { type: "json" };import { defaultAgent } from "./agents/index.js";import { buildProject } from "./commands/build.js";+import { diffTooLarge, isDiffSha, readCommitDiff } from "./diff.js";import { defaultsPrompter, type Io } from "./io.js";import { Config } from "./schema/config.js";import { refreshShareConversations } from "./share.js";@@ -111,6 +112,13 @@ function respond(res: ServerResponse, status: number, body: string): void {res.end(body);}+/** An API answer as JSON; the diff endpoint's body is text, so it needs this. */+function respondJson(res: ServerResponse, status: number, body: unknown): void {+ if (!res.headersSent)+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });+ res.end(JSON.stringify(body));+}+/** The root of a registered project, or null when the request names another path. */async function registeredRoot(env: NodeJS.ProcessEnv, dir: string): Promise<string | null> {const requested = resolve(dir);@@ -392,6 +400,61 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>res.end(JSON.stringify({ ok: true, settings: editableSettings(panelSettings(config)) }));}+ /**+ * `GET /api/diff?dir&commit[&file]` (Story 10.5): one commit's patch for the+ * message details. Read-only, a registered project only, and the same Origin+ * and token checks as the settings read. A bad or unknown hash is a 4xx, and+ * an oversized patch comes back as a one-line notice instead of the bytes.+ */+ async function readDiff(+ req: IncomingMessage,+ res: ServerResponse,+ port: number,+ url: URL,+ ): Promise<void> {+ if (+ !readOriginAllowed(req.headers.origin, port) ||+ !tokenMatches(req.headers[CONFIG_TOKEN_HEADER])+ ) {+ respond(res, 403, "forbidden");+ return;+ }+ const dir = url.searchParams.get("dir");+ const commit = url.searchParams.get("commit");+ const file = url.searchParams.get("file") || undefined;+ if (!dir) {+ respond(res, 400, "dir is required");+ return;+ }+ if (commit === null || !isDiffSha(commit)) {+ respond(res, 400, "commit must be 7–40 hex characters");+ return;+ }+ const root = await registeredRoot(env, dir);+ if (root === null) {+ respond(res, 403, "not a registered project");+ return;+ }+ const result = await readCommitDiff(root, commit, file);+ if (!result.ok) {+ if (result.reason === "file-not-in-commit") {+ respond(res, 400, "file is not part of this commit");+ return;+ }+ if (result.reason === "unknown-commit") {+ respond(res, 404, "commit not found");+ return;+ }+ if (result.reason === "no-git") {+ respond(res, 404, "not a git repository");+ return;+ }+ respondJson(res, 200, { ok: true, text: diffTooLarge(commit) });+ return;+ }+ respondJson(res, 200, { ok: true, text: result.text });+ }+/*** `POST /api/config` { key, value }: the modal's only write. Host, Origin,* content type and token all have to match, the key must be one the modal may@@ -566,6 +629,14 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>return;}const url = new URL(req.url ?? "/", `http://${HOST}:${port}`);+ if (url.pathname === "/api/diff") {+ if (req.method !== "GET") {+ respond(res, 405, "method not allowed");+ return;+ }+ await readDiff(req, res, port, url);+ return;+ }if (url.pathname === "/api/config") {if (req.method !== "GET") {respond(res, 405, "method not allowed");diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.tsindex a6d0c37..5ca7e42 100644--- a/packages/cli/src/view/lineage.ts+++ b/packages/cli/src/view/lineage.ts@@ -25,6 +25,7 @@ export function buildMessages(nodes: LineageNode[],pending: ViewPendingMessage[] = [],commitSubjects?: ReadonlyMap<string, string>,+ commitFiles?: ReadonlyMap<string, string[]>,): ViewNode[] {const recorded = nodes.filter((node) => node.kind === "message");// One row per message in send order; unrecorded messages are part of the same@@ -109,7 +110,12 @@ export function buildMessages(? {commitTags: node.commits.map((hash) => {const subject = commitSubjects?.get(hash);- return subject === undefined ? { hash } : { hash, subject };+ const files = commitFiles?.get(hash);+ return {+ hash,+ ...(subject === undefined ? {} : { subject }),+ ...(files === undefined ? {} : { files }),+ };}),}: {}),@@ -235,6 +241,7 @@ function toViewSession(unrecorded?: number,pending?: ViewPendingMessage[],commitSubjects?: ReadonlyMap<string, string>,+ commitFiles?: ReadonlyMap<string, string[]>,): ViewSession {return {sessionId: session.sessionId,@@ -245,7 +252,7 @@ function toViewSession(startedAt: session.startedAt,updatedAt: session.updatedAt,status: session.status,- messages: buildMessages(session.nodes, pending, commitSubjects),+ messages: buildMessages(session.nodes, pending, commitSubjects, commitFiles),// Undefined means the caller did not ask (fixtures, unit tests); then the// record is shown as resumable rather than pretending the transcript is gone.transcriptAvailable: transcripts === undefined ? true : transcripts.has(session.sessionId),@@ -276,6 +283,8 @@ export interface ViewModelInput {pending?: ReadonlyMap<string, ViewPendingMessage[]> | undefined;/** Commit subjects read from git at build time (Story 8.8). */commitSubjects?: ReadonlyMap<string, string> | undefined;+ /** Project-relative files per commit, for the diff rows (Story 10.5). */+ commitFiles?: ReadonlyMap<string, string[]> | undefined;/** Settings embedded for the modal's `file://` view (Story 8.13). */settings?: PanelSettings | undefined;}@@ -329,6 +338,7 @@ export function buildViewModel(input: ViewModelInput): LineageViewModel {input.unrecorded?.get(session.sessionId),input.pending?.get(session.sessionId),input.commitSubjects,+ input.commitFiles,);const bucket = session.epoch === null ? undefined : buckets.get(session.epoch);(bucket ?? unassigned).push(view);diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex 2460aff..37cf699 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -56,6 +56,12 @@ export interface ViewCommit {hash: string;/** The commit's subject; absent when git no longer knows the commit. */subject?: string;+ /**+ * Project-relative files the commit changed (Story 10.5), so a file row can+ * ask for the diff of the commit that touched it. Absent on pages built+ * before 10.5 and for commits git no longer knows.+ */+ files?: string[];}/**diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.tsindex 391ca41..217c4d3 100644--- a/packages/cli/test/build.test.ts+++ b/packages/cli/test/build.test.ts@@ -58,6 +58,18 @@ function session(over: Partial<Session> & { sessionId: string }): Session {}describe("buildMessages", () => {+ it("carries each commit's files, so a file row can open its patch (10.5)", () => {+ const [tagged] = buildMessages(+ [node("m1", "message", "M", null, { commits: ["abc1234"] })],+ [],+ new Map([["abc1234", "feat: x"]]),+ new Map([["abc1234", ["a.ts"]]]),+ );+ expect(tagged?.commitTags).toEqual([{ hash: "abc1234", subject: "feat: x", files: ["a.ts"] }]);+ const [bare] = buildMessages([node("m1", "message", "M", null, { commits: ["abc1234"] })]);+ expect(bare?.commitTags).toEqual([{ hash: "abc1234" }]);+ });+it("carries message detail into the view and drops empty lists", () => {const [m] = buildMessages([node("m1", "message", "M", null, {@@ -659,7 +671,7 @@ describe("cogit build", () => {const first = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });expect(first.epochs[0]?.sessions[0]?.messages[0]?.commitTags).toEqual([- { hash: short, subject: "feat: first commit" },+ { hash: short, subject: "feat: first commit", files: ["a.txt"] },]);// One hash git does not know makes the batched lookup fail; the per-hash@@ -674,7 +686,7 @@ describe("cogit build", () => {);const second = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });expect(second.epochs[0]?.sessions[0]?.messages[0]?.commitTags).toEqual([- { hash: short, subject: "feat: first commit" },+ { hash: short, subject: "feat: first commit", files: ["a.txt"] },{ hash: "0000000" },]);});diff --git a/packages/cli/test/diff.test.ts b/packages/cli/test/diff.test.tsnew file mode 100644index 0000000..af0eaf6--- /dev/null+++ b/packages/cli/test/diff.test.ts@@ -0,0 +1,166 @@+import { execFile } from "node:child_process";+import { mkdir, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { promisify } from "node:util";+import { beforeEach, describe, expect, it } from "vitest";+import {+ DIFF_MAX_BYTES,+ diffTooLarge,+ isDiffSha,+ normalizeDiff,+ readCommitDiff,+} from "../src/diff.js";+import { tempDir } from "./helpers.js";++const run = promisify(execFile);++/**+ * Story 10.5: the diff the message details show comes from `git show`. The+ * endpoint's validation and the size/binary handling are pinned here; the+ * server tests cover its HTTP surface.+ */+describe("readCommitDiff", () => {+ let dir: string;+ let root: string;++ const git = async (...args: string[]): Promise<string> => {+ const { stdout } = await run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir },+ });+ return stdout;+ };++ const commit = async (message: string): Promise<string> => {+ await git("add", "-A");+ await git("commit", "-q", "-m", message);+ return (await git("rev-parse", "HEAD")).trim();+ };++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ 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 commit("feat: base");+ });++ it("answers no-git outside a repository", async () => {+ const plain = join(dir, "plain");+ await mkdir(plain);+ expect(await readCommitDiff(plain, "abcdef0")).toEqual({+ ok: false,+ reason: "no-git",+ });+ });++ it("rejects anything that is not a hex hash before git sees it", async () => {+ expect(await readCommitDiff(root, "--help")).toEqual({+ ok: false,+ reason: "unknown-commit",+ });+ expect(await readCommitDiff(root, "abc")).toEqual({ ok: false, reason: "unknown-commit" });+ expect(await readCommitDiff(root, "a".repeat(41))).toEqual({+ ok: false,+ reason: "unknown-commit",+ });+ });++ it("answers an unknown commit instead of a git error", async () => {+ expect(await readCommitDiff(root, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")).toEqual({+ ok: false,+ reason: "unknown-commit",+ });+ });++ it("returns the commit's patch, also for a short hash", async () => {+ await writeFile(join(root, "a.txt"), "two\n");+ const sha = await commit("fix: two");+ const full = await readCommitDiff(root, sha);+ expect(full.ok).toBe(true);+ if (full.ok) {+ expect(full.text).toContain("diff --git a/a.txt b/a.txt");+ expect(full.text).toContain("-one");+ expect(full.text).toContain("+two");+ }+ const short = await readCommitDiff(root, sha.slice(0, 7).toUpperCase());+ expect(short).toEqual(full);+ });++ it("limits the patch to a file the commit touched", async () => {+ await writeFile(join(root, "a.txt"), "two\n");+ await writeFile(join(root, "b.txt"), "b\n");+ const sha = await commit("feat: both");+ const only = await readCommitDiff(root, sha, "a.txt");+ expect(only.ok).toBe(true);+ if (only.ok) {+ expect(only.text).toContain("a/a.txt");+ expect(only.text).not.toContain("b/b.txt");+ }+ });++ it("rejects a file the commit did not touch", async () => {+ await writeFile(join(root, "b.txt"), "b\n");+ const sha = await commit("feat: b only");+ expect(await readCommitDiff(root, sha, "a.txt")).toEqual({+ ok: false,+ reason: "file-not-in-commit",+ });+ expect(await readCommitDiff(root, sha, "../outside.txt")).toEqual({+ ok: false,+ reason: "file-not-in-commit",+ });+ });++ it("turns git's binary marker into one readable line", async () => {+ await writeFile(join(root, "img.bin"), Buffer.from([0, 1, 2, 0, 3]));+ const sha = await commit("feat: image");+ const result = await readCommitDiff(root, sha);+ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.text).toContain("binary file changed");+ expect(result.text).not.toContain("Binary files");+ }+ });++ it("caps a patch past the size limit", async () => {+ const line = "x".repeat(100);+ await writeFile(+ join(root, "big.txt"),+ `${Array.from({ length: 5000 }, () => line).join("\n")}\n`,+ );+ const sha = await commit("feat: big");+ expect(await readCommitDiff(root, sha)).toEqual({ ok: false, reason: "too-large" });+ expect(DIFF_MAX_BYTES).toBe(400 * 1024);+ });++ it("caps a patch past the read buffer without crashing", async () => {+ await writeFile(join(root, "huge.txt"), `${"y".repeat(DIFF_MAX_BYTES * 9)}\n`);+ const sha = await commit("feat: huge");+ expect(await readCommitDiff(root, sha)).toEqual({ ok: false, reason: "too-large" });+ });+});++describe("diff helpers", () => {+ it("accepts 7–40 hex characters only", () => {+ expect(isDiffSha("abcdef0")).toBe(true);+ expect(isDiffSha("A".repeat(40))).toBe(true);+ expect(isDiffSha("abcdef")).toBe(false);+ expect(isDiffSha("a".repeat(41))).toBe(false);+ expect(isDiffSha("main")).toBe(false);+ });++ it("normalizes binary markers and reports whether one was seen", () => {+ expect(normalizeDiff("diff --git a/x b/x\nBinary files a/x and b/x differ\n")).toEqual({+ text: "diff --git a/x b/x\nbinary file changed\n",+ binary: true,+ });+ expect(normalizeDiff("plain\n")).toEqual({ text: "plain\n", binary: false });+ });++ it("names the command to run past the cap", () => {+ expect(diffTooLarge("abcdef0")).toContain("git show abcdef0");+ });+});diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex 2629817..fada7ec 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -1,3 +1,4 @@+import { execFile } from "node:child_process";import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import {type ClientRequest,@@ -9,6 +10,7 @@ import {} from "node:http";import { type AddressInfo, createServer as createNetServer } from "node:net";import { join } from "node:path";+import { promisify } from "node:util";import { afterEach, beforeEach, describe, expect, it } from "vitest";import pkg from "../package.json" with { type: "json" };import { buildProject } from "../src/commands/build.js";@@ -809,3 +811,140 @@ describe("read marks (10.3)", () => {expect(reply.status).toBe(500);});});++describe("commit diff endpoint (Story 10.5)", () => {+ const run = promisify(execFile);++ const git = async (...args: string[]): Promise<string> => {+ const { stdout } = await run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir },+ });+ return stdout;+ };++ const commit = async (message: string): Promise<string> => {+ await git("add", "-A");+ await git("commit", "-q", "-m", message);+ return (await git("rev-parse", "HEAD")).trim();+ };++ function diffRequest(+ server: MapServer,+ token: string,+ params: Record<string, string | undefined>,+ overrides: Record<string, string> = {},+ ): Promise<Reply> {+ const url = new URL(`${server.url}/api/diff`);+ for (const [key, value] of Object.entries(params)) {+ if (value !== undefined) url.searchParams.set(key, value);+ }+ return request(url.toString(), {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ ...overrides,+ });+ }++ beforeEach(async () => {+ 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 commit("feat: base");+ });++ it("serves one commit's patch and limits it to a file", async () => {+ const server = await start();+ const token = await panelToken(server);+ await writeFile(join(root, "a.txt"), "two\n");+ const sha = await commit("fix: two");++ const full = await diffRequest(server, token, { dir: root, commit: sha });+ expect(full.status).toBe(200);+ expect(full.headers["content-type"]).toContain("application/json");+ const body = JSON.parse(full.body) as { ok: boolean; text: string };+ expect(body.ok).toBe(true);+ expect(body.text).toContain("diff --git a/a.txt b/a.txt");+ expect(body.text).toContain("+two");++ const only = await diffRequest(server, token, {+ dir: root,+ commit: sha.slice(0, 7),+ file: "a.txt",+ });+ expect(only.status).toBe(200);+ expect((JSON.parse(only.body) as { text: string }).text).toContain("+two");+ });++ it("rejects a bad hash, an unknown commit and a file outside the commit", async () => {+ const server = await start();+ const token = await panelToken(server);+ await writeFile(join(root, "a.txt"), "two\n");+ const sha = await commit("fix: two");++ expect((await diffRequest(server, token, { commit: "abcdef0" })).status).toBe(400);+ expect((await diffRequest(server, token, { dir: root })).status).toBe(400);+ expect((await diffRequest(server, token, { dir: root, commit: "abc" })).status).toBe(400);+ const head = await request(+ `${server.url}/api/diff?dir=${encodeURIComponent(root)}&commit=abcdef0`,+ { origin: `http://127.0.0.1:${server.port}`, [CONFIG_TOKEN_HEADER]: token },+ "HEAD",+ );+ expect(head.status).toBe(405);+ expect(+ (+ await diffRequest(server, token, {+ dir: root,+ commit: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",+ })+ ).status,+ ).toBe(404);+ const file = await diffRequest(server, token, { dir: root, commit: sha, file: "a.txt.bak" });+ expect(file.status).toBe(400);+ expect(file.body).toContain("file is not part of this commit");+ });++ it("requires a registered project, the token and this origin", async () => {+ const server = await start();+ const token = await panelToken(server);+ expect((await diffRequest(server, token, { dir, commit: "abcdef0" })).status).toBe(403);+ expect((await diffRequest(server, "", { dir: root, commit: "abcdef0" })).status).toBe(403);+ expect(+ (+ await diffRequest(+ server,+ token,+ { dir: root, commit: "abcdef0" },+ { origin: "http://evil.example" },+ )+ ).status,+ ).toBe(403);+ });++ it("answers not-a-git-repository for a registered project without git", async () => {+ const server = await start();+ const token = await panelToken(server);+ const plain = join(dir, "plain");+ await mkdir(plain);+ await init(plain, { name: "plain", retention: "keep", language: "auto" }, fakeIo(env));+ const reply = await diffRequest(server, token, { dir: plain, commit: "abcdef0" });+ expect(reply.status).toBe(404);+ expect(reply.body).toContain("not a git repository");+ });++ it("answers a one-line notice past the size cap", async () => {+ const server = await start();+ const token = await panelToken(server);+ const line = "x".repeat(100);+ await writeFile(+ join(root, "big.txt"),+ `${Array.from({ length: 5000 }, () => line).join("\n")}\n`,+ );+ const sha = await commit("feat: big");+ const reply = await diffRequest(server, token, { dir: root, commit: sha });+ expect(reply.status).toBe(200);+ const body = JSON.parse(reply.body) as { text: string };+ expect(body.text).toContain("diff too large");+ expect(body.text).toContain(`git show ${sha}`);+ });+});diff --git a/packages/template/src/DiffView.tsx b/packages/template/src/DiffView.tsxnew file mode 100644index 0000000..ccdb527--- /dev/null+++ b/packages/template/src/DiffView.tsx@@ -0,0 +1,163 @@+import { useEffect, useState } from "react";+import { loadDiff, pageToken } from "./data.js";+import { type DiffFile, type DiffHunk, parsePatch, sideBySide } from "./diffView.js";++/** The viewer's choice of diff layout; kept locally, never sent anywhere. */+const MODE_KEY = "cogit.diffSideBySide";++function readSideBySide(): boolean {+ try {+ return window.localStorage.getItem(MODE_KEY) === "1";+ } catch {+ return false;+ }+}++function saveSideBySide(on: boolean): void {+ try {+ window.localStorage.setItem(MODE_KEY, on ? "1" : "0");+ } catch {+ // A browser that refuses storage still switches the view for this panel.+ }+}++function DiffRows({ hunk, side }: { hunk: DiffHunk; side: boolean }) {+ if (!side) {+ return (+ <>+ <div className="diff-hunk">{hunk.header}</div>+ {hunk.lines.map((line, index) => (+ <div+ // Diff lines have no identity beyond their place in the hunk.+ key={`${hunk.header}-${index}`}+ className={`diff-row diff-${line.kind}`}+ >+ <span className="diff-no">{line.oldNo ?? ""}</span>+ <span className="diff-no">{line.newNo ?? ""}</span>+ <span className="diff-mark">+ {line.kind === "add" ? "+" : line.kind === "remove" ? "−" : ""}+ </span>+ <span className="diff-text">{line.text}</span>+ </div>+ ))}+ </>+ );+ }+ return (+ <>+ <div className="diff-hunk diff-hunk-side">+ <span>{hunk.header}</span>+ </div>+ {sideBySide(hunk.lines).map((row, index) => (+ <div key={`${hunk.header}-side-${index}`} className="diff-row diff-side-row">+ {row.note !== undefined ? (+ <span className="diff-note-line">{row.note}</span>+ ) : (+ <>+ <span+ className={`diff-no diff-side-no${row.left?.kind === "remove" ? " is-old" : ""}`}+ >+ {row.left?.no ?? ""}+ </span>+ <span className={`diff-cell${row.left ? ` diff-${row.left.kind}` : " is-empty"}`}>+ {row.left?.text ?? ""}+ </span>+ <span className={`diff-no diff-side-no${row.right?.kind === "add" ? " is-new" : ""}`}>+ {row.right?.no ?? ""}+ </span>+ <span className={`diff-cell${row.right ? ` diff-${row.right.kind}` : " is-empty"}`}>+ {row.right?.text ?? ""}+ </span>+ </>+ )}+ </div>+ ))}+ </>+ );+}++function Patch({ file, side }: { file: DiffFile; side: boolean }) {+ return (+ <div className="diff-patch">+ <div className="diff-file">{file.path}</div>+ {file.meta.map((line, index) => (+ <div key={`${line}-${index}`} className="diff-meta">+ {line}+ </div>+ ))}+ {file.binary ? <p className="diff-note-line">binary file changed</p> : null}+ {file.hunks.map((hunk) => (+ <DiffRows key={hunk.header} hunk={hunk} side={side} />+ ))}+ </div>+ );+}++/**+ * One commit's (or one file's) diff, fetched when a row is opened (Story 10.5).+ * The server caps the size and replaces binary markers with one line, so this+ * only has to decide between a rendered patch and a plain notice.+ */+export function DiffView({+ dir,+ commit,+ file,+}: {+ dir: string;+ commit: string;+ file?: string | undefined;+}) {+ const [text, setText] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [side, setSide] = useState(readSideBySide);++ useEffect(() => {+ let mounted = true;+ setText(null);+ setError(null);+ const token = pageToken();+ if (token === null) {+ setError("Diffs need the local server: open the map with `cogit open`.");+ return () => {+ mounted = false;+ };+ }+ loadDiff(dir, commit, file, token).then(+ (diff) => {+ if (mounted) setText(diff);+ },+ (err: unknown) => {+ if (mounted) setError(err instanceof Error ? err.message : String(err));+ },+ );+ return () => {+ mounted = false;+ };+ }, [dir, commit, file]);++ function changeMode(next: boolean): void {+ setSide(next);+ saveSideBySide(next);+ }++ if (error !== null) return <p className="error diff-loading">{error}</p>;+ if (text === null) return <p className="muted diff-loading">Loading diff…</p>;++ const files = parsePatch(text);+ if (files.length === 0)+ return <p className="diff-loading">{text === "" ? "No changes in this commit." : text}</p>;++ return (+ <div className="diff-view">+ <div className="diff-toolbar">+ <label>+ <input type="checkbox" checked={side} onChange={(e) => changeMode(e.target.checked)} />{" "}+ Side by side+ </label>+ </div>+ {files.map((file) => (+ <Patch key={file.path} file={file} side={side} />+ ))}+ </div>+ );+}diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex c0e09dd..f60d780 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -8,7 +8,8 @@ import type {} from "../../cli/src/view/model.js";import { resumeCommand } from "../../cli/src/view/resume.js";import { parseSubject, splitPath, typeColour } from "./codeRefs.js";-import { isLivePage } from "./data.js";+import { DiffView } from "./DiffView.js";+import { isLivePage, pageToken } from "./data.js";import { formatTime, kindLabel } from "./format.js";import { layoutGitGraph } from "./gitLayout.js";import {@@ -411,6 +412,9 @@ function NodeDetails({readError: string | null;}) {const session = findSession(model, node.sessionId);+ // Diffs are read from the local server (Story 10.5); a `file://` map has no+ // git endpoint, and the rows say so once instead of failing on every click.+ const live = typeof document !== "undefined" && isLivePage() && pageToken() !== null;return (<><MessageNav session={session} node={node} onNavigate={onNavigate} />@@ -516,7 +520,14 @@ function NodeDetails({const tag = node.commitTags?.find((candidate) => candidate.hash === commit);const missing = node.commitTags !== undefined && tag?.subject === undefined;return (- <CommitItem key={commit} hash={commit} subject={tag?.subject} missing={missing} />+ <CommitItem+ key={commit}+ hash={commit}+ subject={tag?.subject}+ missing={missing}+ root={model.project.path}+ expandable={live && !missing}+ />);})}</ul>@@ -529,17 +540,27 @@ function NodeDetails({</h3><ul className="file-list">{node.files.map((file) => {- const { dir, name } = splitPath(file);+ // The newest commit that touched the file; a file only the record+ // lists has no patch to open.+ const owner = [...(node.commitTags ?? [])]+ .reverse()+ .find((tag) => tag.files?.includes(file));return (- <li key={file} title={file}>- <span className="file-name">{name}</span>- {dir ? <span className="file-dir">{dir}</span> : null}- </li>+ <FileItem+ key={file}+ file={file}+ root={model.project.path}+ commit={owner?.hash}+ expandable={live && owner !== undefined}+ />);})}</ul></section>) : null}+ {!live && (node.commits?.length || node.files?.length) ? (+ <p className="muted">Open with `cogit open` to see diffs.</p>+ ) : null}{node.kind === "message" ? <Conversation session={session} id={node.nodeId} /> : null}<dl className="drilldown-meta">{node.decidedBy ? <Field label="Decided by">{DECIDED_LABEL[node.decidedBy]}</Field> : null}@@ -574,21 +595,27 @@ function NodeDetails({/*** One commit of a message: the short hash, the Conventional Commits type as a* coloured badge, the scope and the description. A commit git no longer has- * stays listed, greyed (Story 8.8).+ * stays listed, greyed (Story 8.8). On a live page the row opens the patch the+ * commit carries (Story 10.5).*/function CommitItem({hash,subject,missing,+ root,+ expandable,}: {hash: string;subject: string | undefined;missing: boolean;+ root: string;+ expandable: boolean;}) {+ const [open, setOpen] = useState(false);const parsed = subject === undefined ? undefined : parseSubject(subject);const lane = parsed?.type === undefined ? undefined : typeColour(parsed.type);- return (- <li className={missing ? "commit-item is-missing" : "commit-item"} title={hash}>+ const content = (+ <><code className="commit-hash">{hash.slice(0, 7)}</code>{parsed?.type ? (<span@@ -601,6 +628,67 @@ function CommitItem({) : null}{parsed?.scope ? <span className="commit-scope">{parsed.scope}</span> : null}<span className="commit-subject">{parsed ? parsed.text : "not in this repository"}</span>+ {expandable ? <span className="diff-caret">{open ? "−" : "+"}</span> : null}+ </>+ );+ return (+ <li className={missing ? "commit-item is-missing" : "commit-item"} title={hash}>+ {expandable ? (+ <button+ type="button"+ className="commit-row"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ >+ {content}+ </button>+ ) : (+ <div className="commit-row">{content}</div>+ )}+ {open ? <DiffView dir={root} commit={hash} /> : null}+ </li>+ );+}++/**+ * One file of a message's changes (Story 10.5). It opens the patch of the+ * commit that touched it; a file only the record lists stays a plain row.+ */+function FileItem({+ file,+ root,+ commit,+ expandable,+}: {+ file: string;+ root: string;+ commit: string | undefined;+ expandable: boolean;+}) {+ const [open, setOpen] = useState(false);+ const { dir, name } = splitPath(file);+ const content = (+ <>+ <span className="file-name">{name}</span>+ {dir ? <span className="file-dir">{dir}</span> : null}+ {expandable ? <span className="diff-caret">{open ? "−" : "+"}</span> : null}+ </>+ );+ return (+ <li title={file}>+ {expandable && commit !== undefined ? (+ <button+ type="button"+ className="file-row"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ >+ {content}+ </button>+ ) : (+ <div className="file-row">{content}</div>+ )}+ {open && commit !== undefined ? <DiffView dir={root} commit={commit} file={file} /> : null}</li>);}diff --git a/packages/template/src/data.ts b/packages/template/src/data.tsindex cf4242d..81f2c24 100644--- a/packages/template/src/data.ts+++ b/packages/template/src/data.ts@@ -98,6 +98,30 @@ export async function saveRead(}}+/**+ * One commit's patch for the message details (Story 10.5). Only the local+ * server answers this; over `file://` the diff rows do not expand.+ */+export async function loadDiff(+ dir: string,+ commit: string,+ file: string | undefined,+ token: string,+): Promise<string> {+ const params = new URLSearchParams({ dir, commit });+ if (file !== undefined) params.set("file", file);+ const response = await fetch(`/api/diff?${params.toString()}`, {+ headers: { "x-cogit-token": token },+ cache: "no-store",+ });+ if (!response.ok) {+ const text = (await response.text()).trim();+ throw new Error(text || `could not read the diff (HTTP ${response.status})`);+ }+ const body = (await response.json().catch(() => null)) as { text?: unknown } | null;+ return typeof body?.text === "string" ? body.text : "";+}+/** One settings write; the server validates the key, the value and the token. */export async function saveSetting(key: string,diff --git a/packages/template/src/diffView.ts b/packages/template/src/diffView.tsnew file mode 100644index 0000000..101bf5f--- /dev/null+++ b/packages/template/src/diffView.ts@@ -0,0 +1,171 @@+/**+ * Reading `git show`'s patch for the map's message details (Story 10.5). Pure:+ * the raw patch comes from the local server, and the same parse feeds both the+ * unified view and the side-by-side pairing.+ */++export type DiffLineKind = "context" | "add" | "remove" | "note";++export interface DiffLine {+ kind: DiffLineKind;+ /** The line without git's prefix (`+`, `-`, ` `). */+ text: string;+ /** Line number on the old side; null for an added line. */+ oldNo: number | null;+ /** Line number on the new side; null for a removed line. */+ newNo: number | null;+}++export interface DiffHunk {+ /** The `@@ -a,b +c,d @@` line, shown as git printed it. */+ header: string;+ lines: DiffLine[];+}++export interface DiffFile {+ /** Repository- or project-relative path, whichever the build holds. */+ path: string;+ /** `index …`, mode lines and the binary notice, shown above the hunks. */+ meta: string[];+ hunks: DiffHunk[];+ binary: boolean;+}++/** A `diff --git` line starts one file; `@@` starts one hunk. */+export function parsePatch(text: string): DiffFile[] {+ const files: DiffFile[] = [];+ let file: DiffFile | null = null;+ let hunk: DiffHunk | null = null;+ let oldNo = 0;+ let newNo = 0;++ for (const raw of text.split(/\r?\n/)) {+ if (raw.startsWith("diff --git ")) {+ const match = /^diff --git a\/(.+) b\/(.+)$/.exec(raw);+ file = {+ path: match?.[2] ?? raw.slice("diff --git ".length),+ meta: [],+ hunks: [],+ binary: false,+ };+ files.push(file);+ hunk = null;+ continue;+ }+ if (file === null) continue;++ if (raw.startsWith("Binary files ") && raw.endsWith(" differ")) {+ file.binary = true;+ continue;+ }++ if (raw.startsWith("@@")) {+ const match = /^@@+ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);+ oldNo = Number(match?.[1] ?? 0);+ newNo = Number(match?.[2] ?? 0);+ hunk = { header: raw, lines: [] };+ file.hunks.push(hunk);+ continue;+ }++ if (hunk !== null) {+ if (raw === "") continue;+ if (raw.startsWith("\\")) {+ hunk.lines.push({ kind: "note", text: raw, oldNo: null, newNo: null });+ continue;+ }+ const mark = raw[0];+ if (mark === "+") {+ hunk.lines.push({ kind: "add", text: raw.slice(1), oldNo: null, newNo });+ newNo += 1;+ continue;+ }+ if (mark === "-") {+ hunk.lines.push({ kind: "remove", text: raw.slice(1), oldNo, newNo: null });+ oldNo += 1;+ continue;+ }+ if (mark === " ") {+ hunk.lines.push({ kind: "context", text: raw.slice(1), oldNo, newNo });+ oldNo += 1;+ newNo += 1;+ continue;+ }+ hunk.lines.push({ kind: "note", text: raw, oldNo: null, newNo: null });+ continue;+ }++ if (raw.startsWith("+++ ")) {+ const path = raw.slice(4);+ if (path !== "/dev/null") file.path = path.replace(/^b\//, "");+ continue;+ }+ if (raw !== "") file.meta.push(raw);+ }++ return files;+}++export interface SideCell {+ kind: "context" | "add" | "remove";+ no: number | null;+ text: string;+}++/** One row of the side-by-side view; either side may be empty. */+export interface SideRow {+ left: SideCell | null;+ right: SideCell | null;+ /** A line with no side (`\ No newline at end of file`). */+ note?: string;+}++function cell(line: DiffLine, kind: SideCell["kind"], no: number | null): SideCell {+ return { kind, no, text: line.text };+}++/**+ * Pairs a hunk's lines into two columns. Context lines sit on both sides; a+ * block of removals and the additions that replace it pair by position, so a+ * three-line removal against a one-line addition leaves two empty right cells.+ */+export function sideBySide(lines: DiffLine[]): SideRow[] {+ const rows: SideRow[] = [];+ let index = 0;+ while (index < lines.length) {+ const line = lines[index] as DiffLine;+ if (line.kind === "note") {+ rows.push({ left: null, right: null, note: line.text });+ index += 1;+ continue;+ }+ if (line.kind === "context") {+ rows.push({+ left: cell(line, "context", line.oldNo),+ right: cell(line, "context", line.newNo),+ });+ index += 1;+ continue;+ }+ const removed: DiffLine[] = [];+ const added: DiffLine[] = [];+ while (index < lines.length && (lines[index] as DiffLine).kind === "remove") {+ removed.push(lines[index] as DiffLine);+ index += 1;+ }+ while (index < lines.length && (lines[index] as DiffLine).kind === "add") {+ added.push(lines[index] as DiffLine);+ index += 1;+ }+ const count = Math.max(removed.length, added.length);+ for (let i = 0; i < count; i += 1) {+ const left = removed[i];+ const right = added[i];+ rows.push({+ left: left === undefined ? null : cell(left, "remove", left.oldNo),+ right: right === undefined ? null : cell(right, "add", right.newNo),+ });+ }+ }+ return rows;+}diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex b0742f1..1e18c69 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -31,6 +31,11 @@--missing: #a2abbf;--search-hit-bg: #2b2724;--search-active-bg: #373129;+ /* Diff lines in the message details (Story 10.5). */+ --diff-add-bg: #16301c;+ --diff-add-text: #b7f0c0;+ --diff-remove-bg: #3a1d23;+ --diff-remove-text: #ffc4cc;--on-lane: #0f1115;--translucent-panel: rgba(20, 23, 30, 0.97);--translucent-outline: rgba(17, 20, 26, 0.94);@@ -72,6 +77,10 @@--missing: #4f586b;--search-hit-bg: #e7e2dc;--search-active-bg: #e1d9cd;+ --diff-add-bg: #e2f5e4;+ --diff-add-text: #145c22;+ --diff-remove-bg: #fbe4e6;+ --diff-remove-text: #8a1c26;--on-lane: #ffffff;--translucent-panel: rgba(255, 255, 255, 0.97);--translucent-outline: rgba(246, 248, 251, 0.96);@@ -1198,15 +1207,33 @@ h3 .count {overflow: hidden;}-.commit-item {+.commit-item,+.file-list li {+ background: var(--row-bg);+}++.commit-row {display: flex;flex-wrap: wrap;align-items: baseline;gap: 6px;+ width: 100%;padding: 7px 10px;+ color: inherit;+ font: inherit;font-size: 13px;line-height: 18px;- background: var(--row-bg);+ text-align: left;+ background: none;+ border: 0;+}++button.commit-row {+ cursor: pointer;+}++button.commit-row:hover {+ background: var(--hover);}.commit-item + .commit-item,@@ -1267,15 +1294,27 @@ h3 .count {font-style: italic;}-.file-list li {+.file-row {display: flex;align-items: baseline;gap: 8px;min-width: 0;+ width: 100%;padding: 5px 10px;+ color: inherit;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;font-size: 12px;- background: var(--row-bg);+ text-align: left;+ background: none;+ border: 0;+}++button.file-row {+ cursor: pointer;+}++button.file-row:hover {+ background: var(--hover);}.file-name {@@ -1292,6 +1331,153 @@ h3 .count {white-space: nowrap;}+/* A commit or file row that opens its patch (Story 10.5). */+.diff-caret {+ flex: none;+ margin-left: auto;+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 13px;+}++.diff-view {+ padding: 8px 10px 10px;+ overflow-x: hidden;+ background: var(--raised-2);+ border-top: 1px solid var(--line);+}++.diff-toolbar {+ display: flex;+ justify-content: flex-end;+ margin-bottom: 6px;+ color: var(--muted);+ font-size: 11px;+}++.diff-loading {+ margin: 6px 0;+ padding: 6px 10px;+ font-size: 12px;+}++.diff-patch + .diff-patch {+ margin-top: 8px;+ padding-top: 8px;+ border-top: 1px solid var(--line);+}++.diff-file {+ margin-bottom: 4px;+ overflow-wrap: anywhere;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+ font-weight: 600;+}++.diff-meta {+ overflow-wrap: anywhere;+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+}++.diff-hunk {+ margin: 6px 0 2px;+ padding: 2px 6px;+ overflow-wrap: anywhere;+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+ background: var(--chip-bg);+ border-radius: 4px;+}++.diff-row {+ display: flex;+ align-items: baseline;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11.5px;+ line-height: 16px;+}++.diff-no {+ flex: none;+ width: 34px;+ padding-right: 4px;+ color: var(--muted);+ text-align: right;+ user-select: none;+}++.diff-mark {+ flex: none;+ width: 14px;+ text-align: center;+}++.diff-text {+ flex: 1;+ min-width: 0;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}++.diff-add {+ color: var(--diff-add-text);+ background: var(--diff-add-bg);+}++.diff-remove {+ color: var(--diff-remove-text);+ background: var(--diff-remove-bg);+}++.diff-context {+ color: var(--text);+}++.diff-note {+ color: var(--muted);+ font-style: italic;+}++.diff-note-line {+ display: block;+ padding: 2px 6px;+ overflow-wrap: anywhere;+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+}++/* Side by side: two line-number columns, each cell keeps its own tint. */+.diff-side-row {+ display: grid;+ grid-template-columns: 34px minmax(0, 1fr) 34px minmax(0, 1fr);+}++.diff-side-row .diff-note-line {+ grid-column: 1 / -1;+}++.diff-side-no {+ width: auto;+ padding: 0 4px;+}++.diff-cell {+ min-width: 0;+ padding: 0 4px;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}++.diff-cell.is-empty {+ background: var(--bg);+ opacity: 0.55;+}+.drilldown-meta {display: grid;gap: 8px;diff --git a/packages/template/test/diffView.test.ts b/packages/template/test/diffView.test.tsnew file mode 100644index 0000000..a093270--- /dev/null+++ b/packages/template/test/diffView.test.ts@@ -0,0 +1,159 @@+import { describe, expect, it } from "vitest";+import { parsePatch, sideBySide } from "../src/diffView.js";++/**+ * Story 10.5: the message details show git's own patch. The parse and the+ * side-by-side pairing are pure, so their line numbers and pairing are pinned+ * here rather than only being looked at in a browser.+ */++const PATCH = [+ "diff --git a/src/a.ts b/src/a.ts",+ "index 1111111..2222222 100644",+ "--- a/src/a.ts",+ "+++ b/src/a.ts",+ "@@ -1,4 +1,5 @@ function",+ " one",+ "-two",+ "+TWO",+ "+TWO-extra",+ " three",+ "@@ -10,2 +11,2 @@",+ " ten",+ "-eleven",+ "+ELEVEN",+].join("\n");++describe("parsePatch", () => {+ it("splits files and hunks and numbers both sides", () => {+ const files = parsePatch(PATCH);+ expect(files).toHaveLength(1);+ const [file] = files;+ expect(file?.path).toBe("src/a.ts");+ expect(file?.binary).toBe(false);+ expect(file?.meta).toEqual(["index 1111111..2222222 100644", "--- a/src/a.ts"]);+ expect(file?.hunks).toHaveLength(2);++ expect(file?.hunks[0]?.lines).toEqual([+ { kind: "context", text: "one", oldNo: 1, newNo: 1 },+ { kind: "remove", text: "two", oldNo: 2, newNo: null },+ { kind: "add", text: "TWO", oldNo: null, newNo: 2 },+ { kind: "add", text: "TWO-extra", oldNo: null, newNo: 3 },+ { kind: "context", text: "three", oldNo: 3, newNo: 4 },+ ]);+ expect(file?.hunks[1]?.lines.at(-1)).toEqual({+ kind: "add",+ text: "ELEVEN",+ oldNo: null,+ newNo: 12,+ });+ });++ it("keeps the no-newline marker as a note", () => {+ const files = parsePatch(+ [+ "diff --git a/x b/x",+ "--- a/x",+ "+++ b/x",+ "@@ -1 +1 @@",+ "-a",+ "\\ No newline at end of file",+ "+b",+ ].join("\n"),+ );+ expect(files[0]?.hunks[0]?.lines[1]).toEqual({+ kind: "note",+ text: "\\ No newline at end of file",+ oldNo: null,+ newNo: null,+ });+ });++ it("marks binary files and starts a new file at each diff header", () => {+ const files = parsePatch(+ [+ "diff --git a/img.png b/img.png",+ "index 1111111..2222222 100644",+ "Binary files a/img.png and b/img.png differ",+ "diff --git a/src/b.ts b/src/b.ts",+ "+++ b/src/b.ts",+ "@@ -1 +1 @@",+ "-old",+ "+new",+ ].join("\n"),+ );+ expect(files.map((file) => file.path)).toEqual(["img.png", "src/b.ts"]);+ expect(files[0]?.binary).toBe(true);+ expect(files[0]?.hunks).toEqual([]);+ expect(files[1]?.hunks[0]?.lines).toHaveLength(2);+ });++ it("keeps the old path when the new side is /dev/null and skips prose", () => {+ const files = parsePatch(+ [+ "diff --git a/gone.txt b/gone.txt",+ "deleted file mode 100644",+ "--- a/gone.txt",+ "+++ /dev/null",+ "@@ -1 +0,0 @@",+ "-bye",+ ].join("\n"),+ );+ expect(files[0]?.path).toBe("gone.txt");+ expect(files[0]?.meta).toEqual(["deleted file mode 100644", "--- a/gone.txt"]);+ });++ it("falls back to the raw header when a path is not the usual form", () => {+ const files = parsePatch("diff --git weird\n");+ expect(files[0]?.path).toBe("weird");+ });++ it("ignores text outside any diff", () => {+ expect(+ parsePatch("diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\ntrailing"),+ ).toHaveLength(1);+ expect(parsePatch("not a patch")).toEqual([]);+ });+});++describe("sideBySide", () => {+ it("pairs a removal block with the additions that replace it", () => {+ const lines = parsePatch(PATCH)[0]?.hunks[0]?.lines ?? [];+ const rows = sideBySide(lines);+ expect(rows).toHaveLength(4);+ expect(rows[0]).toEqual({+ left: { kind: "context", no: 1, text: "one" },+ right: { kind: "context", no: 1, text: "one" },+ });+ expect(rows[1]).toEqual({+ left: { kind: "remove", no: 2, text: "two" },+ right: { kind: "add", no: 2, text: "TWO" },+ });+ // The second addition has no removed line to sit opposite.+ expect(rows[2]).toEqual({+ left: null,+ right: { kind: "add", no: 3, text: "TWO-extra" },+ });+ expect(rows[3]?.left).toEqual({ kind: "context", no: 3, text: "three" });+ });++ it("keeps more removals than additions on one side", () => {+ const rows = sideBySide([+ { kind: "remove", text: "a", oldNo: 1, newNo: null },+ { kind: "remove", text: "b", oldNo: 2, newNo: null },+ { kind: "add", text: "c", oldNo: null, newNo: 1 },+ ]);+ expect(rows).toHaveLength(2);+ expect(rows[0]?.left?.text).toBe("a");+ expect(rows[0]?.right?.text).toBe("c");+ expect(rows[1]?.left?.text).toBe("b");+ expect(rows[1]?.right).toBeNull();+ });++ it("spans a note across both sides", () => {+ const rows = sideBySide([+ { kind: "note", text: "\\ No newline at end of file", oldNo: null, newNo: null },+ ]);+ expect(rows).toEqual([{ left: null, right: null, note: "\\ No newline at end of file" }]);+ });+});diff --git a/packages/template/test/layout.test.ts b/packages/template/test/layout.test.tsindex b2d0af0..86bd349 100644--- a/packages/template/test/layout.test.ts+++ b/packages/template/test/layout.test.ts@@ -142,6 +142,9 @@ describe("small text contrast (Story 9.2)", () => {["warn", "kind-question-bg"],["kind-message-text", "kind-message-bg"],["kind-decision-text", "kind-decision-bg"],+ // Diff lines in the message details (Story 10.5).+ ["diff-add-text", "diff-add-bg"],+ ["diff-remove-text", "diff-remove-bg"],];it("declares a light theme besides the dark default", () => {