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): draw each session as a git graph of its messages
Eren8aea48dd6aaf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 31b52f0..35d2403 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- Lineage records: each message node now hangs from the earlier message it reacts to (or is a new root), with up to five `links` back to other messages and a `branch` summary (title, asked, outcome, open) on the first message of each branch. `session write` moves a parent that is not an earlier message to the previous message and drops links that are not earlier messages, with a warning; `session show` hints each unrecorded message with `gapMinutes`, `resumed` (a `/clear` or a resume in between) and `commitBetween` (a commit this session made), and lists the last recorded messages with their parent.+### Changed+- The map draws each session as a git graph of the user's messages: one row per message in send order, one coloured lane per branch, a hollow ring and the branch title at a branch's first row, a curve out of the message a branch reacts to, and a dashed return arrow through a channel left of the lanes with "↩ m22" on the row. Long branches fold to first / "⋮ N more" / last with an "Unfold all" toggle, the newest branch starts unfolded and "left off here" marks the newest message. A clicked row opens the branch summary (range, count, time span, asked / outcome / open) above the existing message drill-down, and the map opens framed on the newest message at a readable zoom. Records whose message parents point at topics render as one chain; the old topic layout and its card sizing are removed. Live rebuilds keep the selected branch, unfolded branches, scroll and zoom.+### Fixed- `open` adds an initialized project that is missing from the global registry (for example one set up inside a sandbox with its own home) back before serving it; the local map server only shows registered projects, so such a map returned "not found". When the registry cannot be written, `open` opens the file instead.diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.tsindex 9da98a2..6ee08ba 100644--- a/packages/cli/src/view/lineage.ts+++ b/packages/cli/src/view/lineage.ts@@ -14,80 +14,92 @@ import {} from "./model.js";/**- * Turns a session's flat node list into the nested tree the graph draws, siblings- * in the order their threads began (stored order for unstamped nodes). A missing parent, a self-reference or a cycle becomes a root, so no- * recorded node is ever dropped.+ * The session's user messages, flat and in the order they were sent (8.2). A+ * message hangs from the earlier message it reacts to; an explicit `null` in+ * the record makes a new root. Any other parent (a topic in an older record, a+ * forward or unknown id) falls back to the previous message, so an old record+ * renders as one chain and no message is ever dropped.*/-export function buildNodeTree(nodes: LineageNode[]): ViewNode[] {- const byId = new Map(nodes.map((node) => [node.id, node]));- const childrenOf = new Map<string, LineageNode[]>();- const roots: LineageNode[] = [];- for (const node of nodes) {- const parent = node.parent === null ? undefined : byId.get(node.parent);- if (parent && parent.id !== node.id) {- const list = childrenOf.get(parent.id) ?? [];- list.push(node);- childrenOf.set(parent.id, list);- } else {- roots.push(node);- }- }+export function buildMessages(+ nodes: LineageNode[],+ pending: ViewPendingMessage[] = [],+): ViewNode[] {+ const messages = nodes.filter((node) => node.kind === "message").sort(compareMessages);+ const known = new Set(messages.map((message) => message.id));+ /** Position in send order: a parent or link must come before the message. */+ const order = new Map(messages.map((message, index) => [message.id, index]));+ const earlier = (other: string, id: string): boolean => {+ const otherAt = order.get(other);+ const selfAt = order.get(id);+ return otherAt !== undefined && selfAt !== undefined && otherAt < selfAt;+ };+ const out: ViewNode[] = [];+ let previous: string | null = null;- const visited = new Set<string>();- const build = (node: LineageNode): ViewNode => {- visited.add(node.id);- const children = (childrenOf.get(node.id) ?? [])- .filter((child) => !visited.has(child.id))- .map(build);- return {- id: node.id,- kind: node.kind,- title: node.title,- ...(node.summary === undefined ? {} : { summary: node.summary }),- ...(node.why === undefined ? {} : { why: node.why }),- ...(node.at === undefined ? {} : { at: node.at }),- ...(node.decidedBy === undefined ? {} : { decidedBy: node.decidedBy }),- ...(node.alternatives?.length ? { alternatives: node.alternatives } : {}),- ...(node.commits?.length ? { commits: node.commits } : {}),- ...(node.files?.length ? { files: node.files } : {}),- ...(node.work?.length ? { work: node.work } : {}),- ...(node.agentDecisions?.length ? { agentDecisions: node.agentDecisions } : {}),- ...(node.addedAt === undefined ? {} : { addedAt: node.addedAt }),- ...(node.touchedAt === undefined ? {} : { touchedAt: node.touchedAt }),- children,- };+ const push = (message: ViewNode, parent: string | null): void => {+ message.parent = parent;+ out.push(message);+ previous = message.id;};- const tree = roots.filter((root) => !visited.has(root.id)).map(build);- // A pure cycle has no root, so break it at the first node not yet emitted.- for (const node of nodes) if (!visited.has(node.id)) tree.push(build(node));- return byStart(tree);-}+ for (const node of messages) {+ const parent =+ node.parent === null+ ? null+ : node.parent !== undefined && known.has(node.parent) && earlier(node.parent, node.id)+ ? node.parent+ : previous;+ const links = (node.links ?? []).filter((link) => known.has(link) && earlier(link, node.id));+ push(+ {+ id: node.id,+ kind: node.kind,+ title: node.title,+ ...(node.summary === undefined ? {} : { summary: node.summary }),+ ...(node.why === undefined ? {} : { why: node.why }),+ ...(node.at === undefined ? {} : { at: node.at }),+ ...(node.decidedBy === undefined ? {} : { decidedBy: node.decidedBy }),+ ...(node.alternatives?.length ? { alternatives: node.alternatives } : {}),+ ...(node.commits?.length ? { commits: node.commits } : {}),+ ...(node.files?.length ? { files: node.files } : {}),+ ...(node.work?.length ? { work: node.work } : {}),+ ...(node.agentDecisions?.length ? { agentDecisions: node.agentDecisions } : {}),+ ...(node.addedAt === undefined ? {} : { addedAt: node.addedAt }),+ ...(node.touchedAt === undefined ? {} : { touchedAt: node.touchedAt }),+ ...(node.branch === undefined ? {} : { branch: node.branch }),+ ...(links.length ? { links } : {}),+ },+ parent,+ );+ }-/**- * When a node's thread began: its own or any descendant's start, whichever is- * earliest. A message starts when the user sent it, other nodes when they were- * added. Unstamped nodes predate the stamps, so they count as earliest of all.- */-function startOf(node: ViewNode): string {- let start = (node.kind === "message" ? node.at : undefined) ?? node.addedAt ?? "";- for (const child of node.children) {- const childStart = startOf(child);- if (childStart < start) start = childStart;+ // Messages the record does not hold yet continue the chain where it stopped.+ for (const message of pending) {+ push(+ {+ id: message.id,+ kind: "message",+ title: message.title,+ at: message.at,+ unsummarized: true,+ },+ previous,+ );}- return start;+ return out;}-/**- * Orders siblings by when their thread began, at every level, so topics read left- * to right and items top to bottom in time order even after the agent renames or- * moves them. The sort is stable: ties keep their stored order.- */-function byStart(nodes: ViewNode[]): ViewNode[] {- for (const node of nodes) node.children = byStart(node.children);- const keyed = nodes.map((node) => ({ node, start: startOf(node) }));- keyed.sort((a, b) => (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));- return keyed.map((entry) => entry.node);+const MESSAGE_NUMBER = /^m([1-9][0-9]*)$/;++function messageNumber(id: string): number {+ const match = MESSAGE_NUMBER.exec(id);+ return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;+}++/** Send time first; the message number keeps records written in one go in order. */+function compareMessages(a: LineageNode, b: LineageNode): number {+ const at = (a.at ?? "").localeCompare(b.at ?? "");+ return at !== 0 ? at : messageNumber(a.id) - messageNumber(b.id);}/** A session counts as active while it was updated within this window. */@@ -151,36 +163,10 @@ export function statusCard(sessions: Session[], now: string): StatusCard {};}-/** Title of the last group of a session: messages the record does not hold yet. */-export const PENDING_GROUP_TITLE = "New";-/**- * The messages the record does not hold yet, as cards under one "New" group at- * the end of the session, so the newest message is on the map before the agent- * summarizes it. The group id never collides with a recorded node's.+ * The messages the record does not hold yet join the end of the chain, so the+ * newest message is on the map before the agent summarizes it (8.2).*/-function pendingGroup(session: Session, pending: ViewPendingMessage[] | undefined): ViewNode[] {- if (!pending?.length) return [];- const used = new Set(session.nodes.map((node) => node.id));- let id = "pending";- for (let n = 2; used.has(id); n += 1) id = `pending-${n}`;- return [- {- id,- kind: "phase",- title: PENDING_GROUP_TITLE,- children: pending.map((message) => ({- id: message.id,- kind: "message" as const,- title: message.title,- at: message.at,- unsummarized: true as const,- children: [],- })),- },- ];-}-function toViewSession(session: Session,transcripts?: ReadonlySet<string>,@@ -196,7 +182,7 @@ function toViewSession(startedAt: session.startedAt,updatedAt: session.updatedAt,status: session.status,- nodes: [...buildNodeTree(session.nodes), ...pendingGroup(session, pending)],+ messages: buildMessages(session.nodes, pending),// 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),diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex f995df5..eceabfd 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -1,4 +1,4 @@-import type { NodeKind } from "../schema/session.js";+import type { BranchSummary, NodeKind } from "../schema/session.js";/*** Serialized contract between `codelineage build` and the HTML template. The@@ -27,6 +27,16 @@ export interface ViewNode {summary?: string;why?: string;at?: string;+ /**+ * The earlier message this one reacts to; `null` for a new root. Always set+ * on the messages the map draws (buildMessages falls back to the previous+ * message when a record points elsewhere).+ */+ parent?: string | null;+ /** Earlier messages this one returns to or builds on besides its parent. */+ links?: string[];+ /** On a branch's first message: what that thread asked and what came of it. */+ branch?: BranchSummary;decidedBy?: "user" | "agent" | "agreed";alternatives?: { option: string; why: string }[];commits?: string[];@@ -43,10 +53,8 @@ export interface ViewNode {addedAt?: string;/** When the node was last added or changed; marks where the work left off. */touchedAt?: string;- /** A user message the record does not hold yet: the card is not summarized. */+ /** A user message the record does not hold yet: the row is not summarized. */unsummarized?: true;- /** Nested children, already ordered as the graph should draw them. */- children: ViewNode[];}export interface ViewPendingItem {@@ -97,7 +105,12 @@ export interface ViewSession {startedAt: string;updatedAt: string;status: ViewStatus;- nodes: ViewNode[];+ /**+ * The session's user messages, flat and in the order they were sent. Older+ * records' topic nodes are not part of the map any more (Epic 8); every+ * message carries the id of the message it hangs from.+ */+ messages: ViewNode[];/** False when the Claude Code transcript is gone, so resume cannot work. */transcriptAvailable: boolean;/** The linked git worktree the session ran in, if any. */diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.tsindex 5a4a2a4..604ecd4 100644--- a/packages/cli/test/build.test.ts+++ b/packages/cli/test/build.test.ts@@ -9,7 +9,7 @@ import { init } from "../src/commands/init.js";import { sessionWrite } from "../src/commands/session.js";import type { LineageNode, Session } from "../src/schema/session.js";import { projectPaths } from "../src/store/paths.js";-import { buildNodeTree, buildViewModel, embedViewModel, statusCard } from "../src/view/lineage.js";+import { buildMessages, buildViewModel, embedViewModel, statusCard } from "../src/view/lineage.js";import { DATA_ELEMENT_ID } from "../src/view/model.js";import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";@@ -49,94 +49,70 @@ function session(over: Partial<Session> & { sessionId: string }): Session {};}-describe("buildNodeTree", () => {- it("carries decision detail into the view and drops empty lists", () => {- const [d] = buildNodeTree([- node("d", "decision", "D", null, {+describe("buildMessages", () => {+ it("carries message detail into the view and drops empty lists", () => {+ const [m] = buildMessages([+ node("m1", "message", "M", null, {decidedBy: "user",alternatives: [{ option: "x", why: "y" }],commits: ["abc1234"],files: [],}),]);- expect(d).toMatchObject({ decidedBy: "user", commits: ["abc1234"] });- expect(d?.alternatives).toHaveLength(1);- expect(d).not.toHaveProperty("files");- });-- it("orders siblings by when their thread began, keeping unstamped ones first and in order", () => {- const t = (h: number) => `2026-10-23T${String(h).padStart(2, "0")}:00:00.000Z`;- const tree = buildNodeTree([- node("late", "phase", "Late topic", null, { addedAt: t(1) }),- node("old", "phase", "Unstamped topic"),- node("early", "phase", "Renamed topic", null, { addedAt: t(9) }),- node("x", "step", "Old item moved in", "early", { addedAt: t(0) }),- node("y", "step", "Second", "late", { addedAt: t(5) }),- node("z", "step", "First", "late", { addedAt: t(2) }),- node("old2", "phase", "Another unstamped"),- ]);- expect(tree.map((n) => n.id)).toEqual(["old", "old2", "early", "late"]);- expect(tree[3]?.children.map((n) => n.id)).toEqual(["z", "y"]);- expect(tree[2]?.addedAt).toBe(t(9));+ expect(m).toMatchObject({ decidedBy: "user", commits: ["abc1234"], parent: null });+ expect(m?.alternatives).toHaveLength(1);+ expect(m).not.toHaveProperty("files");});it("orders messages by when the user sent them and carries the agent's work", () => {const t = (h: number) => `2026-10-23T${String(h).padStart(2, "0")}:00:00.000Z`;- const [topic] = buildNodeTree([- node("topic", "phase", "Topic", null, { addedAt: t(1) }),- // Written in one go, so the add time cannot tell their order.- node("m2", "message", "Second", "topic", { at: t(3), addedAt: t(5) }),- node("m1", "message", "First", "topic", {+ // Written in one go, so the add time cannot tell their order.+ const messages = buildMessages([+ node("m2", "message", "Second", "m1", { at: t(3), addedAt: t(5) }),+ node("m1", "message", "First", null, {at: t(2),addedAt: t(5),work: ["did a thing"],agentDecisions: [{ title: "Chose x", why: "simpler" }],}),]);- expect(topic?.children.map((n) => n.id)).toEqual(["m1", "m2"]);- expect(topic?.children[0]).toMatchObject({+ expect(messages.map((m) => m.id)).toEqual(["m1", "m2"]);+ expect(messages[0]).toMatchObject({+ parent: null,work: ["did a thing"],agentDecisions: [{ title: "Chose x", why: "simpler" }],});- expect(topic?.children[1]).not.toHaveProperty("work");+ expect(messages[1]).toMatchObject({ parent: "m1" });+ expect(messages[1]).not.toHaveProperty("work");});- it("nests children in order and keeps optional fields only when present", () => {- const tree = buildNodeTree([- node("a", "phase", "A", null, { summary: "phase one", at: T0 }),- node("b", "step", "B", "a"),- node("c", "decision", "C", "b", { why: "because" }),- node("d", "question", "D", "a"),+ it("chains an old record whose parents point at topics, and drops forward parents", () => {+ const t = (h: number) => `2026-10-23T${String(h).padStart(2, "0")}:00:00.000Z`;+ const old = buildMessages([+ node("m1", "message", "One", "topic", { at: t(1) }),+ node("m2", "message", "Two", "topic", { at: t(2) }),+ node("m3", "message", "Three", "m2", { at: t(3) }),]);- expect(tree).toEqual([- {- id: "a",- kind: "phase",- title: "A",- summary: "phase one",- at: T0,- children: [- {- id: "b",- kind: "step",- title: "B",- children: [{ id: "c", kind: "decision", title: "C", why: "because", children: [] }],- },- { id: "d", kind: "question", title: "D", children: [] },- ],- },+ expect(old.map((m) => m.parent)).toEqual([null, "m1", "m2"]);++ const forward = buildMessages([+ node("m1", "message", "One", "m2", { at: t(1) }),+ node("m2", "message", "Two", null, { at: t(2) }),]);+ expect(forward.map((m) => m.parent)).toEqual([null, null]);});- it("re-roots missing parents, self references and cycles without losing nodes", () => {- const tree = buildNodeTree([- node("a", "phase", "A", "ghost"),- node("b", "step", "B", "b"),- node("x", "decision", "X", "y"),- node("y", "step", "Y", "x"),+ it("keeps only links to earlier messages and a branch summary where it belongs", () => {+ const t = (h: number) => `2026-10-23T${String(h).padStart(2, "0")}:00:00.000Z`;+ const branch = { title: "Thread", asked: "What?", outcome: "This.", open: "" };+ const messages = buildMessages([+ node("m1", "message", "One", null, { at: t(1), branch }),+ node("m2", "message", "Two", "m1", { at: t(2), links: ["m1", "m3"] }),+ node("m3", "message", "Three", "m2", { at: t(3) }),]);- expect(tree.map((n) => n.id)).toEqual(["a", "b", "x"]);- expect(tree[2]).toMatchObject({ id: "x", children: [{ id: "y", children: [] }] });+ expect(messages[0]?.branch).toEqual(branch);+ expect(messages[1]?.links).toEqual(["m1"]);+ expect(messages[2]).not.toHaveProperty("branch");});});@@ -202,11 +178,18 @@ describe("buildViewModel", () => {expect(model.project).toEqual({ name: "p", path: "/tmp/p", generatedAt: T0 });});- it("puts unrecorded messages in one New group at the end, with a free id", () => {+ it("appends unrecorded messages to the end of the chain", () => {const model = buildViewModel({project: { schema: 1, name: "p", epochs: [] },sessions: [- session({ sessionId: "s", nodes: [node("pending", "phase", "A recorded topic")] }),+ session({+ sessionId: "s",+ nodes: [+ node("m1", "message", "Recorded message", null, {+ at: "2026-10-21T10:00:00.000Z",+ }),+ ],+ }),],path: "/tmp/p",generatedAt: T0,@@ -220,31 +203,20 @@ describe("buildViewModel", () => {],]),});- const nodes = model.unassigned[0]?.nodes ?? [];- expect(nodes.map((n) => n.title)).toEqual(["A recorded topic", "New"]);- // The recorded node already owns the id "pending".- expect(nodes[1]).toEqual({- id: "pending-2",- kind: "phase",- title: "New",- children: [- {- id: "m2",- kind: "message",- title: "Second message",- at: "2026-10-21T10:02:00.000Z",- unsummarized: true,- children: [],- },- {- id: "m3",- kind: "message",- title: "Third message",- at: "2026-10-21T10:03:00.000Z",- unsummarized: true,- children: [],- },- ],+ const messages = model.unassigned[0]?.messages ?? [];+ expect(messages.map((message) => message.title)).toEqual([+ "Recorded message",+ "Second message",+ "Third message",+ ]);+ expect(messages.map((message) => message.parent)).toEqual([null, "m1", "m2"]);+ expect(messages[2]).toEqual({+ id: "m3",+ kind: "message",+ title: "Third message",+ at: "2026-10-21T10:03:00.000Z",+ unsummarized: true,+ parent: "m2",});});@@ -418,8 +390,8 @@ describe("codelineage build", () => {epoch: "e1",startedAt: "2026-01-02T00:00:00.000Z",nodes: [- node("a", "phase", "A"),- node("b", "step", "B", "a", {+ node("m1", "message", "A", null, {+ at: "2026-01-02T01:00:00.000Z",summary: "token ghp_abcdefghijklmnopqrstuvwxyz0123456789",}),],@@ -479,7 +451,7 @@ describe("codelineage build", () => {expect(model.epochs[0]?.sessions.map((s) => s.sessionId)).toEqual(["s2", "s1", "newer"]);expect(model.unassigned.map((s) => s.sessionId)).toEqual(["s4", "s3"]);- expect(model.epochs[0]?.sessions[1]?.nodes[0]?.children[0]?.summary).toBe("token [REDACTED]");+ expect(model.epochs[0]?.sessions[1]?.messages[0]?.summary).toBe("token [REDACTED]");expect(model.status.goal).toBe("latest");const html = await readFile(paths().html, "utf8");@@ -530,10 +502,11 @@ describe("codelineage build", () => {// s2 records no message, so its unrecorded turn is shown as a pending card// and needs the same conversation for its drill-down.expect(s2?.chat).toEqual([turn]);- expect(s2?.nodes.at(-1)).toMatchObject({- kind: "phase",- title: "New",- children: [{ id: "m1", kind: "message", title: "Fix the card", unsummarized: true }],+ expect(s2?.messages.at(-1)).toMatchObject({+ id: "m1",+ kind: "message",+ title: "Fix the card",+ unsummarized: true,});expect(await readFile(paths().session("s1"), "utf8")).not.toContain("Fix the card");});@@ -565,18 +538,18 @@ describe("codelineage build", () => {);const before = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });- const nodes = before.epochs[0]?.sessions[0]?.nodes ?? [];- expect(nodes.map((n) => n.title)).toEqual(["Topic", "New"]);- expect(nodes[1]).toMatchObject({- children: [- {- id: "m2",- kind: "message",- title: "Second message, with the card",- at: "2026-10-21T10:05:00.000Z",- unsummarized: true,- },- ],+ const messages = before.epochs[0]?.sessions[0]?.messages ?? [];+ expect(messages.map((message) => message.title)).toEqual([+ "First",+ "Second message, with the card",+ ]);+ expect(messages[1]).toMatchObject({+ id: "m2",+ kind: "message",+ title: "Second message, with the card",+ at: "2026-10-21T10:05:00.000Z",+ unsummarized: true,+ parent: "m1",});await sessionWrite({ dir: root }, io, async () =>@@ -591,7 +564,10 @@ describe("codelineage build", () => {expect.stringMatching(/m2: parent topic is not an earlier message of this session, using m1/),]);const after = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });- expect(after.epochs[0]?.sessions[0]?.nodes.map((n) => n.title)).toEqual(["Topic"]);+ expect(after.epochs[0]?.sessions[0]?.messages.map((message) => message.title)).toEqual([+ "First",+ "Second message",+ ]);});it("counts unrecorded messages only while the catch-up is off", async () => {diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsxnew file mode 100644index 0000000..5e264ed--- /dev/null+++ b/packages/template/src/GitGraph.tsx@@ -0,0 +1,218 @@+import { type MouseEvent, type ReactElement, useMemo } from "react";+import { formatStamp } from "./format.js";+import {+ branchPath,+ type GitLayout,+ type GitMessageRow,+ type GitRow,+ LANE_COLORS,+ linkArrow,+ linkPath,+ ROW_HEIGHT,+} from "./gitLayout.js";++/**+ * Draws one session's messages as a git graph (Story 8.2): time-ordered rows on+ * the right, dots, lanes, branch starts and returns on the left. The geometry+ * comes from `gitLayout.ts`; this file only renders it.+ */++function color(index: number): string {+ return `var(--l${index % LANE_COLORS})`;+}++function rowRange(row: GitRow): string {+ if (row.kind === "more") return "";+ return row.message.at ? formatStamp(row.message.at) : "";+}++function returnMark(row: GitMessageRow): ReactElement | null {+ if (row.returns.length === 0) return null;+ return (+ <span className="git-returns">+ {row.returns.map((back) => (+ <span key={back.id} className="git-return" style={{ color: color(back.colorIndex) }}>+ ↩ {back.id}+ </span>+ ))}+ </span>+ );+}++function Row({+ row,+ branchTitle,+ selected,+ branchSelected,+ onSelect,+ onUnfold,+}: {+ row: GitRow;+ branchTitle: string;+ selected: boolean;+ branchSelected: boolean;+ onSelect: (row: GitMessageRow) => void;+ onUnfold: (segmentId: string) => void;+}) {+ const style = {+ top: row.y - ROW_HEIGHT / 2,+ height: ROW_HEIGHT,+ borderColor: branchSelected ? color(row.colorIndex) : undefined,+ };++ if (row.kind === "more") {+ return (+ <button+ type="button"+ className="git-row git-more"+ style={style}+ onClick={(event) => {+ event.stopPropagation();+ onUnfold(row.segmentId);+ }}+ title="Show the folded messages of this branch"+ >+ <span className="git-branch" style={{ background: color(row.colorIndex) }}>+ {branchTitle}+ </span>+ <span className="git-title">⋮ {row.hidden.length} more — open</span>+ </button>+ );+ }++ const message = row.message;+ return (+ <button+ type="button"+ className={`git-row${selected ? " is-selected" : ""}${branchSelected ? " in-branch" : ""}`}+ style={style}+ data-message={message.id}+ onClick={(event: MouseEvent) => {+ event.stopPropagation();+ onSelect(row);+ }}+ title={message.summary || message.title}+ >+ <span className="git-time">{rowRange(row)}</span>+ {row.first ? (+ <span className="git-branch" style={{ background: color(row.colorIndex) }}>+ {branchTitle}+ </span>+ ) : null}+ <span className="git-id">{message.id}</span>+ <span className="git-title">{message.title}</span>+ {returnMark(row)}+ {row.head ? <span className="left-off">left off here</span> : null}+ {message.unsummarized ? <span className="unsummarized">not summarized yet</span> : null}+ </button>+ );+}++export function GitGraph({+ git,+ selectedId,+ activeSegmentId,+ onSelect,+ onUnfold,+}: {+ git: GitLayout;+ /** Message id of the open drill-down, if it belongs to this session. */+ selectedId: string | null;+ /** Branch the drill-down belongs to. */+ activeSegmentId: string | null;+ onSelect: (row: GitMessageRow) => void;+ onUnfold: (segmentId: string) => void;+}) {+ const branches = useMemo(+ () => new Map(git.segments.map((segment) => [segment.id, segment])),+ [git.segments],+ );+ const segmentOf = useMemo(() => {+ const map = new Map<string, string>();+ for (const segment of git.segments) for (const id of segment.ids) map.set(id, segment.id);+ return map;+ }, [git.segments]);++ return (+ <div className="git-graph" style={{ width: git.width, height: git.height }}>+ <svg+ className="git-lanes"+ width={git.graphWidth}+ height={git.height}+ aria-hidden="true"+ focusable="false"+ >+ {git.segments.map((segment) => {+ const start = branchPath(segment, git.laneX);+ const rows = git.rows.filter((row) => row.segmentId === segment.id);+ const x = git.laneX[segment.lane] ?? 0;+ return (+ <g key={segment.id} stroke={color(segment.colorIndex)} fill="none">+ {start ? <path d={start} strokeWidth={2.5} /> : null}+ {rows.slice(1).map((row, at) => {+ const previous = rows[at] as GitRow | undefined;+ if (!previous) return null;+ const folded = previous.kind === "more" || row.kind === "more";+ return (+ <path+ key={`${row.segmentId}-${at}`}+ d={`M${x},${previous.y} L${x},${row.y}`}+ strokeWidth={folded ? 6 : 2.5}+ opacity={folded ? 0.3 : 1}+ />+ );+ })}+ </g>+ );+ })}+ {git.links.map((link) => {+ const target = segmentOf.get(link.toId);+ const from = segmentOf.get(link.fromId);+ const targetX = git.laneX[branches.get(target ?? "")?.lane ?? 0] ?? 0;+ const fromX = git.laneX[branches.get(from ?? "")?.lane ?? 0] ?? 0;+ return (+ <g key={`${link.fromId}-${link.toId}`} fill="none" stroke={color(link.colorIndex)}>+ <path d={linkPath(link, targetX, fromX)} strokeWidth={1.8} strokeDasharray="5 3" />+ <path d={linkArrow(link, fromX)} strokeWidth={1.8} />+ </g>+ );+ })}+ {git.rows.map((row) => {+ if (row.kind !== "message") return null;+ const x = git.laneX[branches.get(row.segmentId)?.lane ?? 0] ?? 0;+ return row.first ? (+ <circle+ key={row.message.id}+ cx={x}+ cy={row.y}+ r={6}+ fill="var(--bg)"+ stroke={color(row.colorIndex)}+ strokeWidth={3}+ />+ ) : (+ <circle key={row.message.id} cx={x} cy={row.y} r={4.5} fill={color(row.colorIndex)} />+ );+ })}+ </svg>+ <div className="git-rows" style={{ left: git.graphWidth + 8 }}>+ {git.rows.map((row) => {+ const branch = branches.get(row.segmentId);+ return (+ <Row+ key={row.kind === "more" ? `${row.segmentId}-more` : row.message.id}+ row={row}+ branchTitle={branch?.branch.title ?? ""}+ selected={+ row.kind === "message" && selectedId !== null && row.message.id === selectedId+ }+ branchSelected={activeSegmentId !== null && row.segmentId === activeSegmentId}+ onSelect={onSelect}+ onUnfold={onUnfold}+ />+ );+ })}+ </div>+ </div>+ );+}diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsxindex 8486d13..e299c52 100644--- a/packages/template/src/Graph.tsx+++ b/packages/template/src/Graph.tsx@@ -23,25 +23,38 @@ import {useState,} from "react";import type { LineageViewModel } from "../../cli/src/view/model.js";-import { cardMeta, cardText, formatDate, formatTime, itemsInside, kindLabel } from "./format.js";+import { formatDate, formatTime } from "./format.js";import { useFullscreen } from "./fullscreen.js";+import { GitGraph } from "./GitGraph.js";+import type { GitMessageRow } from "./gitLayout.js";import {absolutePosition,defaultExpanded,type EpochFlowNode,+ GROUP_INSET,type GraphNode,- type LineageFlowNode,- lastTouched,+ headOf,layoutGraph,+ nodeId,+ SESSION_GROUP_HEADER,type SessionFlowNode,- TREE_LEFT,- TREE_OUT,+ sessionId as sessionKey,} from "./graph.js";import { Outline, type OutlineTarget, outlinePath } from "./Outline.js";import { DrillDown, type Selection } from "./SidePanel.js";-/** Toggle callback reaches the group headers without threading props through React Flow. */-const GraphActions = createContext<{ toggle: (id: string) => void }>({ toggle: () => {} });+/** Row clicks and group toggles reach the shared state without prop threading. */+const GraphActions = createContext<{+ toggle: (id: string) => void;+ openRow: (sessionId: string, messageId: string, segmentId: string) => void;+ unfold: (segmentId: string) => void;+ selection: Selection | null;+}>({+ toggle: () => {},+ openRow: () => {},+ unfold: () => {},+ selection: null,+});function GroupToggle({id,@@ -68,28 +81,6 @@ function GroupToggle({);}-/** Spine handles for the outline inside a topic column (see placeSessionNodes). */-function TreeHandles() {- return (- <>- <Handle- id={TREE_LEFT}- type="target"- position={Position.Left}- className="flow-handle"- isConnectable={false}- />- <Handle- id={TREE_OUT}- type="source"- position={Position.Bottom}- className="flow-handle tree-handle"- isConnectable={false}- />- </>- );-}-/** Edges need handles; they are invisible because the layout owns the geometry. */function AnchorHandles() {return (@@ -121,6 +112,13 @@ function EpochNode({ id, data }: NodeProps<EpochFlowNode>) {}function SessionNode({ id, data }: NodeProps<SessionFlowNode>) {+ const { selection, openRow, unfold } = useContext(GraphActions);+ const selectedId =+ selection?.type === "node" && selection.sessionId === data.sessionId ? selection.nodeId : null;+ const activeSegmentId =+ selection?.type === "node" && selection.sessionId === data.sessionId+ ? (selection.branchId ?? null)+ : null;return (<div className="flow-group session-group" title={data.goal || data.title}><AnchorHandles />@@ -128,33 +126,24 @@ function SessionNode({ id, data }: NodeProps<SessionFlowNode>) {<GroupToggle id={id} data={data} /><strong className="group-title">{data.title}</strong><span className="muted">{data.count}</span>+ {data.unrecorded ? (+ <span className="muted unrecorded" title="The SessionEnd catch-up is off">+ {data.unrecorded} not recorded+ </span>+ ) : null}<time className="muted" dateTime={data.updatedAt} title={formatTime(data.updatedAt)}>{formatDate(data.updatedAt)}</time></div>- </div>- );-}--function LineageBox({ id, data }: NodeProps<LineageFlowNode>) {- return (- <div className={`lineage-box kind-${data.kind}${data.isLast ? " is-last" : ""}`}>- <TreeHandles />- <div className="lineage-head">- {data.hasChildren ? <GroupToggle id={id} data={data} /> : null}- <span className={`kind kind-${data.kind}`}>{kindLabel(data.kind)}</span>- <strong title={data.title}>{data.title}</strong>- </div>- {data.isLast ? <span className="left-off">left off here</span> : null}- {data.unsummarized ? <span className="unsummarized">not summarized yet</span> : null}- {data.hasChildren && !data.expanded ? (- <p className="lineage-count">{itemsInside(data.count)}</p>- ) : data.at && data.kind !== "message" ? (- <time dateTime={data.at}>{formatTime(data.at)}</time>- ) : cardText(data) ? (- <p>{cardText(data)}</p>+ {data.git ? (+ <GitGraph+ git={data.git}+ selectedId={selectedId}+ activeSegmentId={activeSegmentId}+ onSelect={(row: GitMessageRow) => openRow(data.sessionId, row.message.id, row.segmentId)}+ onUnfold={unfold}+ />) : null}- {cardMeta(data) ? <p className="card-meta">{cardMeta(data)}</p> : null}</div>);}@@ -162,31 +151,25 @@ function LineageBox({ id, data }: NodeProps<LineageFlowNode>) {const nodeTypes: NodeTypes = {epoch: EpochNode,session: SessionNode,- lineage: LineageBox,};/** React Flow overlays get their colours from the node type, not the kind. */function minimapColor(node: GraphNode): string {- if (node.type === "epoch") return "#2b3446";- if (node.type === "session") return "#243040";- const kind = node.data.kind;- if (kind === "decision") return "#4b3a72";- if (kind === "question") return "#5a4526";- if (kind === "message") return "#1f3a4a";- return "#1f2a3d";+ return node.type === "epoch" ? "#2b3446" : "#243040";}function Flow({ model }: { model: LineageViewModel }) {const [expanded, setExpanded] = useState<Set<string>>(() => defaultExpanded(model));const [selection, setSelection] = useState<Selection | null>(null);+ const [unfolded, setUnfolded] = useState<Set<string>>(() => new Set());+ const [openAll, setOpenAll] = useState(false);const [layout, setLayout] = useState<Awaited<ReturnType<typeof layoutGraph>> | null>(null);const [error, setError] = useState<string | null>(null);const [showOutline, setShowOutline] = useState(false);const { expanded: fullscreen, toggle: toggleFullscreen } = useFullscreen();const [focusedId, setFocusedId] = useState<string | null>(null);- /** Wait for the layout that contains this node, then centre on it. */// Open on the session where the work left off, framed around it.- const pendingFocus = useRef<string | null>(lastTouched(model)?.sessionKey ?? null);+ const pendingFocus = useRef<string | null>(headOf(model)?.sessionKey ?? null);const focusTimer = useRef<number | null>(null);/** Outline selection just re-fitted the view; don't let the generic fit undo it. */const lastFocusRequest = useRef(@@ -218,10 +201,74 @@ function Flow({ model }: { model: LineageViewModel }) {[],);+ /** A message row picked in the outline, to centre once its layout lands. */+ const pendingRow = useRef<{ sessionKey: string; messageId: string } | null>(null);++ /**+ * Centres one message row of a laid-out session at a readable zoom (0.9).+ * Fitting the whole session would shrink a long history to illegible text.+ */+ const centerRow = useCallback(+ (+ result: Awaited<ReturnType<typeof layoutGraph>>,+ sessionKeyValue: string,+ messageId: string,+ delay = 0,+ ): boolean => {+ const node = result.nodes.find((candidate) => candidate.id === sessionKeyValue);+ if (node?.type !== "session" || !node.data.git) return false;+ const { git } = node.data;+ const row = git.rows.find(+ (candidate) => candidate.kind === "message" && candidate.message.id === messageId,+ );+ const at = absolutePosition(result.nodes, sessionKeyValue);+ if (!row || !at) return false;+ const zoom = 0.9;+ const apply = (): void => {+ const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();+ if (!canvas) return;+ void setViewport({+ zoom,+ x: canvas.width / 2 - (at.x + GROUP_INSET + git.graphWidth / 2) * zoom,+ y: canvas.height / 2 - (at.y + SESSION_GROUP_HEADER + row.y) * zoom,+ });+ };+ if (delay > 0) {+ // After React Flow has mounted its canvas and run its own initial fit,+ // or either would overwrite this.+ if (focusTimer.current !== null) window.clearTimeout(focusTimer.current);+ focusTimer.current = window.setTimeout(() => {+ focusTimer.current = null;+ apply();+ }, delay);+ } else {+ apply();+ }+ return true;+ },+ [setViewport],+ );++ /** Opening the map frames the newest message, so HEAD is readable at once. */+ const focusInitial = useCallback(+ (result: Awaited<ReturnType<typeof layoutGraph>>, id: string) => {+ const head = headOf(model);+ if (+ head?.messageId &&+ id === head.sessionKey &&+ centerRow(result, head.sessionKey, head.messageId, 120)+ ) {+ return;+ }+ scheduleFocus(id);+ },+ [centerRow, model, scheduleFocus],+ );+useEffect(() => {let cancelled = false;setError(null);- layoutGraph(model, expanded)+ layoutGraph(model, expanded, { unfolded, openAll }).then((result) => {if (cancelled) return;setLayout(result);@@ -239,10 +286,19 @@ function Flow({ model }: { model: LineageViewModel }) {}// Survives into the single-file build so a 500-node run can be measured.document.documentElement.dataset.layoutMs = result.layoutMs.toFixed(1);+ const row = pendingRow.current;+ if (row && result.nodes.some((node) => node.id === row.sessionKey)) {+ pendingRow.current = null;+ pendingFocus.current = null;+ if (!centerRow(result, row.sessionKey, row.messageId)) {+ focusInitial(result, row.sessionKey);+ }+ return;+ }const focus = pendingFocus.current;if (focus && result.nodes.some((node) => node.id === focus)) {pendingFocus.current = null;- scheduleFocus(focus);+ focusInitial(result, focus);}}).catch((err: unknown) => {@@ -252,7 +308,7 @@ function Flow({ model }: { model: LineageViewModel }) {return () => {cancelled = true;};- }, [model, expanded, scheduleFocus, getViewport, setViewport]);+ }, [model, expanded, unfolded, openAll, centerRow, focusInitial, getViewport, setViewport]);useEffect(() => {if (!layout || framed.current) return;@@ -289,28 +345,51 @@ function Flow({ model }: { model: LineageViewModel }) {},[layout],);- const actions = useMemo(() => ({ toggle }), [toggle]);+ const openRow = useCallback((sessionIdValue: string, messageId: string, segmentId: string) => {+ setFocusedId(nodeId(sessionKey(sessionIdValue), messageId));+ setSelection({+ type: "node",+ sessionId: sessionIdValue,+ nodeId: messageId,+ branchId: segmentId,+ });+ }, []);+ const unfold = useCallback((segmentId: string) => {+ setUnfolded((previous) => {+ const next = new Set(previous);+ next.add(segmentId);+ return next;+ });+ }, []);+ const toggleUnfoldAll = useCallback(() => {+ setOpenAll((value) => !value);+ setUnfolded(new Set());+ }, []);+ const actions = useMemo(+ () => ({ toggle, openRow, unfold, selection }),+ [toggle, openRow, unfold, selection],+ );const closePanel = useCallback(() => setSelection(null), []);const toggleOutline = useCallback(() => setShowOutline((value) => !value), []);const onNodeClick = useCallback<NodeMouseHandler<GraphNode>>((_event, node) => {setFocusedId(node.id);- if (node.type === "lineage") {- setSelection({ type: "node", node: node.data });- } else if (node.type === "session") {+ if (node.type === "session") {setSelection({ type: "session", sessionId: node.data.sessionId });}}, []);/**- * Selecting in the outline must reveal the target's group chain in the graph+ * Selecting in the outline must reveal the target's group chain in the map* first: a collapsed group has no flow node at all, so its child cannot be* focused until the next layout lands.*/const selectFromOutline = useCallback((target: OutlineTarget) => {- // Open every layer above the target, including topics it is nested in.const reveal = [...target.expand, ...(outlinePath(model, target.focusId) ?? []).slice(0, -1)];const needsLayout = reveal.some((id) => !expanded.has(id));+ // A message row belongs to its session's group, which is what gets framed.+ const focusId =+ target.selection?.type === "node" ? sessionKey(target.selection.sessionId) : target.focusId;setExpanded((previous) => {const next = new Set(previous);for (const id of reveal) next.add(id);@@ -319,14 +398,27 @@ function Flow({ model }: { model: LineageViewModel }) {setSelection(target.selection);setFocusedId(target.focusId);lastFocusRequest.current = performance.now();+ const rowTarget =+ target.selection?.type === "node"+ ? {+ sessionKey: sessionKey(target.selection.sessionId),+ messageId: target.selection.nodeId,+ }+ : null;if (needsLayout) {- pendingFocus.current = target.focusId;+ pendingFocus.current = rowTarget ? null : focusId;+ pendingRow.current = rowTarget;} else {pendingFocus.current = null;- scheduleFocus(target.focusId);+ pendingRow.current = null;+ const centered =+ rowTarget !== null &&+ layout !== null &&+ centerRow(layout, rowTarget.sessionKey, rowTarget.messageId);+ if (!centered) scheduleFocus(focusId);}},- [expanded, model, scheduleFocus],+ [centerRow, expanded, layout, model, scheduleFocus],);let content: ReactNode;@@ -372,6 +464,14 @@ function Flow({ model }: { model: LineageViewModel }) {>{fullscreen ? "Exit full screen" : "Full screen"}</button>+ <button+ type="button"+ className="outline-button"+ aria-pressed={openAll}+ onClick={toggleUnfoldAll}+ >+ {openAll ? "Fold all" : "Unfold all"}+ </button><buttontype="button"className="outline-button"@@ -405,7 +505,7 @@ function Flow({ model }: { model: LineageViewModel }) {);}-/** Nested epoch → session → node map; layout runs in the page from embedded data. */+/** Epoch → session map; each session draws its messages as a git graph. */export function Graph({ model }: { model: LineageViewModel }) {return (<section className="lineage-map" aria-label="Project lineage graph">diff --git a/packages/template/src/Outline.tsx b/packages/template/src/Outline.tsxindex 72e9ce5..7707d51 100644--- a/packages/template/src/Outline.tsx+++ b/packages/template/src/Outline.tsx@@ -1,21 +1,13 @@import { useEffect, useMemo, useState } from "react";-import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";+import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";import { kindLabel } from "./format.js";-import {- countNodes,- epochId,- nodeId,- sessionId,- toNodeDetail,- UNASSIGNED_EPOCH_ID,-} from "./graph.js";+import { epochId, nodeId, sessionId, UNASSIGNED_EPOCH_ID } from "./graph.js";import type { Selection } from "./SidePanel.js";/**- * Experimental outline tree (epoch → session → nodes) that sits next to the- * graph. Selecting a row expands the graph groups the row lives in, centres the- * matching React Flow node and opens the same drill-down panel a click would.- * Epochs have no panel of their own: focusing the group is their detail view.+ * Experimental outline tree (epoch → session → messages) that sits next to the+ * map. Selecting a row opens its epoch and session, centres the session's git+ * graph and opens the same drill-down panel a row click would.*/export interface OutlineTarget {@@ -45,21 +37,10 @@ function groups(model: LineageViewModel): Group[] {return result;}-/** Ids from the first matching node down to the target, or `null`. */-function findNodePath(nodes: ViewNode[], group: string, targetId: string): string[] | null {- for (const node of nodes) {- const id = nodeId(group, node.id);- if (id === targetId) return [id];- const childPath = findNodePath(node.children, group, targetId);- if (childPath) return [id, ...childPath];- }- return null;-}-/*** Ancestor chain of an outline item, including the item itself: the epoch for a- * session, the epoch, session and node ancestors for a node. `null` when the id- * does not belong to this model.+ * session, the epoch and session for a message. `null` when the id does not+ * belong to this model.*/export function outlinePath(model: LineageViewModel, targetId: string): string[] | null {for (const group of groups(model)) {@@ -67,8 +48,9 @@ export function outlinePath(model: LineageViewModel, targetId: string): string[]for (const session of group.sessions) {const key = sessionId(session.sessionId);if (key === targetId) return [group.id];- const nodePath = findNodePath(session.nodes, key, targetId);- if (nodePath) return [group.id, key, ...nodePath];+ if (session.messages.some((message) => nodeId(key, message.id) === targetId)) {+ return [group.id, key];+ }}}return null;@@ -99,79 +81,6 @@ function ExpandToggle({);}-function NodeRows({- nodes,- epoch,- sessionKey,- rawSessionId,- activeId,- expanded,- onToggle,- onSelect,-}: {- nodes: ViewNode[];- epoch: string;- sessionKey: string;- rawSessionId: string;- activeId: string | null;- expanded: ReadonlySet<string>;- onToggle: (id: string) => void;- onSelect: (target: OutlineTarget) => void;-}) {- return (- <>- {nodes.map((node) => {- const id = nodeId(sessionKey, node.id);- const hasChildren = node.children.length > 0;- const open = hasChildren && expanded.has(id);- return (- <li key={id}>- <div className="outline-row">- <ExpandToggle- id={id}- hasChildren={hasChildren}- expanded={expanded.has(id)}- onToggle={onToggle}- />- <button- type="button"- className={`outline-item${activeId === id ? " is-active" : ""}`}- onClick={() =>- onSelect({- focusId: id,- expand: [epoch, sessionKey],- selection: {- type: "node",- node: toNodeDetail(node, rawSessionId),- },- })- }- >- <span className={`kind kind-${node.kind}`}>{kindLabel(node.kind)}</span>- <span className="label">{node.title}</span>- </button>- </div>- {open ? (- <ul>- <NodeRows- nodes={node.children}- epoch={epoch}- sessionKey={sessionKey}- rawSessionId={rawSessionId}- activeId={activeId}- expanded={expanded}- onToggle={onToggle}- onSelect={onSelect}- />- </ul>- ) : null}- </li>- );- })}- </>- );-}-function SessionRow({group,session,@@ -188,7 +97,7 @@ function SessionRow({onSelect: (target: OutlineTarget) => void;}) {const key = sessionId(session.sessionId);- const hasChildren = session.nodes.length > 0;+ const hasChildren = session.messages.length > 0;const open = hasChildren && expanded.has(key);return (<li>@@ -205,27 +114,45 @@ function SessionRow({onClick={() =>onSelect({focusId: key,- expand: [group],+ expand: [group, key],selection: { type: "session", sessionId: session.sessionId },})}><span className="label">{session.title || session.sessionId}</span>- <span className="outline-count">{countNodes(session.nodes)}</span>+ <span className="outline-count">{session.messages.length}</span></button></div>{open ? (<ul>- <NodeRows- nodes={session.nodes}- epoch={group}- sessionKey={key}- rawSessionId={session.sessionId}- activeId={activeId}- expanded={expanded}- onToggle={onToggle}- onSelect={onSelect}- />+ {session.messages.map((message) => {+ const id = nodeId(key, message.id);+ return (+ <li key={id}>+ <div className="outline-row">+ <span className="outline-toggle is-empty" aria-hidden="true" />+ <button+ type="button"+ className={`outline-item${activeId === id ? " is-active" : ""}`}+ onClick={() =>+ onSelect({+ focusId: id,+ expand: [group, key],+ selection: {+ type: "node",+ sessionId: session.sessionId,+ nodeId: message.id,+ },+ })+ }+ >+ <span className={`kind kind-${message.kind}`}>{kindLabel(message.kind)}</span>+ <span className="label">{message.title}</span>+ </button>+ </div>+ </li>+ );+ })}</ul>) : null}</li>@@ -244,13 +171,13 @@ export function Outline({onClose: () => void;}) {const allGroups = useMemo(() => groups(model), [model]);- // Epochs start open so the tree lists every session; sessions and nodes close- // their own children until asked, mirroring the graph's collapsed default.+ // Epochs start open so the tree lists every session; sessions close their+ // messages until asked, mirroring the map's collapsed default.const [expanded, setExpanded] = useState<Set<string>>(() => new Set(allGroups.map((group) => group.id)),);- // Graph clicks drive the highlight too; reveal the row when it is nested.+ // Map clicks drive the highlight too; reveal the row when it is nested.useEffect(() => {if (!activeId) return;const path = outlinePath(model, activeId);diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex 3ba6ef9..e13af3e 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -1,18 +1,30 @@import { type ReactNode, useEffect, useRef, useState } from "react";-import type { LineageViewModel, ViewChatTurn, ViewSession } from "../../cli/src/view/model.js";+import type {+ LineageViewModel,+ ViewChatTurn,+ ViewNode,+ ViewSession,+} from "../../cli/src/view/model.js";import { resumeCommand } from "../../cli/src/view/resume.js";import { formatTime, kindLabel } from "./format.js";+import { layoutGitGraph } from "./gitLayout.js";import {messageNeighbors,type NodeDetail,- nodeId,+ sessionGroupId,sessionId as sessionKey,toNodeDetail,} from "./graph.js";import type { OutlineTarget } from "./Outline.js";-/** What the drill-down shows: a graph node or a whole session. */-export type Selection = { type: "node"; node: NodeDetail } | { type: "session"; sessionId: string };+/**+ * What the drill-down shows: a message (with the branch it belongs to) or a+ * whole session. Ids, not copies, so a live rebuild does not leave the panel+ * showing stale text.+ */+export type Selection =+ | { type: "node"; sessionId: string; nodeId: string; branchId?: string | undefined }+ | { type: "session"; sessionId: string };function findSession(model: LineageViewModel, sessionId: string): ViewSession | undefined {for (const epoch of model.epochs) {@@ -23,6 +35,10 @@ function findSession(model: LineageViewModel, sessionId: string): ViewSession |return model.unassigned.find((session) => session.sessionId === sessionId);}+function findMessage(session: ViewSession, id: string): ViewNode | undefined {+ return session.messages.find((message) => message.id === id);+}+/*** `navigator.clipboard` is unavailable or rejected in some `file://` contexts,* so fall back to the hidden-textarea + `execCommand("copy")` path.@@ -233,25 +249,85 @@ function Conversation({ session, id }: { session: ViewSession | undefined; id: s);}+/** The branch a message belongs to, so the panel survives prev/next navigation. */+function branchOf(session: ViewSession, messageId: string): string | undefined {+ return layoutGitGraph(session.messages).segments.find((segment) =>+ segment.ids.includes(messageId),+ )?.id;+}++/** The branch summary a clicked row opens the panel with (Story 8.2). */+function BranchDetails({+ session,+ branchId,+}: {+ session: ViewSession;+ branchId?: string | undefined;+}) {+ if (!branchId) return null;+ const segment = layoutGitGraph(session.messages).segments.find(+ (candidate) => candidate.id === branchId,+ );+ if (!segment) return null;+ const { branch } = segment;+ const span =+ branch.firstAt && branch.lastAt && branch.firstAt !== branch.lastAt+ ? ` · ${formatTime(branch.firstAt)} → ${formatTime(branch.lastAt)}`+ : "";+ return (+ <section className="branch-detail">+ <h3 style={{ color: `var(--l${segment.colorIndex})` }}>{branch.title}</h3>+ <p className="branch-range">+ {branch.count > 1 ? `${branch.fromId}–${branch.toId}` : branch.fromId} · {branch.count}{" "}+ message{branch.count === 1 ? "" : "s"}+ {span}+ </p>+ {branch.asked ? (+ <p>+ <b>Asked:</b> {branch.asked}+ </p>+ ) : null}+ {branch.outcome ? (+ <p>+ <b>Outcome:</b> {branch.outcome}+ </p>+ ) : null}+ {branch.open ? (+ <p>+ <b>Open:</b> {branch.open}+ </p>+ ) : null}+ </section>+ );+}+/** Previous and next message of the session, so the chat can be read in order. */function MessageNav({+ model,session,node,onNavigate,}: {+ model: LineageViewModel;session: ViewSession | undefined;node: NodeDetail;onNavigate: ((target: OutlineTarget) => void) | undefined;}) {if (!session || !onNavigate || node.kind !== "message") return null;- const { previous, next } = messageNeighbors(session.nodes, node.nodeId);- const go = (target: typeof previous) =>+ const { previous, next } = messageNeighbors(session.messages, node.nodeId);+ const group = sessionGroupId(model, session.sessionId);+ const go = (target: ViewNode | null) =>target? () =>onNavigate({- focusId: nodeId(sessionKey(session.sessionId), target.id),- expand: [],- selection: { type: "node", node: toNodeDetail(target, session.sessionId) },+ focusId: sessionKey(session.sessionId),+ expand: group ? [group, sessionKey(session.sessionId)] : [],+ selection: {+ type: "node",+ sessionId: session.sessionId,+ nodeId: target.id,+ ...(branchOf(session, target.id) ? { branchId: branchOf(session, target.id) } : {}),+ },}): undefined;return (@@ -269,16 +345,19 @@ function MessageNav({function NodeDetails({model,node,+ branchId,onNavigate,}: {model: LineageViewModel;node: NodeDetail;+ branchId?: string | undefined;onNavigate: ((target: OutlineTarget) => void) | undefined;}) {const session = findSession(model, node.sessionId);return (<>- <MessageNav session={session} node={node} onNavigate={onNavigate} />+ <MessageNav model={model} session={session} node={node} onNavigate={onNavigate} />+ {session ? <BranchDetails session={session} branchId={branchId} /> : null}{node.summary ? (<section><h3>Summary</h3>@@ -450,9 +529,12 @@ export function DrillDown({);}- const { node } = selection;+ const session = findSession(model, selection.sessionId);+ const message = session ? findMessage(session, selection.nodeId) : undefined;+ if (!session || !message) return null;+ const node = toNodeDetail(message, session.sessionId);return (- <aside className="drilldown" role="dialog" aria-label="Node details">+ <aside className="drilldown" role="dialog" aria-label="Message details"><header className="drilldown-head"><div><span className={`kind kind-${node.kind}`}>{kindLabel(node.kind)}</span>@@ -463,7 +545,12 @@ export function DrillDown({</button></header><div className="drilldown-body">- <NodeDetails model={model} node={node} onNavigate={onNavigate} />+ <NodeDetails+ model={model}+ node={node}+ branchId={selection.branchId}+ onNavigate={onNavigate}+ /></div></aside>);diff --git a/packages/template/src/cardHeight.ts b/packages/template/src/cardHeight.tsdeleted file mode 100644index 7901ec9..0000000--- a/packages/template/src/cardHeight.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * Card heights for the map, computed from the text so every card shows its whole- * title and summary. The layout never measures the DOM; it wraps words against- * canvas text metrics (or a character estimate where no canvas exists).- */--export type Measure = (text: string, font: string) => number;--const FONT_FAMILY = 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif';-const TITLE_FONT = `700 13px ${FONT_FAMILY}`;-const BODY_FONT = `400 11px ${FONT_FAMILY}`;-const KIND_FONT = `400 10px ${FONT_FAMILY}`;-const META_FONT = `400 10px ${FONT_FAMILY}`;-const TITLE_LINE = 17;-const BODY_LINE = 15;-/** Padding, borders and the gap above the body line. */-const CHROME = 18;-const BODY_GAP = 3;-const HEAD_MIN = 20;-/**- * Horizontal room the card's padding and borders take, plus a margin: the browser- * wraps a little earlier than the measured widths suggest.- */-const INSET = 34;-const TOGGLE = 26;-const KIND_PADDING = 18;-/** Wrapping is measured, not rendered; a little slack keeps the last line clear. */-const SLACK = 4;--let canvasMeasure: Measure | null | undefined;--function defaultMeasure(): Measure {- if (canvasMeasure === undefined) {- canvasMeasure = null;- try {- const context = document.createElement("canvas").getContext("2d");- if (context) {- canvasMeasure = (text, font) => {- context.font = font;- return context.measureText(text).width;- };- }- } catch {- // no DOM (tests, server): fall back to the estimate- }- }- return canvasMeasure ?? estimate;-}--/** Average glyph width for the UI fonts, used when there is no canvas. */-function estimate(text: string, font: string): number {- const size = Number.parseFloat(font.split(" ")[1] ?? "12");- return text.length * size * 0.56;-}--/** Number of lines `text` takes when wrapped at word boundaries to `width`. */-export function countLines(text: string, width: number, font: string, measure: Measure): number {- const words = text.split(/\s+/).filter(Boolean);- if (words.length === 0) return 0;- let lines = 1;- let line = "";- for (const word of words) {- const next = line ? `${line} ${word}` : word;- if (measure(next, font) <= width || !line) {- // a single word wider than the card breaks inside itself- if (!line && measure(word, font) > width) {- lines += Math.ceil(measure(word, font) / width) - 1;- }- line = next;- } else {- lines += 1;- line = word;- if (measure(word, font) > width) lines += Math.ceil(measure(word, font) / width) - 1;- }- }- return lines;-}--export interface CardText {- kindLabel: string;- title: string;- /** The line under the title: a summary, a time or an "N items inside" count. */- body?: string;- hasToggle: boolean;- /** A small line at the bottom: who decided, commits, rejected options. */- meta?: string;-}--export function cardHeight(- card: CardText,- width: number,- measure: Measure = defaultMeasure(),-): number {- const kindWidth = measure(card.kindLabel.toUpperCase(), KIND_FONT) * 1.05 + KIND_PADDING;- const titleWidth = width - INSET - kindWidth - (card.hasToggle ? TOGGLE : 0);- const titleLines = Math.max(1, countLines(card.title, titleWidth, TITLE_FONT, measure));- const head = Math.max(HEAD_MIN, titleLines * TITLE_LINE);- const bodyLines = card.body ? countLines(card.body, width - INSET, BODY_FONT, measure) : 0;- const body = bodyLines > 0 ? BODY_GAP + bodyLines * BODY_LINE : 0;- const metaLines = card.meta ? countLines(card.meta, width - INSET, META_FONT, measure) : 0;- const meta = metaLines > 0 ? BODY_GAP + metaLines * BODY_LINE : 0;- return Math.ceil(CHROME + head + body + meta + SLACK);-}diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.tsindex 0198aa2..90c6c5d 100644--- a/packages/template/src/fixture.ts+++ b/packages/template/src/fixture.ts@@ -1,11 +1,12 @@import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";-const node = (+const message = (id: string,- kind: ViewNode["kind"],title: string,+ parent: string | null,+ at: string,extra: Partial<ViewNode> = {},-): ViewNode => ({ id, kind, title, children: [], ...extra });+): ViewNode => ({ id, kind: "message", title, parent, at, ...extra });const session = (sessionId: string,@@ -13,7 +14,7 @@ const session = (epoch: string | null,startedAt: string,updatedAt: string,- nodes: ViewNode[],+ messages: ViewNode[],status: ViewSession["status"],): ViewSession => ({sessionId,@@ -23,13 +24,14 @@ const session = (startedAt,updatedAt,status,- nodes,+ messages,transcriptAvailable: true,});/*** Dev-only sample data (`npm run dev -w template`). Mirrors the shape `codelineage- * build` produces: two epochs, three sessions (one unassigned) and nested nodes.+ * build` produces: two epochs, three sessions (one unassigned), a branch that+ * folds, a return link and an unrecorded message at the end of a chain.*/export const fixture: LineageViewModel = {kind: "lineage",@@ -37,7 +39,7 @@ export const fixture: LineageViewModel = {project: {name: "codelineage",path: "/home/dev/codelineage",- generatedAt: "2026-10-21T12:00:00.000Z",+ generatedAt: "2026-10-24T12:00:00.000Z",},status: {goal: "Ship the project map as one self-contained HTML file.",@@ -47,7 +49,7 @@ export const fixture: LineageViewModel = {{ text: "Write the resume command copy fallback", needsUser: false },],next: "Render the fixture through the template and check the single-file build.",- lastActivity: "2026-10-21T11:42:00.000Z",+ lastActivity: "2026-10-24T11:42:00.000Z",},epochs: [{@@ -59,29 +61,58 @@ export const fixture: LineageViewModel = {"fixture-template","Template package and single-file output","map",- "2026-10-21T08:00:00.000Z",- "2026-10-21T11:42:00.000Z",+ "2026-10-24T08:00:00.000Z",+ "2026-10-24T11:42:00.000Z",[- node("n1", "phase", "Scaffold the template", {+ message("m1", "Scaffold the template package", null, "2026-10-24T09:00:00.000Z", {summary: "React 19 + Vite 8, one index.html at build time.",- at: "2026-10-21T09:05:00.000Z",- children: [- node("n2", "step", "Wire the data contract", {- summary: "The page reads the JSON script element and types it once.",- children: [- node("n3", "decision", "Read data from the DOM, not a fetch", {- why: "A fetch would break file://; the JSON element survives inlining.",- }),- ],- }),- node("n4", "question", "Should the fixture ship in production?", {- summary: "No: dev-only import is tree-shaken from the build.",- }),- ],+ branch: {+ title: "Template scaffold",+ asked: "Which build setup keeps the page one file?",+ outcome: "Vite + vite-plugin-singlefile; the data is embedded as JSON.",+ open: "",+ },}),- node("n5", "step", "Build the dev fixture", {+ message("m2", "Wire the data contract", "m1", "2026-10-24T09:12:00.000Z", {+ summary: "The page reads the JSON script element and types it once.",+ work: ["Added view/model.ts shared by CLI and template"],+ }),+ message("m3", "Read data from the DOM", "m2", "2026-10-24T09:20:00.000Z", {+ summary: "A fetch would break file://; the JSON element survives inlining.",+ decidedBy: "agent",+ alternatives: [{ option: "fetch the JSON", why: "breaks over file://" }],+ }),+ message("m4", "Build the dev fixture", "m3", "2026-10-24T09:41:00.000Z", {summary: "Two epochs, three sessions, one unassigned.",}),+ message("m5", "Check the page in the browser", "m4", "2026-10-24T10:02:00.000Z", {+ summary: "Layout measured; console clean.",+ }),+ message("m6", "Draw nested groups", "m4", "2026-10-24T10:20:00.000Z", {+ summary: "A second branch off the fixture work.",+ branch: {+ title: "Nested groups",+ asked: "How do epochs, sessions and messages nest?",+ outcome: "Groups around the git rows.",+ open: "",+ },+ }),+ message("m7", "Return to the data contract", "m6", "2026-10-24T10:35:00.000Z", {+ summary: "The contract needed one more field for the pending count.",+ links: ["m2"],+ }),+ message("m8", "Ship the map", "m7", "2026-10-24T11:10:00.000Z", {+ summary: "Build, open and verify.",+ }),+ message("m9", "Lineage graph idea", null, "2026-10-24T11:42:00.000Z", {+ summary: "A git graph of the user's messages.",+ branch: {+ title: "Git graph",+ asked: "What if the map read like a git history?",+ outcome: "",+ open: "Not built yet.",+ },+ }),],{goal: "Render a typed fixture through the template.",@@ -104,14 +135,20 @@ export const fixture: LineageViewModel = {"2026-10-20T09:00:00.000Z","2026-10-20T16:30:00.000Z",[- node("c1", "phase", "Harden session writes", {+ message("c1", "Harden session writes", null, "2026-10-20T09:00:00.000Z", {summary: "Locked read → merge → write with redaction.",- children: [- node("c2", "decision", "Keep node parents optional on input", {- why: "The agent can add a child without re-sending the whole tree.",- }),- ],+ branch: {+ title: "Safe writes",+ asked: "How do two turns write the same session?",+ outcome: "A per-session lock, then merge and redact.",+ open: "",+ },}),+ message("c2", "Keep parents optional on input", "c1", "2026-10-20T09:30:00.000Z", {+ why: "The agent can add a child without re-sending the whole tree.",+ decidedBy: "agreed",+ }),+ message("c3", "Add the turn counter", "c2", "2026-10-20T16:30:00.000Z"),],{goal: "Make session writes safe under concurrency.",@@ -131,9 +168,12 @@ export const fixture: LineageViewModel = {"2026-10-19T16:00:00.000Z","2026-10-19T18:00:00.000Z",[- node("u1", "step", "Sketch the status card", {+ message("u1", "Sketch the status card", null, "2026-10-19T16:00:00.000Z", {summary: "Goal, done, pending, next and last activity.",- children: [node("u2", "question", "What counts as an active session?")],+ }),+ message("u2", "What counts as an active session?", "u1", "2026-10-19T18:00:00.000Z", {+ summary: "Updated within the last 7 days.",+ unsummarized: true,}),],{diff --git a/packages/template/src/format.ts b/packages/template/src/format.tsindex bfde55a..59c7a6e 100644--- a/packages/template/src/format.ts+++ b/packages/template/src/format.ts@@ -14,41 +14,16 @@ export function formatDate(iso: string | null): string {: date.toLocaleDateString(undefined, { month: "short", day: "numeric" });}+/** A compact stamp for dense rows ("10-24 00:10"); unparseable values pass through. */+export function formatStamp(iso: string | null): string {+ if (!iso) return "—";+ const date = new Date(iso);+ if (Number.isNaN(date.getTime())) return iso;+ const pad = (value: number): string => String(value).padStart(2, "0");+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;+}+/** Phases are shown as topics, messages as what the user said. */export function kindLabel(kind: string): string {return kind === "phase" ? "topic" : kind === "message" ? "you" : kind;}--/** The line a collapsed topic shows in place of its summary. */-export function itemsInside(count: number): string {- return `${count} item${count === 1 ? "" : "s"} inside`;-}--const DECIDED_BY = { user: "you decided", agent: "agent decided", agreed: "agreed" } as const;--/** Who decided, and what more the drill-down holds; empty when there is nothing to say. */-export function cardMeta(node: {- decidedBy?: keyof typeof DECIDED_BY | undefined;- commits?: string[] | undefined;- alternatives?: unknown[] | undefined;- agentDecisions?: unknown[] | undefined;-}): string {- const parts: string[] = [];- if (node.decidedBy) parts.push(DECIDED_BY[node.decidedBy]);- const own = node.agentDecisions?.length ?? 0;- if (own > 0) parts.push(`${own} agent decision${own === 1 ? "" : "s"}`);- const commits = node.commits?.length ?? 0;- if (commits > 0) parts.push(`${commits} commit${commits === 1 ? "" : "s"}`);- const rejected = node.alternatives?.length ?? 0;- if (rejected > 0) parts.push(`${rejected} option${rejected === 1 ? "" : "s"} rejected`);- return parts.join(" · ");-}--/** A card's second line: for decisions the reason, otherwise the summary. */-export function cardText(node: {- kind: string;- summary?: string | undefined;- why?: string | undefined;-}) {- return node.kind === "decision" && node.why ? node.why : node.summary;-}diff --git a/packages/template/src/gitLayout.ts b/packages/template/src/gitLayout.tsnew file mode 100644index 0000000..2b6c337--- /dev/null+++ b/packages/template/src/gitLayout.ts@@ -0,0 +1,411 @@+import type { ViewNode } from "../../cli/src/view/model.js";++/**+ * Lays a session's messages out as a git graph (Story 8.2): one row per message+ * in send order, one lane per branch, branch starts curving out of the message+ * they react to, returns routed through a channel left of the lanes. Pure: the+ * React component draws exactly what this returns.+ *+ * Git terms here: a message is a commit, its `parent` is the message it reacts+ * to, a root starts something new, a branch is a chain of messages with only+ * one child each, and `links` are returns to older messages.+ */++/** One message per row; long branches fold into first / ⋮ N more / last. */+export const ROW_HEIGHT = 30;+/** A branch with more messages than this starts folded. */+export const FOLD_LIMIT = 4;+/** Extra space above a new root, so a fresh start reads as a break. */+export const ROOT_GAP = 24;+/** Distance between lanes; also the dot column spacing. */+export const LANE_GAP = 20;+/** Distance between the return channels on the left. */+export const CHANNEL_GAP = 12;+const CHANNEL_PAD = 8;+const LANE_PAD = 10;+const LANE_TAIL = 6;+/** Width reserved for the row text right of the dots. */+export const ROW_WIDTH = 520;+const ROW_GAP = 8;++/** How many lane colours the page defines (`--l0` … `--l5`). */+export const LANE_COLORS = 6;++export interface GitBranch {+ title: string;+ asked: string;+ outcome: string;+ open: string;+ /** First and last message of the branch, for the "m33–m36" range. */+ fromId: string;+ toId: string;+ count: number;+ firstAt?: string;+ lastAt?: string;+}++export interface GitSegment {+ /** The branch's first message id; stable across rebuilds, so UI state uses it. */+ id: string;+ ids: string[];+ /** The message the branch starts from; null for a new root. */+ parentId: string | null;+ parentSegmentId: string | null;+ lane: number;+ /** Lane of the branch this one starts from; null for a root. */+ parentLane: number | null;+ colorIndex: number;+ branch: GitBranch;+ /** Row y of the branch's first message and of the message it reacts to. */+ startY: number;+ parentY: number | null;+}++export interface GitReturn {+ /** The older message this row returns to. */+ id: string;+ colorIndex: number;+}++export interface GitMessageRow {+ kind: "message";+ message: ViewNode;+ segmentId: string;+ colorIndex: number;+ /** Centre of the row on the canvas. */+ y: number;+ /** First message of its branch: hollow ring and branch label. */+ first: boolean;+ /** A new root starts here, with a gap above it. */+ gap: boolean;+ returns: GitReturn[];+ /** "left off here": the newest message of the newest session. */+ head: boolean;+}++export interface GitMoreRow {+ kind: "more";+ segmentId: string;+ colorIndex: number;+ y: number;+ /** The messages the fold hides. */+ hidden: string[];+}++export type GitRow = GitMessageRow | GitMoreRow;++export interface GitLink {+ /** The message that returns. */+ fromId: string;+ /** The older message it returns to. */+ toId: string;+ fromY: number;+ toY: number;+ /** The column left of the lanes this link runs through. */+ channelX: number;+ colorIndex: number;+}++export interface GitLayout {+ segments: GitSegment[];+ rows: GitRow[];+ links: GitLink[];+ /** Dot x per lane. */+ laneX: number[];+ /** Width of the channel + lanes area; the row text starts after it. */+ graphWidth: number;+ /** Whole box: graph width, gap, then the row text. */+ width: number;+ height: number;+ headId: string | null;+}++export interface GitLayoutOptions {+ /** Branch ids the user has unfolded. */+ unfolded?: ReadonlySet<string>;+ /** The "Unfold all" toggle. */+ openAll?: boolean;+ /** Message that carries "left off here"; defaults to the newest message. */+ headId?: string | null;+}++interface RawRow {+ kind: "message" | "more";+ /** Position in send order; a folded row sits just after its first message. */+ index: number;+ segment: GitSegment;+ id?: string;+ hidden?: string[];+ y: number;+ gap: boolean;+}++/** Parent ids that point forward, at themselves or outside the session become roots. */+function parentOf(message: ViewNode, index: Map<string, number>): string | null {+ const parent = message.parent;+ if (typeof parent !== "string") return null;+ const self = index.get(message.id) ?? 0;+ const at = index.get(parent);+ return at !== undefined && at < self ? parent : null;+}++function branchOf(ids: string[], byId: Map<string, ViewNode>): GitBranch {+ const first = byId.get(ids[0] ?? "");+ const last = byId.get(ids[ids.length - 1] ?? "");+ return {+ title: (first?.branch?.title ?? first?.title ?? ids[0] ?? "").slice(0, 80),+ asked: first?.branch?.asked ?? "",+ outcome: first?.branch?.outcome ?? first?.summary ?? "",+ open: first?.branch?.open ?? "",+ fromId: ids[0] ?? "",+ toId: ids[ids.length - 1] ?? "",+ count: ids.length,+ ...(first?.at === undefined ? {} : { firstAt: first.at }),+ ...(last?.at === undefined ? {} : { lastAt: last.at }),+ };+}++export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions = {}): GitLayout {+ const index = new Map(messages.map((message, at) => [message.id, at]));+ const byId = new Map(messages.map((message) => [message.id, message]));+ const kids = new Map<string | null, string[]>();+ const parents = new Map<string, string | null>();+ for (const message of messages) {+ const parent = parentOf(message, index);+ parents.set(message.id, parent);+ const list = kids.get(parent) ?? [];+ list.push(message.id);+ kids.set(parent, list);+ }+ const children = (id: string | null): string[] => kids.get(id) ?? [];++ // A branch runs while each message has exactly one child; every child of its+ // last message starts a new branch hanging from it.+ const segments: GitSegment[] = [];+ const segOf = new Map<string, GitSegment>();+ const build = (start: string, parentSegment: GitSegment | null): GitSegment => {+ const ids = [start];+ let cur = start;+ while (children(cur).length === 1) {+ cur = children(cur)[0] as string;+ ids.push(cur);+ }+ const last = ids[ids.length - 1] as string;+ const segment: GitSegment = {+ id: start,+ ids,+ parentId: parents.get(start) ?? null,+ parentSegmentId: parentSegment?.id ?? null,+ lane: 0,+ parentLane: null,+ colorIndex: segments.length % LANE_COLORS,+ branch: branchOf(ids, byId),+ startY: 0,+ parentY: null,+ };+ segments.push(segment);+ for (const id of ids) segOf.set(id, segment);+ // The last message id and branch id agree only by accident; keep the map+ // from the last message's children as the branch points.+ for (const child of children(last)) build(child, segment);+ return segment;+ };+ for (const root of children(null)) build(root, null);++ // No `headId` key: the newest message is HEAD. An explicit null means this+ // session holds no HEAD (it is not the newest one), so its long branches fold.+ const headId = "headId" in options ? options.headId : (messages[messages.length - 1]?.id ?? null);+ const unfolded = options.unfolded ?? new Set<string>();+ const openAll = options.openAll ?? false;++ const raw: RawRow[] = [];+ for (const segment of segments) {+ const folded =+ segment.ids.length > FOLD_LIMIT &&+ !openAll &&+ !unfolded.has(segment.id) &&+ !(headId !== null && segment.ids.includes(headId));+ if (folded) {+ const first = segment.ids[0] as string;+ const last = segment.ids[segment.ids.length - 1] as string;+ const hidden = segment.ids.slice(1, -1);+ raw.push({+ kind: "message",+ index: index.get(first) ?? 0,+ segment,+ id: first,+ y: 0,+ gap: false,+ });+ raw.push({+ kind: "more",+ index: (index.get(first) ?? 0) + 0.5,+ segment,+ hidden,+ y: 0,+ gap: false,+ });+ raw.push({+ kind: "message",+ index: index.get(last) ?? 0,+ segment,+ id: last,+ y: 0,+ gap: false,+ });+ } else {+ for (const id of segment.ids) {+ raw.push({+ kind: "message",+ index: index.get(id) ?? 0,+ segment,+ id,+ y: 0,+ gap: false,+ });+ }+ }+ }+ raw.sort((a, b) => a.index - b.index);++ // Rows in time order; a new root gets a gap above it.+ let cursor = ROW_HEIGHT / 2;+ const rowOf = new Map<string, RawRow>();+ raw.forEach((row, at) => {+ row.gap =+ at > 0 &&+ row.kind === "message" &&+ row.segment.parentId === null &&+ row.segment.ids[0] === row.id;+ if (row.gap) cursor += ROOT_GAP;+ row.y = cursor + ROW_HEIGHT / 2;+ cursor += ROW_HEIGHT;+ if (row.kind === "message" && row.id) rowOf.set(row.id, row);+ for (const hidden of row.hidden ?? []) rowOf.set(hidden, row);+ });++ // Lanes: a branch may reuse its parent's lane once the parent is done, and+ // any lane whose earlier occupants no longer span this row.+ const segById = new Map(segments.map((segment) => [segment.id, segment]));+ const occupancy = new Map<number, [number, number][]>();+ const ordered = [...segments].sort((a, b) => (index.get(a.id) ?? 0) - (index.get(b.id) ?? 0));+ for (const segment of ordered) {+ const first = rowOf.get(segment.ids[0] ?? "");+ const last = rowOf.get(segment.ids[segment.ids.length - 1] ?? "");+ if (!first || !last) continue;+ const parentRow = segment.parentId === null ? null : rowOf.get(segment.parentId);+ const start = parentRow?.y ?? first.y;+ const span: [number, number] = [start, last.y + 0.1];+ const free = (lane: number): boolean =>+ !(occupancy.get(lane) ?? []).some(([a, b]) => a < span[1] && span[0] < b);+ const parent = segment.parentSegmentId === null ? null : segById.get(segment.parentSegmentId);+ let lane = parent && free(parent.lane) ? parent.lane : 0;+ while (!free(lane)) lane += 1;+ segment.lane = lane;+ segment.parentLane = parent?.lane ?? null;+ segment.startY = first.y;+ segment.parentY = parentRow?.y ?? null;+ const list = occupancy.get(lane) ?? [];+ list.push(span);+ occupancy.set(lane, list);+ }++ const laneCount = Math.max(0, ...segments.map((segment) => segment.lane + 1));+ const links: GitLink[] = [];+ for (const message of messages) {+ for (const target of message.links ?? []) {+ const from = rowOf.get(message.id);+ const to = rowOf.get(target);+ if (!from || !to) continue;+ links.push({+ fromId: message.id,+ toId: target,+ fromY: from.y,+ toY: to.y,+ channelX: 6 + links.length * CHANNEL_GAP,+ colorIndex: segOf.get(target)?.colorIndex ?? 0,+ });+ }+ }++ const channelWidth = links.length > 0 ? links.length * CHANNEL_GAP + CHANNEL_PAD : 0;+ const laneX = Array.from(+ { length: Math.max(laneCount, 1) },+ (_, lane) => channelWidth + LANE_PAD + lane * LANE_GAP,+ );+ const graphWidth = channelWidth + LANE_PAD + Math.max(laneCount, 1) * LANE_GAP + LANE_TAIL;++ const rows: GitRow[] = raw.map((row): GitRow => {+ if (row.kind === "more") {+ return {+ kind: "more",+ segmentId: row.segment.id,+ colorIndex: row.segment.colorIndex,+ y: row.y,+ hidden: row.hidden ?? [],+ };+ }+ const message = byId.get(row.id ?? "");+ if (!message) throw new Error(`message ${String(row.id)} vanished from the layout`);+ const returns: GitReturn[] = [];+ for (const target of message.links ?? []) {+ if (!rowOf.has(target)) continue;+ returns.push({ id: target, colorIndex: segOf.get(target)?.colorIndex ?? 0 });+ }+ return {+ kind: "message",+ message,+ segmentId: row.segment.id,+ colorIndex: row.segment.colorIndex,+ y: row.y,+ first: row.segment.ids[0] === message.id,+ gap: row.gap,+ returns,+ head: message.id === headId,+ };+ });++ return {+ segments,+ rows,+ links,+ laneX,+ graphWidth,+ width: graphWidth + ROW_GAP + ROW_WIDTH,+ height: cursor,+ headId,+ };+}++/** The dashed return route: target dot → left channel → arrow at the returning dot. */+export function linkPath(link: GitLink, targetX: number, fromX: number): string {+ const q = 6;+ const g = link.channelX;+ return [+ `M${targetX},${link.toY}`,+ `L${g + q},${link.toY}`,+ `Q${g},${link.toY} ${g},${link.toY + q}`,+ `L${g},${link.fromY - q}`,+ `Q${g},${link.fromY} ${g + q},${link.fromY}`,+ `L${fromX - 9},${link.fromY}`,+ ].join(" ");+}++/** Arrowhead at the returning message, pointing at its dot. */+export function linkArrow(link: GitLink, fromX: number): string {+ return `M${fromX - 15},${link.fromY - 4} L${fromX - 8},${link.fromY} L${fromX - 15},${link.fromY + 4}`;+}++/** The curve a branch start draws from its parent's dot into its lane. */+export function branchPath(segment: GitSegment, laneX: number[]): string {+ const x = laneX[segment.lane] ?? 0;+ const y0 = segment.parentY;+ if (y0 === null) return "";+ const px = segment.parentLane === null ? x : (laneX[segment.parentLane] ?? x);+ if (px === x) return `M${x},${y0} L${x},${segment.startY}`;+ return [+ `M${px},${y0}`,+ `C${px},${y0 + ROW_HEIGHT * 0.7} ${x},${y0 + ROW_HEIGHT * 0.3} ${x},${y0 + ROW_HEIGHT}`,+ `L${x},${segment.startY}`,+ ].join(" ");+}diff --git a/packages/template/src/graph.ts b/packages/template/src/graph.tsindex a1efb55..b63cb49 100644--- a/packages/template/src/graph.ts+++ b/packages/template/src/graph.ts@@ -5,41 +5,28 @@ import ELK, {type ElkNode,} from "elkjs/lib/elk.bundled.js";import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";-import { cardHeight } from "./cardHeight.js";-import { cardMeta, cardText, formatTime, itemsInside, kindLabel } from "./format.js";+import { type GitLayout, layoutGitGraph } from "./gitLayout.js";/**- * Builds the nested React Flow graph (epoch → session → node) and lays it out- * with ELK in the page. ELK returns child coordinates relative to their parent,- * which is what React Flow's `parentId` children expect, so no conversion is- * needed for nested nodes.+ * Builds the nested map (epoch → session) and lays it out with ELK in the page.+ * What a session shows inside (its git graph) is laid out by `gitLayout.ts`;+ * only the groups are React Flow nodes, so a 500-message session costs ELK+ * nothing. ELK returns child coordinates relative to their parent, which is+ * what React Flow's `parentId` children expect.*/-/** Fixed card sizes keep ELK fast: it never needs to measure DOM text. */-const NODE_WIDTH = 240;-/** Cards grow with their text (see cardHeight); this is the floor. */-const NODE_HEIGHT = 48;const GROUP_HEIGHT = 56;const GROUP_WIDTH = 260;const GROUP_PADDING = 24;const GROUP_HEADER = 44;-+/** Height of a session's header bar; its git graph starts right below. */+export const SESSION_GROUP_HEADER = GROUP_HEADER;+/** Inner padding of a group box. */+export const GROUP_INSET = GROUP_PADDING;const ROOT_PADDING = 48;--/** Inside a topic column nodes read top to bottom, nested items indented below their topic. */-const INDENT = 32;-const ROW_GAP = 16;-const COLUMN_GAP = 24;-/** Room for the "left off here" or "not summarized yet" badge under the title. */-const LEFT_OFF_BADGE = 20;-const PENDING_BADGE = 20;/** Wide enough that a collapsed session shows a readable title. */const SESSION_WIDTH = 380;-/** Handle ids on lineage cards: the spine leaves at the bottom left and enters at the left side. */-export const TREE_OUT = "tree-out";-export const TREE_LEFT = "tree-left";-export type EpochData = {title: string;count: number;@@ -55,9 +42,13 @@ export type SessionData = {count: number;expanded: boolean;hasChildren: boolean;+ /** Draw inside the session; only set while the session is open. */+ git?: GitLayout;+ /** User messages the record does not hold yet, while the catch-up is off. */+ unrecorded?: number;};-/** Everything the drill-down panel shows about a node. */+/** Everything the drill-down panel shows about a message. */export type NodeDetail = {kind: ViewNode["kind"];title: string;@@ -72,6 +63,8 @@ export type NodeDetail = {agentDecisions?: ViewNode["agentDecisions"];addedAt?: string;touchedAt?: string;+ parent?: string | null;+ links?: string[];/** A user message the record does not hold yet. */unsummarized?: true;/** Owning session, so the drill-down panel can show and resume it. */@@ -81,24 +74,13 @@ export type NodeDetail = {};export function toNodeDetail(node: ViewNode, sessionId: string): NodeDetail {- const { id, children: _children, ...detail } = node;- return { ...detail, sessionId, nodeId: id };+ return { ...node, sessionId, nodeId: node.id };}-export type LineageData = NodeDetail & {- /** Nodes nested below this one, at any depth. */- count: number;- expanded: boolean;- hasChildren: boolean;- /** One of the nodes the last write added or changed: where the work left off. */- isLast: boolean;-};--export type EpochFlowNode = FlowNode<EpochData, "epoch">;export type SessionFlowNode = FlowNode<SessionData, "session">;-export type LineageFlowNode = FlowNode<LineageData, "lineage">;+export type EpochFlowNode = FlowNode<EpochData, "epoch">;-export type GraphNode = EpochFlowNode | SessionFlowNode | LineageFlowNode;+export type GraphNode = EpochFlowNode | SessionFlowNode;export interface GraphLayout {nodes: GraphNode[];@@ -118,8 +100,8 @@ export function sessionId(id: string): string {}/**- * Node ids are flat per session (not per parent): the outline and the graph- * must agree on the same id to focus each other's items.+ * Node ids are flat per session: the outline and the map agree on the same id+ * when the outline highlights a message.*/export function nodeId(sessionGroup: string, id: string): string {return `node:${sessionGroup}:${id}`;@@ -141,48 +123,13 @@ function groupOptions() {};}-export interface LastTouched {+/** Where the work left off: the newest message of the most recently updated session. */+export interface Head {sessionKey: string;- /** Every node the last write added or changed: they share the newest touch time. */- nodeKeys: string[];- /** Epoch, session and every topic above those nodes, outermost first. */- ancestors: string[];-}--/**- * Where the work left off, in the most recently updated session: its last user- * message when it has messages, else the nodes touched by its last write (one- * write stamps all its nodes at once, so they are all marked rather than- * guessing which of them came last).- */-export function lastTouched(model: LineageViewModel): LastTouched | null {- const latest = latestSession(model);- if (!latest) return null;- const sessionKey = sessionId(latest.session.sessionId);- let newest = "";- const found: { key: string; ancestors: string[]; at: string }[] = [];- const visit = (nodes: ViewNode[], ancestors: string[]): void => {- for (const node of nodes) {- const key = nodeId(sessionKey, node.id);- const at = byMessage ? (node.kind === "message" ? node.at : undefined) : node.touchedAt;- if (at) {- found.push({ key, ancestors, at });- if (at > newest) newest = at;- }- visit(node.children, [...ancestors, key]);- }- };- const byMessage = hasMessage(latest.session.nodes);- visit(latest.session.nodes, []);- const last = found.filter((entry) => entry.at === newest);- if (last.length === 0) return null;- const ancestors = new Set([latest.group, sessionKey]);- for (const entry of last) for (const key of entry.ancestors) ancestors.add(key);- return { sessionKey, nodeKeys: last.map((entry) => entry.key), ancestors: [...ancestors] };-}--function hasMessage(nodes: ViewNode[]): boolean {- return nodes.some((node) => (node.kind === "message" && node.at) || hasMessage(node.children));+ sessionId: string;+ messageId: string | null;+ /** Epoch group the session belongs to. */+ group: string;}function latestSession(@@ -198,17 +145,34 @@ function latestSession()[0];}+export function headOf(model: LineageViewModel): Head | null {+ const latest = latestSession(model);+ if (!latest) return null;+ return {+ sessionKey: sessionId(latest.session.sessionId),+ sessionId: latest.session.sessionId,+ messageId: latest.session.messages[latest.session.messages.length - 1]?.id ?? null,+ group: latest.group,+ };+}+/*** The map opens on the most recently updated session, with its epoch expanded,- * showing that session's top-level topics and the branch to the last touched node;- * deeper layers open on click.+ * showing that session's git graph.*/export function defaultExpanded(model: LineageViewModel): Set<string> {- const latest = latestSession(model);- if (!latest) return new Set();- // Also open the branch that leads to where the work left off.- const last = lastTouched(model);- return new Set([latest.group, sessionId(latest.session.sessionId), ...(last?.ancestors ?? [])]);+ const head = headOf(model);+ if (!head) return new Set();+ return new Set([head.group, head.sessionKey]);+}++/** The epoch group a session lives in, for the outline's reveal list. */+export function sessionGroupId(model: LineageViewModel, id: string): string | null {+ for (const epoch of model.epochs) {+ if (epoch.sessions.some((session) => session.sessionId === id)) return epochId(epoch.id);+ }+ if (model.unassigned.some((session) => session.sessionId === id)) return UNASSIGNED_EPOCH_ID;+ return null;}interface Group {@@ -239,143 +203,78 @@ function chainEdges(ids: string[]): ElkExtendedEdge[] {return edges;}-interface Placement {- boxes: Map<string, Sized>;- edges: FlowEdge[];+interface Sized {+ x: number;+ y: number;width: number;height: number;}-/** Tall enough for the card's whole title and the line below it, as the card renders them. */-function nodeHeight(node: ViewNode, open: boolean): number {- const hasChildren = node.children.length > 0;- const body =- hasChildren && !open- ? itemsInside(countNodes(node.children))- : node.at && node.kind !== "message"- ? formatTime(node.at)- : cardText(node);- const meta = cardMeta(node);- return Math.max(- NODE_HEIGHT,- cardHeight(- {- kindLabel: kindLabel(node.kind),- title: node.title,- hasToggle: hasChildren,- ...(body ? { body } : {}),- ...(meta ? { meta } : {}),- },- NODE_WIDTH,- ),- );-}--function treeEdge(source: string, target: string, targetHandle: string): FlowEdge {- return {- id: `edge:${source}->${target}`,- source,- target,- sourceHandle: TREE_OUT,- targetHandle,- type: "smoothstep",- };+interface SessionSize {+ width: number;+ height: number;+ git?: GitLayout;}-/**- * Places a session's nodes: top-level topics side by side as columns (they run in- * parallel, so their order matters little), and inside each column an indented,- * top-to-bottom outline of what the topic holds, in recorded order. Time runs- * down the map across sessions; topics run across.- */-export function placeSessionNodes(- nodes: ViewNode[],- sessionGroup: string,- isOpen: (id: string) => boolean = () => true,- lastKeys: ReadonlySet<string> = new Set(),-): Placement {- const boxes = new Map<string, Sized>();- const edges: FlowEdge[] = [];- const top = GROUP_HEADER + 8;- let columnX = GROUP_PADDING;- let bottom = top;- for (const root of nodes) {- let y = top;- let columnWidth = NODE_WIDTH;- const visit = (node: ViewNode, parent: string | null, depth: number): void => {- const id = nodeId(sessionGroup, node.id);- const open = isOpen(id);- const height =- nodeHeight(node, open) +- (lastKeys.has(id) ? LEFT_OFF_BADGE : 0) +- (node.unsummarized ? PENDING_BADGE : 0);- boxes.set(id, { x: columnX + depth * INDENT, y, width: NODE_WIDTH, height });- y += height + ROW_GAP;- columnWidth = Math.max(columnWidth, depth * INDENT + NODE_WIDTH);- if (parent !== null) edges.push(treeEdge(parent, id, TREE_LEFT));- if (open) for (const child of node.children) visit(child, id, depth + 1);- };- visit(root, null, 0);- bottom = Math.max(bottom, y - ROW_GAP);- columnX += columnWidth + COLUMN_GAP;- }+function measureSession(open: boolean, git: GitLayout | null): SessionSize {+ if (!open || !git) return { width: SESSION_WIDTH, height: GROUP_HEIGHT };return {- boxes,- edges,- width: Math.max(columnX - COLUMN_GAP, GROUP_PADDING) + GROUP_PADDING,- height: bottom + GROUP_PADDING,+ width: Math.max(SESSION_WIDTH, git.width + GROUP_PADDING * 2),+ height: GROUP_HEADER + 8 + git.height + GROUP_PADDING,+ git,};}function buildSession(session: ViewSession,expanded: ReadonlySet<string>,- parentId: string,meta: Map<string, string | null>,- placements: Map<string, Placement>,- lastKeys: ReadonlySet<string>,-): ElkNode {+ parentId: string,+ headId: string | null,+ unfolded: ReadonlySet<string>,+ openAll: boolean,+): { node: ElkNode; git?: GitLayout } {const id = sessionId(session.sessionId);meta.set(id, parentId);- const showChildren = expanded.has(id) && session.nodes.length > 0;- if (!showChildren) return { id, width: SESSION_WIDTH, height: GROUP_HEIGHT };-- // ELK sizes the session box; its contents are placed by hand.- const placement = placeSessionNodes(- session.nodes,- id,- (nodeKey) => expanded.has(nodeKey),- lastKeys,- );- placements.set(id, placement);- return { id, width: Math.max(SESSION_WIDTH, placement.width), height: placement.height };+ const open = expanded.has(id) && session.messages.length > 0;+ const git = open ? layoutGitGraph(session.messages, { unfolded, openAll, headId }) : null;+ const size = measureSession(open, git);+ return {+ node: { id, width: size.width, height: size.height },+ ...(size.git ? { git: size.git } : {}),+ };}function buildEpoch(group: Group,expanded: ReadonlySet<string>,meta: Map<string, string | null>,- placements: Map<string, Placement>,- lastKeys: ReadonlySet<string>,+ head: Head | null,+ unfolded: ReadonlySet<string>,+ openAll: boolean,+ gits: Map<string, GitLayout>,): ElkNode {meta.set(group.id, null);const showChildren = expanded.has(group.id) && group.sessions.length > 0;if (!showChildren) return { id: group.id, width: GROUP_WIDTH, height: GROUP_HEIGHT };- const children = group.sessions.map((session) =>- buildSession(session, expanded, group.id, meta, placements, lastKeys),- );+ const children = group.sessions.map((session) => {+ const built = buildSession(+ session,+ expanded,+ meta,+ group.id,+ head?.sessionId === session.sessionId ? head.messageId : null,+ unfolded,+ openAll,+ );+ if (built.git) gits.set(session.sessionId, built.git);+ return built.node;+ });const edges = chainEdges(children.map((child) => child.id));return { id: group.id, children, edges, layoutOptions: groupOptions() };}-interface Sized {- x: number;- y: number;- width: number;- height: number;-}-function collectSizes(elk: ElkNode, out: Map<string, Sized>): void {for (const child of elk.children ?? []) {out.set(child.id, {@@ -388,8 +287,19 @@ function collectSizes(elk: ElkNode, out: Map<string, Sized>): void {}}-export function countNodes(nodes: ViewNode[]): number {- return nodes.reduce((sum, node) => sum + 1 + countNodes(node.children), 0);+/** The messages just before and after a message in its session, by send order. */+export function messageNeighbors(+ messages: ViewNode[],+ id: string,+): { previous: ViewNode | null; next: ViewNode | null } {+ const index = messages.findIndex((message) => message.id === id);+ if (index < 0) return { previous: null, next: null };+ return { previous: messages[index - 1] ?? null, next: messages[index + 1] ?? null };+}++export interface GitLayoutPreferences {+ unfolded: ReadonlySet<string>;+ openAll: boolean;}/**@@ -399,6 +309,7 @@ export function countNodes(nodes: ViewNode[]): number {export async function layoutGraph(model: LineageViewModel,expanded: ReadonlySet<string>,+ preferences: GitLayoutPreferences = { unfolded: new Set(), openAll: false },elk: ElkInstance = new ELK(),): Promise<GraphLayout> {const groups: Group[] = model.epochs.map((epoch) => ({@@ -410,11 +321,11 @@ export async function layoutGraph(groups.push({ id: UNASSIGNED_EPOCH_ID, title: "Unassigned", sessions: model.unassigned });}- const lastKeys: ReadonlySet<string> = new Set(lastTouched(model)?.nodeKeys ?? []);+ const head = headOf(model);const parents = new Map<string, string | null>();- const placements = new Map<string, Placement>();+ const gits = new Map<string, GitLayout>();const rootChildren = groups.map((group) =>- buildEpoch(group, expanded, parents, placements, lastKeys),+ buildEpoch(group, expanded, parents, head, preferences.unfolded, preferences.openAll, gits),);const rootEdges = chainEdges(rootChildren.map((child) => child.id));@@ -434,9 +345,6 @@ export async function layoutGraph(const sizes = new Map<string, Sized>();collectSizes(result, sizes);- for (const placement of placements.values()) {- for (const [id, box] of placement.boxes) sizes.set(id, box);- }const seenEdges = new Set<string>();const edges: FlowEdge[] = [];const addEdge = (edge: ElkExtendedEdge): void => {@@ -444,10 +352,7 @@ export async function layoutGraph(if (flow) edges.push(flow);};for (const edge of rootEdges) addEdge(edge);- for (const child of rootChildren) {- for (const edge of child.edges ?? []) addEdge(edge);- }- for (const placement of placements.values()) edges.push(...placement.edges);+ for (const child of rootChildren) for (const edge of child.edges ?? []) addEdge(edge);const nodes: GraphNode[] = [];const box = (id: string): Sized =>@@ -479,6 +384,7 @@ export async function layoutGraph(const id = sessionId(session.sessionId);const sessionExpanded = expanded.has(id);const sessionSize = box(id);+ const git = gits.get(session.sessionId);nodes.push({id,type: "session",@@ -495,55 +401,19 @@ export async function layoutGraph(sessionId: session.sessionId,updatedAt: session.updatedAt,goal: session.status.goal,- count: countNodes(session.nodes),+ count: session.messages.length,expanded: sessionExpanded,- hasChildren: session.nodes.length > 0,+ hasChildren: session.messages.length > 0,+ ...(git ? { git } : {}),+ ...(session.unrecordedMessages ? { unrecorded: session.unrecordedMessages } : {}),},});- if (!sessionExpanded) continue;- collectFlowNodes(session.nodes, id, session.sessionId, nodes, sizes, expanded, lastKeys);}}return { nodes, edges, layoutMs };}-function collectFlowNodes(- nodes: ViewNode[],- parent: string,- sessionId: string,- out: GraphNode[],- sizes: Map<string, Sized>,- expanded: ReadonlySet<string>,- lastKeys: ReadonlySet<string>,-): void {- for (const node of nodes) {- const id = nodeId(parent, node.id);- const open = expanded.has(id);- const size = sizes.get(id) ?? { x: 0, y: 0, width: NODE_WIDTH, height: NODE_HEIGHT };- out.push({- id,- type: "lineage",- parentId: parent,- position: { x: size.x, y: size.y },- width: size.width,- height: size.height,- style: { width: size.width, height: size.height },- draggable: false,- connectable: false,- selectable: false,- data: {- ...toNodeDetail(node, sessionId),- count: countNodes(node.children),- expanded: open,- hasChildren: node.children.length > 0,- isLast: lastKeys.has(id),- },- });- if (open) collectFlowNodes(node.children, parent, sessionId, out, sizes, expanded, lastKeys);- }-}-/*** Where a node sits on the canvas: its own position plus every parent's, since* React Flow positions children relative to their `parentId`. Null when the@@ -567,22 +437,3 @@ export function absolutePosition(}return { x, y };}--/** The messages just before and after a message in its session, by when they were sent. */-export function messageNeighbors(- nodes: ViewNode[],- id: string,-): { previous: ViewNode | null; next: ViewNode | null } {- const messages: ViewNode[] = [];- const visit = (list: ViewNode[]): void => {- for (const node of list) {- if (node.kind === "message") messages.push(node);- visit(node.children);- }- };- visit(nodes);- messages.sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));- const index = messages.findIndex((node) => node.id === id);- if (index < 0) return { previous: null, next: null };- return { previous: messages[index - 1] ?? null, next: messages[index + 1] ?? null };-}diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 92e9c12..2f2d071 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -7,6 +7,13 @@--muted: #8b93a7;--accent: #7aa2f7;--warn: #e0af68;+ /* Branch lanes in the git graph (Story 8.2). */+ --l0: #7aa2f7;+ --l1: #9ece6a;+ --l2: #e0af68;+ --l3: #bb9af7;+ --l4: #7dcfff;+ --l5: #f7768e;}* {@@ -379,11 +386,6 @@ body:has(.map-shell.is-expanded) {}/* Edges attach here; handles stay invisible because layout decides the shape. */-/* The outline spine runs down the left edge of each card, clear of indented items. */-.react-flow__handle.tree-handle {- left: 16px;-}-.react-flow__handle.flow-handle {width: 4px;height: 4px;@@ -395,75 +397,10 @@ body:has(.map-shell.is-expanded) {background: transparent;}-/* Node cards; the left border encodes the node kind. */-.lineage-box {- width: 100%;- height: 100%;- padding: 7px 10px;- overflow: hidden;- background: var(--panel);- border: 1px solid var(--line);- border-left: 3px solid var(--accent);- border-radius: 8px;- cursor: pointer;-}--.lineage-box:hover {- border-color: var(--accent);-}-.session-group:hover {border-color: var(--accent);}-.lineage-box.kind-phase {- border-left-color: var(--accent);-}--.lineage-box.kind-step {- border-left-color: #7dcfff;-}--.lineage-box.kind-decision {- border-left-color: #c0a8ff;-}--.lineage-box.kind-question {- border-left-color: var(--warn);-}--.lineage-box.kind-message {- border-left-color: #9ece6a;-}--.lineage-head {- display: flex;- align-items: flex-start;- gap: 6px;- min-width: 0;-}--/* Text wraps; the layout sizes each card to fit it (cardHeight.ts mirrors these metrics). */-.lineage-head strong {- min-width: 0;- font-size: 13px;- line-height: 17px;- overflow-wrap: anywhere;-}--.lineage-box p {- margin: 3px 0 0;- color: var(--muted);- font-size: 11px;- line-height: 15px;- overflow-wrap: anywhere;-}--.lineage-box.is-last {- border-color: var(--warn);- box-shadow: 0 0 0 2px rgba(240, 180, 90, 0.35);-}-.left-off {display: inline-block;margin-top: 4px;@@ -475,8 +412,8 @@ body:has(.map-shell.is-expanded) {line-height: 14px;}-/* A card built from the transcript before the record summarizes it. */-.lineage-box.kind-message .unsummarized {+/* A row built from the transcript before the record summarizes it. */+.unsummarized {display: inline-block;margin-top: 4px;padding: 1px 6px;@@ -487,23 +424,6 @@ body:has(.map-shell.is-expanded) {line-height: 14px;}-.lineage-box p.card-meta {- font-size: 10px;- color: var(--accent);- opacity: 0.85;-}--.lineage-box p.lineage-count {- color: var(--accent);-}--.lineage-box time {- display: block;- margin-top: 3px;- font-size: 11px;- line-height: 15px;-}-.kind {flex: none;padding: 1px 6px;@@ -881,3 +801,118 @@ time {color: var(--muted);font-style: italic;}++/* Git graph inside a session (Story 8.2): rows in time order, dots and lanes+ drawn in an SVG to their left. */+.git-graph {+ position: relative;+ margin: 0 0 24px 24px;+}++.git-lanes {+ position: absolute;+ top: 0;+ left: 0;+ overflow: visible;+}++.git-rows {+ position: absolute;+ top: 0;+ width: 520px;+}++.git-row {+ position: absolute;+ left: 0;+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ padding: 0 8px;+ overflow: hidden;+ color: var(--text);+ font: inherit;+ font-size: 12px;+ text-align: left;+ white-space: nowrap;+ background: none;+ border: 1px solid transparent;+ border-radius: 5px;+ cursor: pointer;+}++.git-row:hover {+ background: #1d222c;+}++.git-row.in-branch {+ background: rgba(122, 162, 247, 0.06);+}++.git-row.is-selected {+ background: #243040;+ outline: 1px solid var(--accent);+}++.git-more {+ color: var(--muted);+ font-style: italic;+}++.git-time {+ flex: none;+ width: 74px;+ overflow: hidden;+ color: var(--muted);+ font-size: 11px;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.git-branch {+ flex: none;+ max-width: 150px;+ overflow: hidden;+ padding: 1px 6px;+ color: #0f1115;+ font-size: 10px;+ font-weight: 600;+ text-overflow: ellipsis;+ background: var(--accent);+ border-radius: 4px;+}++.git-id {+ flex: none;+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+}++.git-title {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.git-returns {+ display: flex;+ flex: none;+ gap: 4px;+ font-size: 11px;+}++.git-row .left-off,+.git-row .unsummarized {+ flex: none;+ margin: 0;+}++/* The branch summary a clicked row opens in the side panel. */+.branch-range {+ color: var(--muted);+ font-size: 12px;+}diff --git a/packages/template/test/cardHeight.test.ts b/packages/template/test/cardHeight.test.tsdeleted file mode 100644index e14819b..0000000--- a/packages/template/test/cardHeight.test.ts+++ /dev/null@@ -1,47 +0,0 @@-import { describe, expect, it } from "vitest";-import { cardHeight, countLines, type Measure } from "../src/cardHeight.js";--/** Every character is 10px wide, so wrapping is easy to reason about. */-const fixed: Measure = (text) => text.length * 10;--describe("countLines", () => {- it("wraps at word boundaries", () => {- expect(countLines("", 100, "f", fixed)).toBe(0);- expect(countLines("aaaa bbbb", 100, "f", fixed)).toBe(1);- expect(countLines("aaaa bbbb cccc", 100, "f", fixed)).toBe(2);- });-- it("breaks a word longer than the line", () => {- expect(countLines("a".repeat(25), 100, "f", fixed)).toBe(3);- expect(countLines(`ab ${"c".repeat(25)}`, 100, "f", fixed)).toBe(4);- });-});--describe("cardHeight", () => {- const card = { kindLabel: "step", title: "Short", hasToggle: false };-- it("grows with a longer title and with a body line", () => {- const short = cardHeight(card, 240, fixed);- const long = cardHeight({ ...card, title: "word ".repeat(30) }, 240, fixed);- const withBody = cardHeight({ ...card, body: "summary ".repeat(20) }, 240, fixed);- expect(long).toBeGreaterThan(short);- expect(withBody).toBeGreaterThan(short);- });-- it("leaves less room for the title when the card has a toggle", () => {- const title = "word ".repeat(9);- expect(cardHeight({ ...card, title, hasToggle: true }, 240, fixed)).toBeGreaterThanOrEqual(- cardHeight({ ...card, title }, 240, fixed),- );- });-- it("adds room for the meta line", () => {- expect(cardHeight({ ...card, meta: "agreed · 1 commit" }, 240, fixed)).toBeGreaterThan(- cardHeight(card, 240, fixed),- );- });-- it("falls back to an estimate without a canvas", () => {- expect(cardHeight(card, 240)).toBeGreaterThan(30);- });-});diff --git a/packages/template/test/format.test.ts b/packages/template/test/format.test.tsindex 02331ab..3a5bb00 100644--- a/packages/template/test/format.test.ts+++ b/packages/template/test/format.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { cardMeta, cardText, formatDate, formatTime, kindLabel } from "../src/format.js";+import { formatDate, formatTime, kindLabel } from "../src/format.js";describe("format", () => {it("shows a placeholder for a missing time and an unparseable value as-is", () => {@@ -26,21 +26,3 @@ describe("kindLabel", () => {expect(kindLabel("decision")).toBe("decision");});});--describe("card text", () => {- it("shows a decision's reason and other kinds' summary", () => {- expect(cardText({ kind: "decision", summary: "s", why: "w" })).toBe("w");- expect(cardText({ kind: "decision", summary: "s" })).toBe("s");- expect(cardText({ kind: "step", summary: "s", why: "w" })).toBe("s");- });-- it("sums up who decided, commits and rejected options", () => {- expect(cardMeta({})).toBe("");- expect(cardMeta({ decidedBy: "agreed", commits: ["a"], alternatives: [1, 2] })).toBe(- "agreed · 1 commit · 2 options rejected",- );- expect(cardMeta({ decidedBy: "user", commits: ["a", "b"], alternatives: [1] })).toBe(- "you decided · 2 commits · 1 option rejected",- );- });-});diff --git a/packages/template/test/gitLayout.test.ts b/packages/template/test/gitLayout.test.tsnew file mode 100644index 0000000..35a7161--- /dev/null+++ b/packages/template/test/gitLayout.test.ts@@ -0,0 +1,187 @@+import { describe, expect, it } from "vitest";+import type { ViewNode } from "../../cli/src/view/model.js";+import {+ FOLD_LIMIT,+ type GitMessageRow,+ layoutGitGraph,+ linkArrow,+ linkPath,+ ROOT_GAP,+ ROW_HEIGHT,+} from "../src/gitLayout.js";++let clock = 0;++/** Messages in the order they are given; `parent` and `links` as a record has them. */+function message(id: string, parent: string | null, extra: Partial<ViewNode> = {}): ViewNode {+ clock += 1;+ return {+ id,+ kind: "message",+ title: `Message ${id}`,+ at: new Date(Date.UTC(2026, 9, 24, 10, clock)).toISOString(),+ parent,+ ...extra,+ };+}++function rowsOf(messages: ViewNode[], options = {}) {+ const layout = layoutGitGraph(messages, options);+ const messageRows = layout.rows.filter((row): row is GitMessageRow => row.kind === "message");+ return { layout, messageRows };+}++describe("segments", () => {+ it("runs a branch while messages have one child, and starts a branch at each extra child", () => {+ const messages = [+ message("m1", null),+ message("m2", "m1"),+ message("m3", "m1"),+ message("m4", "m2"),+ ];+ const { segments } = layoutGitGraph(messages);+ expect(segments.map((segment) => segment.ids)).toEqual([["m1"], ["m2", "m4"], ["m3"]]);+ expect(segments[1]?.parentId).toBe("m1");+ expect(segments[2]?.parentSegmentId).toBe("m1");+ });++ it("treats a missing or forward parent as a root, so old records still draw", () => {+ const messages = [message("m1", "m2"), message("m2", null)];+ const { segments } = layoutGitGraph(messages);+ expect(segments.map((segment) => segment.ids)).toEqual([["m1"], ["m2"]]);+ expect(segments.every((segment) => segment.parentId === null)).toBe(true);+ });+});++describe("lanes", () => {+ it("reuses a lane once the branch that used it is done", () => {+ const messages = [+ message("m1", null),+ message("m2", "m1"),+ message("m3", null),+ message("m4", "m3"),+ ];+ const { segments, laneX } = layoutGitGraph(messages);+ expect(segments.map((segment) => segment.lane)).toEqual([0, 0]);+ expect(laneX).toHaveLength(1);+ });++ it("gives overlapping branches their own lanes", () => {+ // m2 starts while the m1–m3 chain still runs, so they overlap in time.+ const messages = [message("m1", null), message("m2", null), message("m3", "m1")];+ const { segments, laneX } = layoutGitGraph(messages);+ expect(segments.map((segment) => segment.lane)).toEqual([0, 1]);+ expect(laneX).toHaveLength(2);+ expect(laneX[1]).toBeGreaterThan(laneX[0] ?? 0);+ });+});++describe("rows", () => {+ it("marks the first row of each branch and falls back to the message title as its summary", () => {+ const branch = { title: "Scaffold", asked: "How?", outcome: "Done.", open: "" };+ const messages = [+ message("m1", null),+ message("m2", "m1", { branch }),+ message("m3", "m2"),+ message("m4", "m1", { summary: "A second thread" }),+ message("m5", "m4"),+ ];+ const { layout } = rowsOf(messages);+ const rows = layout.rows.filter((row): row is GitMessageRow => row.kind === "message");+ expect(rows.map((row) => row.first)).toEqual([true, true, false, true, false]);+ expect(layout.segments[1]?.branch).toMatchObject({+ title: "Scaffold",+ asked: "How?",+ outcome: "Done.",+ count: 2,+ });+ expect(layout.segments[2]?.branch).toMatchObject({+ title: "Message m4",+ outcome: "A second thread",+ count: 2,+ });+ });++ it("folds a long branch to first / ⋮ N more / last, unless it holds HEAD or is unfolded", () => {+ const chain = [message("m1", null)];+ for (let n = 2; n <= FOLD_LIMIT + 2; n += 1) chain.push(message(`m${n}`, `m${n - 1}`));+ const head = message("h1", null);++ const folded = layoutGitGraph([...chain, head]);+ const firstRows = folded.rows.filter((row) => row.segmentId === "m1");+ expect(firstRows.map((row) => (row.kind === "more" ? "more" : row.message.id))).toEqual([+ "m1",+ "more",+ `m${FOLD_LIMIT + 2}`,+ ]);+ const more = firstRows[1];+ expect(more?.kind === "more" && more.hidden).toHaveLength(FOLD_LIMIT);++ const unfolded = layoutGitGraph([...chain, head], { unfolded: new Set(["m1"]) });+ expect(unfolded.rows.filter((row) => row.segmentId === "m1")).toHaveLength(FOLD_LIMIT + 2);++ const openAll = layoutGitGraph([...chain, head], { openAll: true });+ expect(openAll.rows.filter((row) => row.segmentId === "m1")).toHaveLength(FOLD_LIMIT + 2);++ const onHead = layoutGitGraph(chain);+ expect(onHead.rows.some((row) => row.kind === "more")).toBe(false);+ });++ it("gives a new root a gap above its first row", () => {+ const { layout } = rowsOf([message("m1", null), message("m2", "m1"), message("m3", null)]);+ const rows = layout.rows.filter((row): row is GitMessageRow => row.kind === "message");+ expect(rows.map((row) => row.gap)).toEqual([false, false, true]);+ const between = rows[2]!.y - rows[1]!.y;+ expect(between).toBe(ROW_HEIGHT + ROOT_GAP);+ });++ 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(+ (row): row is GitMessageRow => row.kind === "message",+ );+ expect(rows.map((row) => row.head)).toEqual([false, false, true]);+ const overridden = layoutGitGraph(messages, { headId: "m2" }).rows.filter(+ (row): row is GitMessageRow => row.kind === "message",+ );+ expect(overridden.map((row) => row.head)).toEqual([false, true, false]);+ });+});++describe("returns", () => {+ it("routes each return through its own channel left of every lane", () => {+ const messages = [+ message("m1", null),+ message("m2", "m1"),+ message("m3", "m2", { links: ["m1"] }),+ message("m4", "m3", { links: ["m2"] }),+ ];+ const { layout } = rowsOf(messages);+ expect(layout.links.map((link) => link.channelX)).toEqual([6, 18]);+ expect(layout.links.map((link) => link.toId)).toEqual(["m1", "m2"]);+ expect(Math.max(...layout.links.map((link) => link.channelX))).toBeLessThan(+ layout.laneX[0] ?? 0,+ );++ const link = layout.links[0]!;+ const path = linkPath(link, 40, 60);+ expect(path).toContain(`M40,${link.toY}`);+ expect(path.endsWith(`L51,${link.fromY}`)).toBe(true);+ expect(linkArrow(link, 60)).toContain(`M45,${link.fromY - 4}`);+ });++ it("marks the returning row and colours it like the branch it returns to", () => {+ const messages = [+ message("m1", null),+ message("m2", "m1"),+ message("m3", null),+ message("m4", "m2", { links: ["m1"] }),+ ];+ const { layout } = rowsOf(messages);+ const row = layout.rows.find(+ (candidate): candidate is GitMessageRow =>+ candidate.kind === "message" && candidate.message.id === "m4",+ );+ expect(row?.returns).toEqual([{ id: "m1", colorIndex: 0 }]);+ });+});diff --git a/packages/template/test/graph.test.ts b/packages/template/test/graph.test.tsindex c2d7d9b..ee73345 100644--- a/packages/template/test/graph.test.ts+++ b/packages/template/test/graph.test.ts@@ -1,71 +1,84 @@import { describe, expect, it } from "vitest";-import type { ViewNode } from "../../cli/src/view/model.js";+import type { LineageViewModel, ViewNode } from "../../cli/src/view/model.js";import {absolutePosition,+ layoutGraph,messageNeighbors,- placeSessionNodes,- TREE_LEFT,+ sessionId,toNodeDetail,} from "../src/graph.js";-function node(id: string, children: ViewNode[] = []): ViewNode {- return { id, kind: "phase", title: id, children };-}--describe("placeSessionNodes", () => {- const tree = [node("a", [node("a1"), node("a2", [node("a2x")])]), node("b", [node("b1")])];- const { boxes, edges, width, height } = placeSessionNodes(tree, "s");- const box = (id: string) => boxes.get(`node:s:${id}`);-- it("puts top-level topics side by side in one row", () => {- expect(box("a")?.y).toBe(box("b")?.y);- expect(box("b")?.x).toBeGreaterThan((box("a2x")?.x ?? 0) + (box("a2x")?.width ?? 0));- });-- it("lists a topic's items below it in recorded order, indented by depth", () => {- const column = ["a", "a1", "a2", "a2x"].map((id) => box(id)?.y ?? -1);- expect(column).toEqual([...column].sort((x, y) => x - y));- expect(new Set(column).size).toBe(column.length);- expect(box("a1")?.x).toBeGreaterThan(box("a")?.x ?? 0);- expect(box("a2x")?.x).toBeGreaterThan(box("a2")?.x ?? 0);- expect(width).toBeGreaterThan((box("b1")?.x ?? 0) + (box("b1")?.width ?? 0));- expect(height).toBeGreaterThan((box("a2x")?.y ?? 0) + (box("a2x")?.height ?? 0));- });-- it("hangs items off their parent and never links parallel topics", () => {- const link = (from: string, to: string) =>- edges.find((e) => e.source === `node:s:${from}` && e.target === `node:s:${to}`);- expect(link("a", "a1")?.targetHandle).toBe(TREE_LEFT);- expect(link("a2", "a2x")?.targetHandle).toBe(TREE_LEFT);- expect(link("a", "b")).toBeUndefined();- expect(edges).toHaveLength(4);- });-- it("hides the children of a closed topic and narrows its column", () => {- const closed = placeSessionNodes(tree, "s", (id) => id !== "node:s:a");- expect(closed.boxes.has("node:s:a1")).toBe(false);- expect(closed.boxes.has("node:s:b1")).toBe(true);- expect(closed.boxes.get("node:s:b")?.x).toBeLessThan(box("b")?.x ?? 0);- expect(closed.edges.map((e) => e.target)).toEqual(["node:s:b1"]);- });+const AT = "2026-10-21T10:00:00.000Z";- it("gives an empty session a minimal box", () => {- expect(placeSessionNodes([], "s").boxes.size).toBe(0);- });+function message(id: string, at = AT, parent: string | null = null): ViewNode {+ return { id, kind: "message", title: id, at, parent };+}- it("makes room for the left-off badge on the last touched card", () => {- const marked = placeSessionNodes(tree, "s", undefined, new Set(["node:s:a1"]));- expect(marked.boxes.get("node:s:a1")?.height).toBeGreaterThan(box("a1")?.height ?? 0);+const model: LineageViewModel = {+ kind: "lineage",+ schema: 1,+ project: { name: "p", path: "/tmp/p", generatedAt: AT },+ status: { goal: "", done: [], pending: [], next: "", lastActivity: null },+ epochs: [+ {+ id: "e1",+ title: "Epoch one",+ createdAt: AT,+ sessions: [+ {+ sessionId: "s1",+ agent: "claude-code",+ title: "One",+ epoch: "e1",+ startedAt: AT,+ updatedAt: AT,+ status: { goal: "", done: [], pending: [], next: "" },+ messages: [message("m1"), message("m2", "2026-10-21T10:01:00.000Z", "m1")],+ transcriptAvailable: true,+ },+ {+ sessionId: "s2",+ agent: "claude-code",+ title: "Two",+ epoch: "e1",+ startedAt: "2026-10-20T10:00:00.000Z",+ updatedAt: "2026-10-20T11:00:00.000Z",+ status: { goal: "", done: [], pending: [], next: "" },+ messages: [],+ transcriptAvailable: true,+ },+ ],+ },+ ],+ unassigned: [],+};++describe("layoutGraph", () => {+ it("gives an open session its git layout and leaves a closed one empty", async () => {+ const expanded = new Set(["epoch:e1", "session:s1"]);+ const layout = await layoutGraph(model, expanded);+ const session = layout.nodes.find((node) => node.id === "session:s1");+ const closed = layout.nodes.find((node) => node.id === "session:s2");+ expect(session?.type).toBe("session");+ if (session?.type === "session") {+ expect(session.data.git?.rows).toHaveLength(2);+ expect(session.width).toBeGreaterThanOrEqual(session.data.git?.width ?? 0);+ expect(session.height).toBeGreaterThan(56);+ }+ if (closed?.type === "session") {+ expect(closed.data.git).toBeUndefined();+ expect(closed.height).toBe(56);+ }});- it("makes room for the not-summarized badge, even on the last touched card", () => {- const card: ViewNode = { id: "m1", kind: "message", title: "Hi", children: [] };- const pending: ViewNode = { ...card, unsummarized: true, at: "2026-10-23T10:00:00.000Z" };- const plainHeight = placeSessionNodes([card], "s").boxes.get("node:s:m1")?.height ?? 0;- const pendingHeight = placeSessionNodes([pending], "s").boxes.get("node:s:m1")?.height ?? 0;- expect(pendingHeight).toBeGreaterThan(plainHeight);- const both = placeSessionNodes([pending], "s", undefined, new Set(["node:s:m1"]));- expect(both.boxes.get("node:s:m1")?.height).toBeGreaterThan(pendingHeight);+ it("puts every session of an open epoch under it and emits no message nodes", async () => {+ const layout = await layoutGraph(model, new Set(["epoch:e1"]));+ expect(layout.nodes.map((node) => node.type)).toEqual(["epoch", "session", "session"]);+ expect(+ layout.nodes+ .filter((node) => node.type === "session")+ .every((n) => n.parentId === "epoch:e1"),+ ).toBe(true);});});@@ -89,34 +102,32 @@ describe("absolutePosition", () => {});describe("messageNeighbors", () => {- const message = (id: string, at?: string): ViewNode => ({- id,- kind: "message",- title: id,- children: [],- ...(at ? { at } : {}),- });- const tree: ViewNode[] = [- {- ...node("a"),- children: [message("m3", "2026-01-01T03:00:00Z"), message("m1", "2026-01-01T01:00:00Z")],- },- { ...node("b"), children: [message("m2", "2026-01-01T02:00:00Z"), message("mx")] },+ const messages = [+ message("m1", "2026-01-01T01:00:00Z"),+ message("m2", "2026-01-01T02:00:00Z"),+ message("m3", "2026-01-01T03:00:00Z"),];- it("finds the messages before and after, by send time across topics", () => {- const { previous, next } = messageNeighbors(tree, "m2");+ it("finds the messages before and after in send order", () => {+ const { previous, next } = messageNeighbors(messages, "m2");expect([previous?.id, next?.id]).toEqual(["m1", "m3"]);- expect(messageNeighbors(tree, "m3").next).toBeNull();+ expect(messageNeighbors(messages, "m3").next).toBeNull();+ expect(messageNeighbors(messages, "m1").previous).toBeNull();});- it("returns nothing for a node that is not a message", () => {- expect(messageNeighbors(tree, "a")).toEqual({ previous: null, next: null });+ it("returns nothing for an id the session does not have", () => {+ expect(messageNeighbors(messages, "gone")).toEqual({ previous: null, next: null });});});describe("toNodeDetail", () => {it("keeps the node's own id next to its session", () => {- expect(toNodeDetail(node("x"), "s1")).toMatchObject({ nodeId: "x", sessionId: "s1" });+ expect(toNodeDetail(message("m1"), "s1")).toMatchObject({ nodeId: "m1", sessionId: "s1" });+ });+});++describe("sessionId", () => {+ it("prefixes the React Flow session group id", () => {+ expect(sessionId("abc")).toBe("session:abc");});});diff --git a/packages/template/test/outline.test.ts b/packages/template/test/outline.test.tsindex c07106b..dc41625 100644--- a/packages/template/test/outline.test.ts+++ b/packages/template/test/outline.test.ts@@ -1,15 +1,15 @@import { describe, expect, it } from "vitest";import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";-import { defaultExpanded, lastTouched } from "../src/graph.js";+import { defaultExpanded, headOf, sessionGroupId } from "../src/graph.js";import { outlinePath } from "../src/Outline.js";const AT = "2026-10-21T10:00:00.000Z";-function node(id: string, title: string, children: ViewNode[] = []): ViewNode {- return { id, kind: "step", title, children };+function message(id: string, at = AT, parent: string | null = null): ViewNode {+ return { id, kind: "message", title: id, at, parent };}-function session(id: string, epoch: string | null, nodes: ViewNode[]): ViewSession {+function session(id: string, epoch: string | null, messages: ViewNode[]): ViewSession {return {sessionId: id,agent: "claude-code",@@ -18,7 +18,7 @@ function session(id: string, epoch: string | null, nodes: ViewNode[]): ViewSessistartedAt: AT,updatedAt: AT,status: { goal: "", done: [], pending: [], next: "" },- nodes,+ messages,transcriptAvailable: true,};}@@ -33,7 +33,9 @@ const model: LineageViewModel = {id: "e1",title: "Epoch one",createdAt: AT,- sessions: [session("s1", "e1", [node("n1", "A", [node("n2", "B")]), node("n3", "C")])],+ sessions: [+ session("s1", "e1", [message("m1"), message("m2", "2026-10-21T10:01:00.000Z", "m1")]),+ ],},],unassigned: [session("u1", null, [])],@@ -48,13 +50,8 @@ describe("outlinePath", () => {expect(outlinePath(model, "session:s1")).toEqual(["epoch:e1"]);});- it("returns every ancestor of a nested node, including the node itself", () => {- expect(outlinePath(model, "node:session:s1:n2")).toEqual([- "epoch:e1",- "session:s1",- "node:session:s1:n1",- "node:session:s1:n2",- ]);+ it("returns the epoch and session for a message row", () => {+ expect(outlinePath(model, "node:session:s1:m2")).toEqual(["epoch:e1", "session:s1"]);});it("places unassigned sessions under the unassigned group", () => {@@ -63,12 +60,12 @@ describe("outlinePath", () => {it("returns null for an id outside the model", () => {expect(outlinePath(model, "session:missing")).toBeNull();+ expect(outlinePath(model, "node:session:s1:gone")).toBeNull();});});-describe("lastTouched", () => {- const touched = (n: ViewNode, at: string): ViewNode => ({ ...n, touchedAt: at });- const withTouches: LineageViewModel = {+describe("headOf", () => {+ const latest: LineageViewModel = {...model,epochs: [{@@ -78,8 +75,8 @@ describe("lastTouched", () => {sessions: [{...session("s1", "e1", [- touched(node("n1", "A", [touched(node("n2", "B"), "2026-10-21T12:00:00.000Z")]), AT),- touched(node("n3", "C"), "2026-10-21T11:00:00.000Z"),+ message("m1"),+ message("m2", "2026-10-21T10:01:00.000Z", "m1"),]),updatedAt: "2026-10-22T00:00:00.000Z",},@@ -88,34 +85,29 @@ describe("lastTouched", () => {],};- it("finds the newest touched node in the latest session, with the branch above it", () => {- expect(lastTouched(withTouches)).toEqual({+ it("marks the newest message of the most recently updated session", () => {+ expect(headOf(latest)).toEqual({sessionKey: "session:s1",- nodeKeys: ["node:session:s1:n2"],- ancestors: ["epoch:e1", "session:s1", "node:session:s1:n1"],+ sessionId: "s1",+ messageId: "m2",+ group: "epoch:e1",});- expect(defaultExpanded(withTouches).has("node:session:s1:n1")).toBe(true);+ expect(defaultExpanded(latest)).toEqual(new Set(["epoch:e1", "session:s1"]));});- it("marks every node of the last write when several share the newest time", () => {- const tie = structuredClone(withTouches);- const s1 = tie.epochs[0]?.sessions[0];- if (s1?.nodes[1]) s1.nodes[1].touchedAt = "2026-10-21T12:00:00.000Z";- expect(lastTouched(tie)?.nodeKeys).toEqual(["node:session:s1:n2", "node:session:s1:n3"]);+ it("has no message for a session without any, and is null for an empty map", () => {+ expect(+ headOf({+ ...latest,+ epochs: [{ ...latest.epochs[0]!, sessions: [session("s2", "e1", [])] }],+ }),+ ).toMatchObject({ sessionKey: "session:s2", messageId: null });+ expect(headOf({ ...latest, epochs: [], unassigned: [] })).toBeNull();});- it("marks only the last user message once the session has messages", () => {- const withMessages = structuredClone(withTouches);- const s1 = withMessages.epochs[0]?.sessions[0];- s1?.nodes[0]?.children.push(- { ...node("m1", "First"), kind: "message", at: "2026-10-21T10:30:00.000Z", touchedAt: AT },- { ...node("m2", "Second"), kind: "message", at: "2026-10-21T10:40:00.000Z", touchedAt: AT },- );- expect(lastTouched(withMessages)?.nodeKeys).toEqual(["node:session:s1:m2"]);- });-- it("is empty when nothing has a touch time yet", () => {- expect(lastTouched(model)).toBeNull();- expect(lastTouched({ ...model, epochs: [], unassigned: [] })).toBeNull();+ it("finds the epoch group of a session", () => {+ expect(sessionGroupId(latest, "s1")).toBe("epoch:e1");+ expect(sessionGroupId(model, "u1")).toBe("unassigned");+ expect(sessionGroupId(latest, "gone")).toBeNull();});});diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.mdindex 168fba5..b2b04d6 100644--- a/specs/codelineage-mvp.md+++ b/specs/codelineage-mvp.md@@ -17,25 +17,29 @@ The agent itself records a structured summary of its session as it works. A CLIthese records into static HTML:- **Project map** (one per project): project → epoch (feature/epic) → session →- topic → sub-topics (any depth) → the user's messages. The map is a minimap of- the chat: one node per message the user wrote, titled in the user's words and- saying what came of it; the agent's work on it (steps, its own decisions with- their reasons, commits, files) lives in that node's detail, not in nodes of its- own. It opens like layers of an onion: time runs down the page (sessions in- order), a session's top-level topics sit side by side as columns ordered by when- they began, and an opened topic lists its messages down its column in the order- the user sent them. Every node with children expands and collapses; the latest- session opens with its topics closed except the branch to its last message,- which is marked "left off here". Cards size themselves to their text. A click- opens a drill-down panel with the full text, who decided, the options considered- and rejected, what the agent did and decided on its own, the commits and files,- the conversation itself (the message as written and the agent's written- replies, tool output left out and tool use counted), previous/next message- buttons, and a `claude --resume <id>` copy button. `build` reads the- conversation from the transcript into `lineage.html` only (never committed, see- Privacy); session files never hold raw text. Records from before messages became- the nodes keep their step/decision/question nodes and their old "left off"- mark (the nodes of the last write).+ a git graph of the user's messages. The map is a minimap of the chat: one row+ per message the user wrote, in the order they sent it, titled in the user's+ words and saying what came of it; the agent's work on it (steps, its own+ decisions with their reasons, commits, files) lives in that row's detail, not+ in rows of its own. Each session draws like a git history: one dot per message,+ one coloured lane per branch (a branch is a chain of messages that react to+ each other one to one), the first message of a branch a hollow ring with the+ branch title, a branch start curving out of the message it reacts to, and a+ return (`links`) a dashed arrow through a channel left of the lanes, marked+ "↩ m22" on the row. A new root starts after a small gap. A branch longer than+ four messages folds to its first and last message plus a "⋮ N more" row that+ unfolds it; "Unfold all" opens every branch at once. The newest branch (where+ "left off here" marks the newest message) starts unfolded. Sessions keep their+ place in the project map; time runs down the page. A click opens a drill-down+ panel with the branch summary (title, range, count, time span, asked / outcome+ / open), the full text, who decided, the options considered and rejected, what+ the agent did and decided on its own, the commits and files, the conversation+ itself (the message as written and the agent's written replies, tool output+ left out and tool use counted), previous/next message buttons, and a+ `claude --resume <id>` copy button. `build` reads the conversation from the+ transcript 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.- **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@@ -109,13 +113,15 @@ and `session write` sets a message's `at` from the transcript. Tool results,injected skill text, compaction summaries, subagent turns, `!` shell lines andslash commands without arguments are not messages. Raw message text never entersthe record, only the agent's title and summary. `step`, `decision` and `question`-are kept for records written before messages became the nodes. Nodes are grouped by topic, not by time, and nest to any depth through-`parent`. `decidedBy` is `user | agent | agreed`. `addedAt` (first write) and-`touchedAt` (last change) are stamped by `session write` and never taken from agent-input; a resent node that changed nothing keeps its `touchedAt`. Siblings are-ordered by when their thread began (the earliest start in their subtree: a-message's `at`, any other node's `addedAt`);-nodes recorded before the stamps existed keep their stored order, first. Epochs live in `project.json`.+are kept for records written before messages became the nodes. A message's+`parent` is the earlier message it reacts to (or `null` for a new root); a parent+that is not an earlier message falls back to the previous message, so old records+chain in send order. `links` (up to five) name older messages the message returns+to besides its parent, and `branch` (title, asked, outcome, open) sits on the+first message of a branch, written when the branch ends rather than every turn.+`decidedBy` is `user | agent | agreed`. `addedAt` (first write) and `touchedAt`+(last change) are stamped by `session write` and never taken from agent input; a+resent node that changed nothing keeps its `touchedAt`. Epochs live in `project.json`.The agent picks an existing epoch or adds one through the CLI (`codelineage epoch add`),which does a locked, atomic write.@@ -227,7 +233,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 open topics, selection and zoom. Falls back to opening the file when the server cannot start. |+| `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 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") |