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): commit tags on messages and `codelineage blame`
Erenc824d9e93b68
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b43b447..c6595d4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Code in the map: a message whose record lists commits shows them as small tag chips (short hash) on its row; `build` reads each commit's subject from git and the drill-down names it, while a commit git no longer has stays listed and is drawn greyed. `codelineage blame <file>[:<line>]` follows git blame (or every commit that touched the file) back to the messages that recorded those commits and prints the commit, session, message, summary and the map URL that opens that message; with no hit it says so plainly. The map page hands a `#s=<session>&m=<message>` URL to the drill-down, so such a URL lands on the message.- The project map's top level is a git graph of sessions: one dot per session, titled with the session, hanging from the session its first message continues, with parallel lanes for sessions that run at the same time without a link and the epoch shown as a tag on the dot. Clicking a dot opens that session's message graph in place (a "← All sessions" control returns), and the session panel shows its status as a "squash message" (goal, done, pending, next). The epoch and session boxes and the `elkjs` layout are gone; both levels use the same layout engine. Live rebuilds keep the open session, selection and viewport.- The conversation store: `build` appends what the drill-down needs for turns not stored yet to `.codelineage/conversations/<sessionId>.jsonl.gz` (one gzip member per append, redacted with the same secret net as the page), reads it before the transcript, and keeps showing a session's conversation after Claude Code deletes the transcript. `init` writes `.codelineage/.gitignore` with `conversations/` even when `.codelineage/` is committed, an existing project gets the line on its next build, and the README explains where the raw chat lives. Stored turns keep the message's stable id, so ids survive the transcript.- Stable message ids: a message node is now `h` + the first 12 hex of the SHA-256 over `{sessionId, uuid, at, text}`, derived from the user message and not from its parent, so correcting a parent never renames a message (and its notes stay attached). `m1`, `m2`, … stay as display labels; `session show` prints both and `session write` accepts either. Records written before this are renamed on load and persisted on their next write.diff --git a/packages/cli/src/commands/blame.ts b/packages/cli/src/commands/blame.tsnew file mode 100644index 0000000..83fd578--- /dev/null+++ b/packages/cli/src/commands/blame.ts@@ -0,0 +1,140 @@+import { stat } from "node:fs/promises";+import { isAbsolute, relative, resolve, sep } from "node:path";+import { pathToFileURL } from "node:url";+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 { buildMessages } from "../view/lineage.js";++/**+ * `codelineage blame` (Story 8.8): git knows which commit wrote a line, the+ * records know which user message that commit carried out, so the command walks+ * commits → messages and points back at the map.+ */++export interface BlameOptions {+ dir: string;+ /** `file` or `file:line`. */+ target: string;+ io: Io;+}++export interface BlameHit {+ /** The blamed commit, short. */+ commit: string;+ sessionId: string;+ sessionTitle: string;+ messageId: string;+ /** The `m12` label the map shows. */+ label: string;+ title: string;+ summary?: string;+ /** The map page at that message. */+ url: string;+}++/** `src/app.ts:42` → file and line; a path without `:line` keeps no line. */+export function parseBlameTarget(target: string): { file: string; line?: number } {+ // Greedy, so a Windows drive letter or a colon in a directory stays in the file.+ const match = /^(.*):([1-9][0-9]*)$/.exec(target);+ if (match === null) return { file: target };+ return { file: match[1] as string, line: Number(match[2]) };+}++/** A short hash from the record may name a full hash from git, or the reverse. */+function sameCommit(recorded: string, blamed: string): boolean {+ return blamed.startsWith(recorded) || recorded.startsWith(blamed);+}++/** One readable line from git's failure; the first line carries the reason. */+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";+}++function oneLine(text: string): string {+ return text.replace(/\s+/g, " ").trim();+}++/**+ * 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+ * records do not know the code yet.+ */+export async function blame(opts: BlameOptions): Promise<BlameHit[]> {+ const { io } = opts;+ const { root } = await resolveProjectRoot(opts.dir);+ const project = await loadProject(root);+ if (!project.found)+ throw new CliError(`${root} is not initialized; run \`codelineage init\` first`);+ if (!project.ok) throw new CliError(project.error);++ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined)+ throw new CliError(`${root} is not inside a git repository; blame needs one`);++ const { file, line } = parseBlameTarget(opts.target);+ const absolute = resolve(root, file);+ const path = relative(gitRoot, absolute);+ if (path === "" || path.startsWith("..") || isAbsolute(path))+ throw new CliError(`${file} is outside ${gitRoot}`);+ // `git log -- <missing file>` quietly finds no commits; the user mistyped a path.+ const exists = await stat(absolute).then(+ (info) => info.isFile(),+ () => false,+ );+ if (!exists) throw new CliError(`${file} does not exist`);+ const repoPath = path.split(sep).join("/");++ let commits: string[];+ try {+ commits = await blameCommitHashes(gitRoot, repoPath, line);+ } catch (err) {+ throw new CliError(`git could not read ${opts.target}: ${gitMessage(err)}`);+ }++ const sessions = [...(await loadAllSessions(root, io.warn))].sort(+ (a, b) => a.startedAt.localeCompare(b.startedAt) || a.sessionId.localeCompare(b.sessionId),+ );+ 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,+ )}`,+ });+ }+ }+ }++ for (const hit of hits) {+ io.out(`${hit.commit} ${hit.sessionTitle} · ${hit.label} ${hit.title}`);+ if (hit.summary !== undefined && hit.summary.trim() !== "") io.out(` ${oneLine(hit.summary)}`);+ io.out(` ${hit.url}`);+ }+ if (hits.length === 0) {+ const what = line === undefined ? file : `${file}:${line}`;+ io.out(`No recorded message lists a commit that touched ${what}.`);+ }+ return hits;+}diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex bb492f8..132bfca 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -1,4 +1,4 @@-import { ensureConversationGitignore } from "../git.js";+import { ensureConversationGitignore, findGitRoot, readCommitSubjects } from "../git.js";import { CliError, type Io } from "../io.js";import {hashTurns,@@ -185,6 +185,25 @@ async function readTranscriptViews(return { chats, pending, sessions: prepared, unrecorded };}+/**+ * Every commit hash the records list, with its subject read from git, so the+ * message rows can show commit tags and the drill-down can name them (Story+ * 8.8). A project outside git, or a commit git no longer knows, only means+ * fewer subjects; the build never fails for it.+ */+async function commitSubjects(root: string, sessions: Session[]): Promise<Map<string, string>> {+ const hashes = new Set<string>();+ for (const session of sessions) {+ for (const node of session.nodes) {+ for (const hash of node.commits ?? []) hashes.add(hash);+ }+ }+ if (hashes.size === 0) return new Map();+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return new Map();+ return await readCommitSubjects(gitRoot, hashes);+}+/*** Rebuilds `.codelineage/lineage.html` from `project.json` and every session file,* then refreshes the global panel. One unreadable session is a warning, never a@@ -216,6 +235,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelconst transcripts = await collectTranscripts(io.env);const config = await loadConfig(io.env);const views = await readTranscriptViews(sessions, transcripts, root, io);+ const subjects = await commitSubjects(root, views.sessions);const built = buildViewModel({project: project.data,sessions: views.sessions,@@ -224,6 +244,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModeltranscripts: new Set(transcripts.keys()),chats: views.chats,pending: views.pending,+ commitSubjects: subjects,// With the catch-up on, the hook records the tail at session end, so the// count would only be a stale warning about work already scheduled.unrecorded: config.sessionEndCatchUp ? undefined : views.unrecorded,diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.tsindex 323f82b..fa97cf8 100644--- a/packages/cli/src/git.ts+++ b/packages/cli/src/git.ts@@ -1,7 +1,11 @@+import { execFile } from "node:child_process";import { readFile, stat } from "node:fs/promises";import { dirname, join } from "node:path";+import { promisify } from "node:util";import { atomicWrite } from "./store/fs.js";+const exec = promisify(execFile);+export type GitPolicy = "ignore" | "commit";/** Walks up from `dir` looking for `.git` (a directory, or a file in worktrees). */@@ -59,3 +63,103 @@ export async function ensureConversationGitignore(root: string): Promise<booleanawait atomicWrite(file, `${text}${sep}conversations/\n`);return true;}++interface CommitLine {+ full: string;+ short: string;+ subject: string;+}++/** `%H%x00%h%x00%s` lines from `git log` / `git show`, one commit each. */+function parseCommitLines(stdout: string): CommitLine[] {+ const out: CommitLine[] = [];+ for (const line of stdout.split("\n")) {+ const [full, short, subject] = line.split("\0");+ if (full === undefined || !/^[0-9a-f]{40}$/.test(full)) continue;+ out.push({ full, short: short ?? "", subject: subject ?? "" });+ }+ return out;+}++/** The recorded hash may be short or full; either way it names the same commit. */+function matches(recorded: string, commit: CommitLine): boolean {+ return commit.full.startsWith(recorded) || recorded.startsWith(commit.short);+}++/**+ * Subjects of the given commit hashes in the repository at `root`, keyed by the+ * hash the record holds (Story 8.8: commit tags on the map). Missing commits and+ * a missing git binary are not errors: the map shows those tags greyed. One+ * `git log` call covers the common case; a hash git no longer knows makes that+ * call fail, so the fallback asks for each hash alone and keeps the rest.+ */+export async function readCommitSubjects(+ root: string,+ hashes: Iterable<string>,+): Promise<Map<string, string>> {+ const wanted = [...new Set(hashes)];+ const out = new Map<string, string>();+ if (wanted.length === 0) return out;++ const remember = (entries: CommitLine[]): void => {+ for (const hash of wanted) {+ const commit = entries.find((entry) => matches(hash, entry));+ if (commit) out.set(hash, commit.subject);+ }+ };++ try {+ const { stdout } = await exec("git", [+ "-C",+ root,+ "log",+ "--no-walk=unsorted",+ "--format=%H%x00%h%x00%s",+ ...wanted,+ ]);+ remember(parseCommitLines(stdout));+ } catch {+ for (const hash of wanted) {+ try {+ const { stdout } = await exec("git", [+ "-C",+ root,+ "show",+ "-s",+ "--format=%H%x00%h%x00%s",+ hash,+ ]);+ remember(parseCommitLines(stdout));+ } catch {+ // gone from this repository (rebased away, or another checkout)+ }+ }+ }+ return out;+}++/**+ * Full hashes git blames for `file`; `file:line` asks about one line and a bare+ * file means every commit that touched it (Story 8.8). `file` is relative to+ * `root`, the repository's worktree.+ */+export async function blameCommitHashes(+ root: string,+ file: string,+ line?: number,+): Promise<string[]> {+ const args =+ line === undefined+ ? ["-C", root, "log", "--format=%H", "--", file]+ : ["-C", root, "blame", "--porcelain", "-L", `${line},${line}`, "--", file];+ const { stdout } = await exec("git", args);+ const out = new Set<string>();+ for (const row of stdout.split("\n")) {+ const hash = row.slice(0, 40);+ if (!/^[0-9a-f]{40}$/.test(hash)) continue;+ // `blame --porcelain` rows continue with the line numbers; a bare `git log`+ // row is the hash alone.+ if (row.length === 40 || /^[0-9a-f]{40} \d+ \d+/.test(row)) out.add(hash);+ }+ return [...out];+}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex fdb199c..c690482 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -1,6 +1,7 @@import { Command, InvalidArgumentError, Option } from "commander";import pkg from "../package.json" with { type: "json" };import { backfillTail } from "./commands/backfill.js";+import { blame } from "./commands/blame.js";import { buildProject } from "./commands/build.js";import {configGet,@@ -88,6 +89,17 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =}),);+ program+ .command("blame")+ .description("show which recorded messages produced the code in a file or line")+ .argument("<target>", "file, or file:line")+ .option("-C, --dir <dir>", "project directory", ".")+ .action(+ run(async (target: string, opts: { dir: string }) => {+ await blame({ dir: opts.dir, target, io: makeIo(false) });+ }),+ );+program.command("open").description("build and open a project map, or the global panel without a directory")diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.tsindex 98a415b..cb5e859 100644--- a/packages/cli/src/view/lineage.ts+++ b/packages/cli/src/view/lineage.ts@@ -23,6 +23,7 @@ import {export function buildMessages(nodes: LineageNode[],pending: ViewPendingMessage[] = [],+ commitSubjects?: 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@@ -101,6 +102,14 @@ export function buildMessages(...(node.decidedBy === undefined ? {} : { decidedBy: node.decidedBy }),...(node.alternatives?.length ? { alternatives: node.alternatives } : {}),...(node.commits?.length ? { commits: node.commits } : {}),+ ...(node.commits?.length+ ? {+ commitTags: node.commits.map((hash) => {+ const subject = commitSubjects?.get(hash);+ return subject === undefined ? { hash } : { hash, subject };+ }),+ }+ : {}),...(node.files?.length ? { files: node.files } : {}),...(node.work?.length ? { work: node.work } : {}),...(node.agentDecisions?.length ? { agentDecisions: node.agentDecisions } : {}),@@ -186,6 +195,7 @@ function toViewSession(chat?: ViewChatTurn[],unrecorded?: number,pending?: ViewPendingMessage[],+ commitSubjects?: ReadonlyMap<string, string>,): ViewSession {return {sessionId: session.sessionId,@@ -195,7 +205,7 @@ function toViewSession(startedAt: session.startedAt,updatedAt: session.updatedAt,status: session.status,- messages: buildMessages(session.nodes, pending),+ messages: buildMessages(session.nodes, pending, commitSubjects),// 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),@@ -224,6 +234,8 @@ export interface ViewModelInput {unrecorded?: ReadonlyMap<string, number> | undefined;/** User messages with no node yet, drawn as not-yet-summarized cards. */pending?: ReadonlyMap<string, ViewPendingMessage[]> | undefined;+ /** Commit subjects read from git at build time (Story 8.8). */+ commitSubjects?: ReadonlyMap<string, string> | undefined;}/**@@ -274,6 +286,7 @@ export function buildViewModel(input: ViewModelInput): LineageViewModel {input.chats?.get(session.sessionId),input.unrecorded?.get(session.sessionId),input.pending?.get(session.sessionId),+ input.commitSubjects,);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 3fca781..ac97ed0 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -20,6 +20,14 @@ export const LIVE_META_NAME = "codelineage-live";/** Version of the serialized view model (not the session schema). */export const VIEW_SCHEMA = 1;+/** A code commit a message carries, with the subject read from git at build time. */+export interface ViewCommit {+ /** The hash as the record holds it (short or full). */+ hash: string;+ /** The commit's subject; absent when git no longer knows the commit. */+ subject?: string;+}+export interface ViewNode {/** Stable id (`h…`); the key of the node, never shown to the user. */id: string;@@ -49,6 +57,11 @@ export interface ViewNode {decidedBy?: "user" | "agent" | "agreed";alternatives?: { option: string; why: string }[];commits?: string[];+ /**+ * `commits` with their subjects (Story 8.8); the map draws them as small tag+ * chips. A tag without a subject is a commit git no longer has, drawn greyed.+ */+ commitTags?: ViewCommit[];files?: string[];/** For a message: what the agent did about it. */work?: string[];diff --git a/packages/cli/test/blame.test.ts b/packages/cli/test/blame.test.tsnew file mode 100644index 0000000..9842c91--- /dev/null+++ b/packages/cli/test/blame.test.ts@@ -0,0 +1,156 @@+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 { blame, parseBlameTarget } from "../src/commands/blame.js";+import { init } from "../src/commands/init.js";+import { createProgram } from "../src/program.js";+import type { Session } from "../src/schema/session.js";+import { projectPaths } from "../src/store/paths.js";+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";++const run = promisify(execFile);++function session(over: Partial<Session> & { sessionId: string }): Session {+ return {+ schema: 1,+ agent: "claude-code",+ title: "",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [],+ ...over,+ };+}++describe("parseBlameTarget", () => {+ it("splits file:line and leaves a bare path alone", () => {+ expect(parseBlameTarget("src/app.ts:42")).toEqual({ file: "src/app.ts", line: 42 });+ expect(parseBlameTarget("src/app.ts")).toEqual({ file: "src/app.ts" });+ // A colon without digits is part of the name, and a drive letter is not a line.+ expect(parseBlameTarget("notes:2026.md")).toEqual({ file: "notes:2026.md" });+ expect(parseBlameTarget("C:\\repo\\a.ts:3")).toEqual({ file: "C:\\repo\\a.ts", line: 3 });+ });+});++describe("codelineage blame", () => {+ let dir: string;+ let root: string;+ let io: FakeIo;+ let shortA: string;+ const git = async (...args: string[]) => run("git", ["-C", root, ...args]);++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ io = fakeIo(envFor(dir));+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "T");+ await writeFile(join(root, "a.txt"), "one\ntwo\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "feat: add a");+ shortA = (await git("rev-parse", "--short", "HEAD")).stdout.trim();+ await writeFile(join(root, "b.txt"), "b\n");+ await git("add", "b.txt");+ await git("commit", "-q", "-m", "feat: add b");++ const record = session({+ sessionId: "s1",+ title: "Ship the parser",+ nodes: [+ {+ id: "h1",+ parent: null,+ kind: "message",+ title: "Parse the file",+ summary: "A line is read and parsed.",+ at: T0,+ commits: [shortA],+ },+ ],+ });+ await writeFile(projectPaths(root).session("s1"), JSON.stringify(record));+ // A second session keeps the output order deterministic (and exercises the sort).+ await writeFile(+ projectPaths(root).session("s0"),+ JSON.stringify(session({ sessionId: "s0", title: "Earlier chat" })),+ );+ });++ it("points a line at the message that recorded its commit", async () => {+ const hits = await blame({ dir: root, target: "a.txt:1", io });+ expect(hits).toHaveLength(1);+ expect(hits[0]).toMatchObject({+ commit: shortA.slice(0, 7),+ sessionId: "s1",+ sessionTitle: "Ship the parser",+ label: "m1",+ title: "Parse the file",+ summary: "A line is read and parsed.",+ });+ expect(hits[0]?.url).toMatch(/#s=s1&m=h1$/);+ expect(io.lines[0]).toBe(`${shortA.slice(0, 7)} Ship the parser · m1 Parse the file`);+ expect(io.lines[1]).toBe(" A line is read and parsed.");+ expect(io.lines[2]).toBe(` ${hits[0]?.url}`);+ });++ it("runs through the CLI", async () => {+ const program = createProgram(() => io);+ await program.parseAsync(["blame", "a.txt:1", "-C", root], { from: "user" });+ expect(io.lines[0]).toContain("Parse the file");+ });++ it("accepts a file without a line and searches every commit that touched it", async () => {+ const hits = await blame({ dir: root, target: "a.txt", io });+ expect(hits.map((hit) => hit.title)).toEqual(["Parse the file"]);+ });++ it("says plainly when no recorded message knows the code", async () => {+ const hits = await blame({ dir: root, target: "b.txt", io });+ expect(hits).toEqual([]);+ expect(io.lines).toEqual(["No recorded message lists a commit that touched b.txt."]);+ });++ it("reports a file that does not exist", async () => {+ await expect(blame({ dir: root, target: "missing.txt", io })).rejects.toThrow(+ /missing\.txt does not exist/,+ );+ });++ it("reports a target git cannot blame", async () => {+ await writeFile(join(root, "untracked.txt"), "one\n");+ await expect(blame({ dir: root, target: "untracked.txt:1", io })).rejects.toThrow(+ /git could not read untracked\.txt:1/,+ );+ });++ it("refuses a file outside the repository", async () => {+ await expect(blame({ dir: root, target: "../other.txt", io })).rejects.toThrow(/outside/);+ });++ it("needs an initialized project", async () => {+ const empty = join(dir, "empty");+ await mkdir(empty);+ await expect(blame({ dir: empty, target: "a.txt", io })).rejects.toThrow(/not initialized/);+ });++ it("reports a broken project file", async () => {+ await writeFile(projectPaths(root).project, "{nope");+ await expect(blame({ dir: root, target: "a.txt", io })).rejects.toThrow(/invalid JSON/);+ });++ it("needs a git repository", async () => {+ const plain = join(dir, "plain");+ await mkdir(plain);+ await init(plain, { name: "plain", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));+ await expect(blame({ dir: plain, target: "a.txt", io })).rejects.toThrow(+ /not inside a git repository/,+ );+ });+});diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.tsindex d2beb19..d16d8a8 100644--- a/packages/cli/test/build.test.ts+++ b/packages/cli/test/build.test.ts@@ -1,6 +1,8 @@+import { execFile } from "node:child_process";import { existsSync } from "node:fs";import { appendFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { join } from "node:path";+import { promisify } from "node:util";import { gzipSync } from "node:zlib";import { beforeEach, describe, expect, it } from "vitest";import { buildProject } from "../src/commands/build.js";@@ -16,6 +18,8 @@ import { buildMessages, buildViewModel, embedViewModel, statusCard } from "../srimport { DATA_ELEMENT_ID } from "../src/view/model.js";import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";+const run = promisify(execFile);+const TEMPLATE = `<!doctype html><html><body><div id="root"></div><script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;@@ -555,6 +559,46 @@ describe("codelineage build", () => {expect(await readFile(paths().session("s1"), "utf8")).not.toContain("Fix the card");});+ it("reads commit subjects from git for the map and greys a hash git no longer has", async () => {+ const git = (...args: string[]) => run("git", ["-C", root, ...args]);+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "T");+ await writeFile(join(root, "a.txt"), "one\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "feat: first commit");+ const short = (await git("rev-parse", "--short", "HEAD")).stdout.trim();+ await saveSession(+ "s1",+ session({+ sessionId: "s1",+ epoch: "e1",+ nodes: [node("m1", "message", "Ship it", null, { commits: [short] })],+ }),+ );++ 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" },+ ]);++ // One hash git does not know makes the batched lookup fail; the per-hash+ // fallback still keeps the commit it can read.+ await saveSession(+ "s1",+ session({+ sessionId: "s1",+ epoch: "e1",+ nodes: [node("m1", "message", "Ship it", null, { commits: [short, "0000000"] })],+ }),+ );+ 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: "0000000" },+ ]);+ });+it("keeps the conversation in the project and shows it after the transcript is gone", async () => {const folder = join(dir, "claude", "projects", "-proj");await mkdir(folder, { recursive: true });diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsxindex 9c3773b..61f3993 100644--- a/packages/template/src/GitGraph.tsx+++ b/packages/template/src/GitGraph.tsx@@ -103,6 +103,28 @@ function Row({) : null}<span className="git-id">{message.label ?? message.id}</span><span className="git-title">{message.title}</span>+ {row.tags.length > 0 ? (+ <span className="git-tags">+ {row.tags.map((tag) => (+ // A span, not a button: the whole row is already a button.+ <span+ key={tag.hash}+ className={`git-tag${tag.missing ? " is-missing" : ""}`}+ title={+ tag.missing+ ? `commit ${tag.short} is not in this repository`+ : `${tag.short} ${tag.subject ?? ""}`+ }+ onClick={(event: MouseEvent) => {+ event.stopPropagation();+ onSelect(row);+ }}+ >+ {tag.short}+ </span>+ ))}+ </span>+ ) : null}{message.continues ? (<spanclassName="git-continues"diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsxindex abb8f70..31d4ab5 100644--- a/packages/template/src/Graph.tsx+++ b/packages/template/src/Graph.tsx@@ -85,6 +85,24 @@ const nodeTypes: NodeTypes = {messages: MessagesBox,};+/**+ * The message a `#s=<sessionId>&m=<messageId>` URL asks for (Story 8.8:+ * `codelineage blame` prints such a URL). The session opens and the message's+ * drill-down is shown; a message id the record no longer holds opens the session.+ */+function readTarget(model: LineageViewModel): { sessionId: string; messageId?: string } | null {+ if (typeof window === "undefined") return null;+ const params = new URLSearchParams(window.location.hash.replace(/^#/, ""));+ const sessionId = params.get("s");+ if (sessionId === null || sessionId === "") return null;+ const session = findSession(model, sessionId);+ if (session === undefined) return null;+ const messageId = params.get("m");+ if (messageId !== null && session.messages.some((message) => message.id === messageId))+ return { sessionId, messageId };+ return { sessionId };+}+function findSession(model: LineageViewModel, id: string): ViewSession | undefined {for (const epoch of model.epochs) {const session = epoch.sessions.find((candidate) => candidate.sessionId === id);@@ -94,35 +112,69 @@ function findSession(model: LineageViewModel, id: string): ViewSession | undefin}function Flow({ model }: { model: LineageViewModel }) {- const [openId, setOpenId] = useState<string | null>(null);- const [selection, setSelection] = useState<Selection | null>(null);+ // Read once: a live data swap must not move the page back to the hash target.+ const [initial] = useState(() => readTarget(model));+ const [openId, setOpenId] = useState<string | null>(initial?.sessionId ?? null);+ const [selection, setSelection] = useState<Selection | null>(() => {+ if (initial === null) return null;+ if (initial.messageId === undefined) return { type: "session", sessionId: initial.sessionId };+ return { type: "node", sessionId: initial.sessionId, nodeId: initial.messageId };+ });const [unfolded, setUnfolded] = useState<Set<string>>(() => new Set());const [openAll, setOpenAll] = useState(false);const [showOutline, setShowOutline] = useState(false);const { expanded: fullscreen, toggle: toggleFullscreen } = useFullscreen();- const [focusedId, setFocusedId] = useState<string | null>(null);+ const [focusedId, setFocusedId] = useState<string | null>(() => {+ if (initial === null) return null;+ if (initial.messageId === undefined) return `session:${initial.sessionId}`;+ return `node:session:${initial.sessionId}:${initial.messageId}`;+ });const openSession = openId === null ? undefined : findSession(model, openId);const head = headOf(model);const sessionGraph = useMemo(() => layoutSessionGraph(model), [model]);+ /** The open drill-down's message, when it belongs to the open session. */+ const targetId =+ selection?.type === "node" && selection.sessionId === openSession?.sessionId+ ? selection.nodeId+ : null;+const messageGit = useMemo(() => {if (!openSession) return null;- return layoutGitGraph(openSession.messages, {+ const options = {unfolded,openAll,headId: head?.sessionId === openSession.sessionId ? head.messageId : null,- });- }, [openSession, head?.sessionId, head?.messageId, unfolded, openAll]);+ };+ const layout = layoutGitGraph(openSession.messages, options);+ if (targetId === null) return layout;+ const visible = layout.rows.some(+ (row) => row.kind === "message" && row.message.id === targetId,+ );+ if (visible) return layout;+ // A deep link (`blame` prints one) may point inside a folded branch: open it+ // rather than letting the page land on a row the user cannot see.+ const segment = layout.segments.find((candidate) => candidate.ids.includes(targetId));+ return segment === undefined+ ? layout+ : layoutGitGraph(openSession.messages, {+ ...options,+ unfolded: new Set([...unfolded, segment.id]),+ });+ }, [openSession, head?.sessionId, head?.messageId, unfolded, openAll, targetId]);- /** Row the view centres on when a session opens: its newest message (HEAD). */+ /** Row the view centres on when a session opens: the open message, else HEAD. */const focusRow = useMemo(() => {- if (!openSession || !messageGit || head?.sessionId !== openSession.sessionId) return null;+ if (!openSession || !messageGit) return null;+ const id =+ targetId ?? (head?.sessionId === openSession.sessionId ? (head.messageId ?? null) : null);+ if (id === null) return null;const row = messageGit.rows.find(- (candidate) => candidate.kind === "message" && candidate.message.id === head.messageId,+ (candidate) => candidate.kind === "message" && candidate.message.id === id,);return row ? { x: messageGit.graphWidth / 2, y: row.y } : null;- }, [openSession, messageGit, head?.sessionId, head?.messageId]);+ }, [openSession, messageGit, targetId, head?.sessionId, head?.messageId]);const viewKey = openSession ? `session:${openSession.sessionId}` : "project";diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex 222cd6d..a1d393a 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -418,9 +418,20 @@ function NodeDetails({<h3>In the code</h3>{node.commits?.length ? (<p className="drilldown-code">- {node.commits.map((commit) => (- <code key={commit}>{commit}</code>- ))}+ {node.commits.map((commit) => {+ const tag = node.commitTags?.find((candidate) => candidate.hash === commit);+ const missing = node.commitTags !== undefined && tag?.subject === undefined;+ return (+ <code+ key={commit}+ className={missing ? "is-missing" : undefined}+ title={missing ? "commit not in this repository" : undefined}+ >+ {commit}+ {tag?.subject === undefined ? "" : ` ${tag.subject}`}+ </code>+ );+ })}</p>) : null}{node.files?.length ? (diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.tsindex 90c6c5d..9417cc3 100644--- a/packages/template/src/fixture.ts+++ b/packages/template/src/fixture.ts@@ -84,6 +84,11 @@ export const fixture: LineageViewModel = {}),message("m4", "Build the dev fixture", "m3", "2026-10-24T09:41:00.000Z", {summary: "Two epochs, three sessions, one unassigned.",+ commits: ["1a2b3c4", "9f8e7d6"],+ commitTags: [+ { hash: "1a2b3c4", subject: "feat(template): add the dev fixture" },+ { hash: "9f8e7d6" },+ ],}),message("m5", "Check the page in the browser", "m4", "2026-10-24T10:02:00.000Z", {summary: "Layout measured; console clean.",diff --git a/packages/template/src/gitLayout.ts b/packages/template/src/gitLayout.tsindex 1001596..85f5398 100644--- a/packages/template/src/gitLayout.ts+++ b/packages/template/src/gitLayout.ts@@ -27,6 +27,8 @@ export interface GitNode {links?: string[] | undefined;branch?: ViewNode["branch"];continues?: ViewNode["continues"];+ commits?: string[] | undefined;+ commitTags?: ViewNode["commitTags"];unsummarized?: true | undefined;/*** When the item stops occupying its lane, as a timestamp. Session level only:@@ -89,6 +91,40 @@ export interface GitSegment {parentY: number | null;}+/** One commit chip on a message row (Story 8.8). */+export interface GitCommitTag {+ /** The hash as the record holds it; a stable key. */+ hash: string;+ /** The short hash the chip shows. */+ short: string;+ /** The commit's subject, when git still knows the commit. */+ subject?: string;+ /** True when git no longer knows the commit: the chip is drawn greyed. */+ missing: boolean;+}++/** The message's commits as chips, from the build's subjects or the bare hashes. */+function tagsOf(message: GitNode): GitCommitTag[] {+ const tags: GitCommitTag[] =+ message.commitTags && message.commitTags.length > 0+ ? message.commitTags.map((commit) =>+ commit.subject === undefined+ ? { hash: commit.hash, short: commit.hash.slice(0, 7), missing: true }+ : {+ hash: commit.hash,+ short: commit.hash.slice(0, 7),+ subject: commit.subject,+ missing: false,+ },+ )+ : (message.commits ?? []).map((hash) => ({+ hash,+ short: hash.slice(0, 7),+ missing: true,+ }));+ return tags;+}+export interface GitReturn {/** The older message this row returns to. */id: string;@@ -109,6 +145,8 @@ export interface GitMessageRow {/** A new root starts here, with a gap above it. */gap: boolean;returns: GitReturn[];+ /** Code commits the record lists for this message; empty for most rows. */+ tags: GitCommitTag[];/** "left off here": the newest message or session. */head: boolean;/** Row height: titles wrap instead of being cut, so long ones get taller rows. */@@ -206,7 +244,7 @@ const ROW_FIXED = 106;*/export function rowHeight(message: GitNode,- row: { first: boolean; branchTitle: string; returns: number; head: boolean },+ row: { first: boolean; branchTitle: string; returns: number; tags: number; head: boolean },rowWidth = ROW_WIDTH,): number {const fixed =@@ -214,6 +252,7 @@ export function rowHeight((message.label ?? message.id).length * 7 +(row.first ? BRANCH_MAX + 8 : 0) +row.returns * 44 ++ row.tags * 62 +(row.head ? 92 : 0) +(message.unsummarized ? 116 : 0) +// The "↑ continues <session> · m67" mark sits in the row, next to the title.@@ -381,6 +420,7 @@ export function layoutGitGraph(messages: GitNode[], options: GitLayoutOptions =first: row.segment.ids[0] === message.id,branchTitle: row.segment.branch.title,returns: (message.links ?? []).filter((id) => segOf.has(id)).length,+ tags: tagsOf(message).length,head: message.id === headId,},rowWidth,@@ -484,6 +524,7 @@ export function layoutGitGraph(messages: GitNode[], options: GitLayoutOptions =first: row.segment.ids[0] === message.id,gap: row.gap,returns,+ tags: tagsOf(message),head: message.id === headId,height: row.height,};diff --git a/packages/template/src/graph.ts b/packages/template/src/graph.tsindex 61b8e6c..96baa61 100644--- a/packages/template/src/graph.ts+++ b/packages/template/src/graph.ts@@ -16,6 +16,7 @@ export type NodeDetail = {decidedBy?: ViewNode["decidedBy"];alternatives?: ViewNode["alternatives"];commits?: string[];+ commitTags?: ViewNode["commitTags"];files?: string[];work?: ViewNode["work"];agentDecisions?: ViewNode["agentDecisions"];diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex bc201bf..b771f3b 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -519,6 +519,12 @@ body:has(.map-shell.is-expanded) {gap: 6px;}+/* A commit git no longer has stays listed, greyed (Story 8.8). */+.drilldown-code code.is-missing {+ color: #5f6675;+ border-style: dashed;+}+.drilldown-meta {display: grid;gap: 8px;@@ -879,6 +885,36 @@ time {font-size: 11px;}+/* Commit tags on a message row (Story 8.8): a short hash, greyed when git no+ longer knows the commit. */+.git-tags {+ display: flex;+ flex: none;+ gap: 4px;+}++.git-tag {+ padding: 0 4px;+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 10px;+ line-height: 15px;+ background: #1c222e;+ border: 1px solid #323b4d;+ border-radius: 3px;+ cursor: pointer;+}++.git-tag:hover {+ color: var(--text);+ border-color: var(--accent);+}++.git-tag.is-missing {+ color: #5f6675;+ border-style: dashed;+}+/* "↑ continues <session> · m67": a jump to the earlier session's message. */.git-continues {flex: none;diff --git a/packages/template/test/gitLayout.test.ts b/packages/template/test/gitLayout.test.tsindex 9bc30ba..7345a11 100644--- a/packages/template/test/gitLayout.test.ts+++ b/packages/template/test/gitLayout.test.ts@@ -165,6 +165,34 @@ describe("rows", () => {expect(layout.height).toBe(ROW_HEIGHT / 2 + first!.height + second!.height + third!.height);});+ it("carries a message's commits as tag chips, marking one git no longer knows", () => {+ const { messageRows } = rowsOf([+ message("m1", null, {+ commitTags: [+ { hash: "abc1234", subject: "feat(map): draw commit tags" },+ { hash: "deadbee" },+ ],+ }),+ message("m2", "m1"),+ ]);+ expect(messageRows[0]?.tags).toEqual([+ {+ hash: "abc1234",+ short: "abc1234",+ subject: "feat(map): draw commit tags",+ missing: false,+ },+ { hash: "deadbee", short: "deadbee", missing: true },+ ]);+ expect(messageRows[1]?.tags).toEqual([]);++ // A hand-written model with only bare hashes still gets chips, all greyed.+ const bare = rowsOf([message("m1", null, { commits: ["fedcba9"] })]);+ expect(bare.messageRows[0]?.tags).toEqual([+ { hash: "fedcba9", short: "fedcba9", missing: true },+ ]);+ });+it("marks the newest message as HEAD unless told otherwise", () => {const messages = [message("m1", null), message("m2", "m1"), message("m3", "m2")];const rows = layoutGitGraph(messages).rows.filter(diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.mdindex b2b04d6..e14484c 100644--- a/specs/codelineage-mvp.md+++ b/specs/codelineage-mvp.md@@ -38,8 +38,13 @@ these records into static HTML:left out and tool use counted), previous/next message buttons, and a`claude --resume <id>` copy button. `build` reads the conversation from thetranscript into `lineage.html` only (never committed, see Privacy); session- files never hold raw text. Records from before messages carried message- parents (their `parent` is a topic or step) render as one chain in send order.+ files never hold raw text. A message whose record lists commits shows them as+ small tag chips with the commit subject read from git at build time; a commit+ git no longer has stays listed and is drawn greyed. `codelineage blame+ <file>[:<line>]` follows git blame (or every commit that touched the file)+ back to the messages that recorded those commits, and prints the map URL that+ opens each message. Records from before messages carried message parents+ (their `parent` is a topic or step) render as one chain in send order.- **Status card** at the top of every project: goal, done, pending (flags itemswaiting on the user), next step, last activity. With parallel sessions, goal andnext come from the most recently updated session; `needsUser` items are merged@@ -234,6 +239,7 @@ Each update costs agent tokens (the user's subscription or API usage).| `codelineage init` | Creates `.codelineage/`, registers the project, asks the install questions || `codelineage build [dir]` | Regenerates `lineage.html` and `panel.html` || `codelineage open [dir]` | Builds, then opens the map (or the panel if no dir is given) through the local map server, starting it in the background if it is not running. The open page refreshes itself whenever the map is rebuilt, keeping the selected branch, unfolded branches, scroll and zoom. Falls back to opening the file when the server cannot start. |+| `codelineage blame <file>[:<line>]` | Follows git blame (or `git log` for a whole file) back to the messages whose record lists those commits; prints each commit, session, message, summary and the map URL that opens that message. Says so plainly when no record knows the code. || `codelineage epoch add <id> <title>` | Adds an epoch (locked write) || `codelineage config get/set <key> [value]` | Reads or changes settings || `codelineage config hint-off [dir]` | Stops the SessionStart setup offer in that project ("don't ask again") |