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 the project as a git graph of sessions
Erenfef656a2bcce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 01abf4d..b43b447 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- The project map's top level is a git graph of sessions: one dot per session, titled with the session, hanging from the session its first message continues, with parallel lanes for sessions that run at the same time without a link and the epoch shown as a tag on the dot. Clicking a dot opens that session's message graph in place (a "← All sessions" control returns), and the session panel shows its status as a "squash message" (goal, done, pending, next). The epoch and session boxes and the `elkjs` layout are gone; both levels use the same layout engine. Live rebuilds keep the open session, selection and viewport.- The conversation store: `build` appends what the drill-down needs for turns not stored yet to `.codelineage/conversations/<sessionId>.jsonl.gz` (one gzip member per append, redacted with the same secret net as the page), reads it before the transcript, and keeps showing a session's conversation after Claude Code deletes the transcript. `init` writes `.codelineage/.gitignore` with `conversations/` even when `.codelineage/` is committed, an existing project gets the line on its next build, and the README explains where the raw chat lives. Stored turns keep the message's stable id, so ids survive the transcript.- Stable message ids: a message node is now `h` + the first 12 hex of the SHA-256 over `{sessionId, uuid, at, text}`, derived from the user message and not from its parent, so correcting a parent never renames a message (and its notes stay attached). `m1`, `m2`, … stay as display labels; `session show` prints both and `session write` accepts either. Records written before this are renamed on load and persisted on their next write.- Structure as append-only facts: each session gets `sessions/<sessionId>.events.jsonl` (`{ at, type: parent|link|unlink, msg, target, by }`), replayed to build the graph (last parent wins). Notes stay in the session JSON keyed by the stable id and may be updated freely. A changed parent or link appends an event instead of overwriting; unchanged input writes nothing, and an old record's existing structure is seeded before its first change. The hidden `codelineage migrate [dir]` upgrades a project's old records in one go (idempotent, backup in `.codelineage/backup-pre-8.5/`).diff --git a/package-lock.json b/package-lock.jsonindex 250a32a..98cf3ac 100644--- a/package-lock.json+++ b/package-lock.json@@ -2700,12 +2700,6 @@"node": ">=8"}},- "node_modules/elkjs": {- "version": "0.12.0",- "resolved": "https://registry.npmjs.org/elkjs/-/elkjs-0.12.0.tgz",- "integrity": "sha512-YZcKynxVxYoKIOEpywEPwCFdg+BTbxQRNf3pbwdDCvc8O3kQD8bmIwSxKU1eOTVc4Xo+VG9Te+575mlfvOrhEQ==",- "license": "EPL-2.0 OR GPL-3.0-or-later"- },"node_modules/es-module-lexer": {"version": "2.3.2","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",@@ -4044,7 +4038,7 @@},"packages/cli": {"name": "codelineage",- "version": "0.1.0",+ "version": "0.7.0","license": "MIT","bin": {"codelineage": "dist/cli.js"@@ -4073,7 +4067,6 @@"version": "0.0.0","dependencies": {"@xyflow/react": "^12.12.0",- "elkjs": "^0.12.0","react": "^19.3.1","react-dom": "^19.3.1"},diff --git a/packages/template/package.json b/packages/template/package.jsonindex 7f9032b..8de85ed 100644--- a/packages/template/package.json+++ b/packages/template/package.json@@ -10,7 +10,6 @@},"dependencies": {"@xyflow/react": "^12.12.0",- "elkjs": "^0.12.0","react": "^19.3.1","react-dom": "^19.3.1"},diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsxindex 10b9f1e..9c3773b 100644--- a/packages/template/src/GitGraph.tsx+++ b/packages/template/src/GitGraph.tsx@@ -213,7 +213,7 @@ export function GitGraph({);})}</svg>- <div className="git-rows" style={{ left: git.graphWidth + 8 }}>+ <div className="git-rows" style={{ left: git.graphWidth + 8, width: git.rowWidth }}>{git.rows.map((row) => {const branch = branches.get(row.segmentId);return (diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsxindex 6b1089f..abb8f70 100644--- a/packages/template/src/Graph.tsx+++ b/packages/template/src/Graph.tsx@@ -1,363 +1,150 @@import {Background,Controls,- Handle,MiniMap,- type NodeMouseHandler,+ type Node,type NodeProps,type NodeTypes,- Position,ReactFlow,ReactFlowProvider,useReactFlow,} from "@xyflow/react";import "@xyflow/react/dist/style.css";-import {- createContext,- type ReactNode,- useCallback,- useContext,- useEffect,- useMemo,- useRef,- useState,-} from "react";-import type { LineageViewModel } from "../../cli/src/view/model.js";-import { formatDate, formatTime } from "./format.js";+import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";+import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.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,- headOf,- layoutGraph,- nodeId,- SESSION_GROUP_HEADER,- type SessionFlowNode,- sessionId as sessionKey,-} from "./graph.js";-import { Outline, type OutlineTarget, outlinePath } from "./Outline.js";+import { type GitLayout, layoutGitGraph } from "./gitLayout.js";+import { headOf } from "./graph.js";+import { Outline, type OutlineTarget } from "./Outline.js";+import { SessionMap } from "./SessionMap.js";import { DrillDown, type Selection } from "./SidePanel.js";+import { layoutSessionGraph, type SessionGraph } from "./sessionLayout.js";++/**+ * The project map (Story 8.7). Level one: the sessions as a git graph, one dot+ * each. Level two: the clicked session's messages as their git graph (8.2), in+ * place, with a back control. Both levels share the same layout engine.+ */-/** 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;- /** Opens another session at one of its messages (a "continues" mark, 8.6). */+ selection: Selection | null;+ openSession: (sessionId: string) => void;+ openNode: (sessionId: string, messageId: string, branchId?: string) => void;openContinue: (sessionId: string, messageId: string) => void;unfold: (segmentId: string) => void;- selection: Selection | null;}>({- toggle: () => {},- openRow: () => {},+ selection: null,+ openSession: () => {},+ openNode: () => {},openContinue: () => {},unfold: () => {},- selection: null,});-function GroupToggle({- id,- data,-}: {- id: string;- data: { expanded: boolean; hasChildren: boolean };-}) {- const { toggle } = useContext(GraphActions);- if (!data.hasChildren) return <span className="group-toggle is-empty">·</span>;- return (- <button- type="button"- className="group-toggle"- aria-expanded={data.expanded}- aria-label={data.expanded ? "Collapse" : "Expand"}- onClick={(event) => {- event.stopPropagation();- toggle(id);- }}- >- {data.expanded ? "▾" : "▸"}- </button>- );-}+type ProjectData = { model: LineageViewModel; graph: SessionGraph };+type MessagesData = { session: ViewSession; git: GitLayout };-/** Edges need handles; they are invisible because the layout owns the geometry. */-function AnchorHandles() {- return (- <>- <Handle type="target" position={Position.Top} className="flow-handle" isConnectable={false} />- <Handle- type="source"- position={Position.Bottom}- className="flow-handle"- isConnectable={false}- />- </>- );-}+type ProjectFlowNode = Node<ProjectData, "project">;+type MessagesFlowNode = Node<MessagesData, "messages">;+type MapFlowNode = ProjectFlowNode | MessagesFlowNode;-function EpochNode({ id, data }: NodeProps<EpochFlowNode>) {+function ProjectBox({ data }: NodeProps<ProjectFlowNode>) {+ const { openSession, openContinue, selection } = useContext(GraphActions);return (- <div className="flow-group epoch-group">- <AnchorHandles />- <div className="group-head">- <GroupToggle id={id} data={data} />- <strong className="group-title">{data.title}</strong>- <span className="muted">- {data.count} session{data.count === 1 ? "" : "s"}- </span>- </div>+ <div className="map-node">+ <SessionMap+ model={data.model}+ graph={data.graph}+ selectedSessionId={selection?.sessionId ?? null}+ onOpen={openSession}+ onContinue={openContinue}+ /></div>);}-function SessionNode({ id, data }: NodeProps<SessionFlowNode>) {- const { selection, openRow, openContinue, 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;+function MessagesBox({ data }: NodeProps<MessagesFlowNode>) {+ const { selection, openNode, openContinue, unfold } = useContext(GraphActions);+ const own = selection?.sessionId === data.session.sessionId;return (- <div className="flow-group session-group" title={data.goal || data.title}>- <AnchorHandles />- <div className="group-head">- <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>- {data.git ? (- <GitGraph- git={data.git}- selectedId={selectedId}- activeSegmentId={activeSegmentId}- onSelect={(row: GitMessageRow) => openRow(data.sessionId, row.message.id, row.segmentId)}- onUnfold={unfold}- onContinue={(target) => openContinue(target.sessionId, target.id)}- />- ) : null}+ <div className="map-node">+ <GitGraph+ git={data.git}+ selectedId={selection?.type === "node" && own ? selection.nodeId : null}+ activeSegmentId={selection?.type === "node" && own ? (selection.branchId ?? null) : null}+ onSelect={(row) => openNode(data.session.sessionId, row.message.id, row.segmentId)}+ onUnfold={unfold}+ onContinue={(continues) => openContinue(continues.sessionId, continues.id)}+ /></div>);}const nodeTypes: NodeTypes = {- epoch: EpochNode,- session: SessionNode,+ project: ProjectBox,+ messages: MessagesBox,};-/** React Flow overlays get their colours from the node type, not the kind. */-function minimapColor(node: GraphNode): string {- return node.type === "epoch" ? "#2b3446" : "#243040";+function findSession(model: LineageViewModel, id: string): ViewSession | undefined {+ for (const epoch of model.epochs) {+ const session = epoch.sessions.find((candidate) => candidate.sessionId === id);+ if (session) return session;+ }+ return model.unassigned.find((session) => session.sessionId === id);}function Flow({ model }: { model: LineageViewModel }) {- const [expanded, setExpanded] = useState<Set<string>>(() => defaultExpanded(model));+ const [openId, setOpenId] = useState<string | null>(null);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);- // Open on the session where the work left off, framed around it.- 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(- pendingFocus.current ? performance.now() : Number.NEGATIVE_INFINITY,- );- /** The first run belongs to mount; only React to the user toggling the outline. */- const firstOutlineToggle = useRef(true);- const { fitView, getViewport, setViewport } = useReactFlow();- /** The box the user just opened or closed, and where it was, so it stays put on screen. */- const anchor = useRef<{ id: string; at: { x: number; y: number } } | null>(null);- /** Only the first layout frames the whole map; later ones keep the user's zoom. */- const framed = useRef(false);- const scheduleFocus = useCallback(- (id: string) => {- if (focusTimer.current !== null) window.clearTimeout(focusTimer.current);- focusTimer.current = window.setTimeout(() => {- focusTimer.current = null;- void fitView({ nodes: [{ id }], padding: 0.6, duration: 300, maxZoom: 1.2 });- }, 80);- },- [fitView],- );-- useEffect(- () => () => {- if (focusTimer.current !== null) window.clearTimeout(focusTimer.current);- },- [],- );+ const openSession = openId === null ? undefined : findSession(model, openId);+ const head = headOf(model);+ const sessionGraph = useMemo(() => layoutSessionGraph(model), [model]);- /** 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, { unfolded, openAll })- .then((result) => {- if (cancelled) return;- setLayout(result);- const held = anchor.current;- anchor.current = null;- const now = held ? absolutePosition(result.nodes, held.id) : null;- if (held && now) {- // Shift the view by as much as the box moved, so content opens below it.- const { x, y, zoom } = getViewport();- void setViewport({- x: x - (now.x - held.at.x) * zoom,- y: y - (now.y - held.at.y) * zoom,- zoom,- });- }- // 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;- focusInitial(result, focus);- }- })- .catch((err: unknown) => {- if (cancelled) return;- setError(err instanceof Error ? err.message : String(err));- });- return () => {- cancelled = true;- };- }, [model, expanded, unfolded, openAll, centerRow, focusInitial, getViewport, setViewport]);+ const messageGit = useMemo(() => {+ if (!openSession) return null;+ return layoutGitGraph(openSession.messages, {+ unfolded,+ openAll,+ headId: head?.sessionId === openSession.sessionId ? head.messageId : null,+ });+ }, [openSession, head?.sessionId, head?.messageId, unfolded, openAll]);- useEffect(() => {- if (!layout || framed.current) return;- framed.current = true;- if (performance.now() - lastFocusRequest.current < 1000) return;- const timer = setTimeout(() => {- void fitView({ padding: 0.15, duration: 200 });- }, 60);- return () => clearTimeout(timer);- }, [layout, fitView]);+ /** Row the view centres on when a session opens: its newest message (HEAD). */+ const focusRow = useMemo(() => {+ if (!openSession || !messageGit || head?.sessionId !== openSession.sessionId) return null;+ const row = messageGit.rows.find(+ (candidate) => candidate.kind === "message" && candidate.message.id === head.messageId,+ );+ return row ? { x: messageGit.graphWidth / 2, y: row.y } : null;+ }, [openSession, messageGit, head?.sessionId, head?.messageId]);- // Opening or closing the outline changes the canvas width, so re-frame the map.- useEffect(() => {- if (firstOutlineToggle.current) {- firstOutlineToggle.current = false;- return;- }- const timer = setTimeout(() => {- void fitView({ padding: 0.15, duration: 200 });- }, 80);- return () => clearTimeout(timer);- }, [showOutline, fitView]);+ const viewKey = openSession ? `session:${openSession.sessionId}` : "project";- const toggle = useCallback(- (id: string) => {- const at = layout ? absolutePosition(layout.nodes, id) : null;- anchor.current = at ? { id, at } : null;- setExpanded((previous) => {- const next = new Set(previous);- if (next.has(id)) next.delete(id);- else next.add(id);- return next;- });- },- [layout],- );- const openRow = useCallback((sessionIdValue: string, messageId: string, segmentId: string) => {- setFocusedId(nodeId(sessionKey(sessionIdValue), messageId));+ const openSessionAt = useCallback((sessionId: string) => {+ setOpenId(sessionId);+ setFocusedId(`session:${sessionId}`);+ setSelection({ type: "session", sessionId });+ }, []);+ const openNode = useCallback((sessionId: string, messageId: string, branchId?: string) => {+ setOpenId(sessionId);+ setFocusedId(`node:session:${sessionId}:${messageId}`);setSelection({type: "node",- sessionId: sessionIdValue,+ sessionId,nodeId: messageId,- branchId: segmentId,+ ...(branchId === undefined ? {} : { branchId }),});}, []);+ const openContinue = useCallback(+ (sessionId: string, messageId: string) => openNode(sessionId, messageId),+ [openNode],+ );const unfold = useCallback((segmentId: string) => {setUnfolded((previous) => {const next = new Set(previous);@@ -365,115 +152,84 @@ function Flow({ model }: { model: LineageViewModel }) {return next;});}, []);- const toggleUnfoldAll = useCallback(() => {- setOpenAll((value) => !value);- setUnfolded(new Set());+ const back = useCallback(() => {+ setOpenId(null);+ setSelection(null);+ setFocusedId(null);}, []);- const closePanel = useCallback(() => setSelection(null), []);- const toggleOutline = useCallback(() => setShowOutline((value) => !value), []);- const onNodeClick = useCallback<NodeMouseHandler<GraphNode>>((_event, node) => {- setFocusedId(node.id);- if (node.type === "session") {- setSelection({ type: "session", sessionId: node.data.sessionId });- }+ const selectFromOutline = useCallback((target: OutlineTarget) => {+ setFocusedId(target.focusId);+ setOpenId(target.sessionId);+ setSelection(target.selection);}, []);- /**- * 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) => {- 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);- return next;- });- 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 = rowTarget ? null : focusId;- pendingRow.current = rowTarget;- } else {- pendingFocus.current = null;- pendingRow.current = null;- const centered =- rowTarget !== null &&- layout !== null &&- centerRow(layout, rowTarget.sessionKey, rowTarget.messageId);- if (!centered) scheduleFocus(focusId);- }- },- [centerRow, expanded, layout, model, scheduleFocus],- );-- /** A "↑ continues …" mark opens the earlier session, revealed and centred. */- const openContinue = useCallback(- (targetSessionId: string, messageId: string) => {- const focus = nodeId(sessionKey(targetSessionId), messageId);- selectFromOutline({- focusId: focus,- expand: outlinePath(model, focus) ?? [sessionKey(targetSessionId)],- selection: { type: "node", sessionId: targetSessionId, nodeId: messageId },- });- },- [model, selectFromOutline],- );-const actions = useMemo(- () => ({ toggle, openRow, openContinue, unfold, selection }),- [toggle, openRow, openContinue, unfold, selection],+ () => ({ selection, openSession: openSessionAt, openNode, openContinue, unfold }),+ [selection, openSessionAt, openNode, openContinue, unfold],);- let content: ReactNode;- if (error) {- content = <p className="error graph-status">{error}</p>;- } else if (!layout) {- content = <p className="graph-status">Laying out the map…</p>;- } else if (layout.nodes.length === 0) {- content = <p className="graph-status empty">No sessions recorded yet.</p>;- } else {- content = (- <ReactFlow- nodes={layout.nodes}- edges={layout.edges}- nodeTypes={nodeTypes}- defaultEdgeOptions={{ style: { stroke: "#4f5b74", strokeWidth: 1.5 } }}- onNodeClick={onNodeClick}- fitView- panOnScroll- minZoom={0.05}- maxZoom={2}- nodesDraggable={false}- nodesConnectable={false}- elementsSelectable={false}- colorMode="dark"- >- <Background gap={24} size={1} color="#242a36" />- <MiniMap pannable zoomable nodeColor={minimapColor} />- <Controls showInteractive={false} />- </ReactFlow>- );- }+ const nodes = useMemo<MapFlowNode[]>(() => {+ if (openSession && messageGit) {+ return [+ {+ id: viewKey,+ type: "messages",+ position: { x: 0, y: 0 },+ width: messageGit.width,+ height: messageGit.height,+ style: { width: messageGit.width, height: messageGit.height },+ draggable: false,+ connectable: false,+ selectable: false,+ data: { session: openSession, git: messageGit },+ },+ ];+ }+ return [+ {+ id: "project",+ type: "project",+ position: { x: 0, y: 0 },+ width: sessionGraph.git.width,+ height: sessionGraph.git.height,+ style: { width: sessionGraph.git.width, height: sessionGraph.git.height },+ draggable: false,+ connectable: false,+ selectable: false,+ data: { model, graph: sessionGraph },+ },+ ];+ }, [openSession, messageGit, model, sessionGraph, viewKey]);return (<GraphActions.Provider value={actions}><div className={fullscreen ? "map-shell is-expanded" : "map-shell"}><div className="map-toolbar">+ {openSession ? (+ <button type="button" className="outline-button" onClick={back}>+ ← All sessions+ </button>+ ) : null}+ <span className="map-title" title={openSession?.title}>+ {openSession+ ? openSession.title || openSession.sessionId+ : `${sessionGraph.git.rows.length} session${+ sessionGraph.git.rows.length === 1 ? "" : "s"+ } · click a dot to open its messages`}+ </span>+ {openSession ? (+ <button+ type="button"+ className="outline-button"+ aria-pressed={openAll}+ onClick={() => {+ setOpenAll((value) => !value);+ setUnfolded(new Set());+ }}+ >+ {openAll ? "Fold all" : "Unfold all"}+ </button>+ ) : null}<buttontype="button"className="outline-button"@@ -482,19 +238,11 @@ 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"aria-pressed={showOutline}- onClick={toggleOutline}+ onClick={() => setShowOutline((value) => !value)}>{showOutline ? "Hide outline" : "Show outline"}</button>@@ -505,15 +253,21 @@ function Flow({ model }: { model: LineageViewModel }) {model={model}activeId={focusedId}onSelect={selectFromOutline}- onClose={toggleOutline}+ onClose={() => setShowOutline(false)}/>) : null}<div className="graph-canvas">- {content}+ {!openSession && sessionGraph.git.rows.length === 0 ? (+ <p className="graph-status empty">No sessions recorded yet.</p>+ ) : openSession && (messageGit?.rows.length ?? 0) === 0 ? (+ <p className="graph-status empty">No messages recorded in this session yet.</p>+ ) : (+ <MapCanvas key={viewKey} nodes={nodes} focusRow={focusRow} fitWhole={!openSession} />+ )}<DrillDownmodel={model}selection={selection}- onClose={closePanel}+ onClose={() => setSelection(null)}onNavigate={selectFromOutline}/></div>@@ -523,7 +277,63 @@ function Flow({ model }: { model: LineageViewModel }) {);}-/** Epoch → session map; each session draws its messages as a git graph. */+/**+ * One React Flow canvas per level (the `key` remounts it and reframes). A live+ * data swap keeps the level, so the viewport stays where the user left it.+ */+function MapCanvas({+ nodes,+ focusRow,+ fitWhole,+}: {+ nodes: MapFlowNode[];+ /** Point to centre on when a session opens; null fits the whole graph. */+ focusRow: { x: number; y: number } | null;+ /** Frame the whole graph instead of one row (the project level). */+ fitWhole: boolean;+}) {+ const { fitView, setViewport } = useReactFlow();++ useEffect(() => {+ const timer = window.setTimeout(() => {+ const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();+ if (!fitWhole && focusRow && canvas) {+ const zoom = 0.9;+ void setViewport({+ zoom,+ x: canvas.width / 2 - focusRow.x * zoom,+ y: canvas.height / 2 - focusRow.y * zoom,+ });+ return;+ }+ void fitView({ padding: fitWhole ? 0.12 : 0.15, maxZoom: 1, duration: 200 });+ }, 80);+ return () => window.clearTimeout(timer);+ // Mount only: the component is keyed by level, and a model swap must not refit.+ }, []);++ return (+ <ReactFlow+ nodes={nodes}+ edges={[]}+ nodeTypes={nodeTypes}+ fitView+ panOnScroll+ minZoom={0.05}+ maxZoom={2}+ nodesDraggable={false}+ nodesConnectable={false}+ elementsSelectable={false}+ colorMode="dark"+ >+ <Background gap={24} size={1} color="#242a36" />+ <MiniMap pannable zoomable nodeColor={() => "#243040"} />+ <Controls showInteractive={false} />+ </ReactFlow>+ );+}++/** The project map: sessions at the top, a session's messages in place. */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 7707d51..8a4f321 100644--- a/packages/template/src/Outline.tsx+++ b/packages/template/src/Outline.tsx@@ -6,15 +6,15 @@ import type { Selection } from "./SidePanel.js";/*** 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.+ * map. Selecting a row opens its session's message graph (or goes back to the+ * session graph for an epoch) and opens the same drill-down a map click would.*/export interface OutlineTarget {- /** React Flow node id to centre on. */+ /** The session to open; null returns the map to the session level. */+ sessionId: string | null;+ /** Highlight key: `epoch:…`, `session:…` or `node:…`. */focusId: string;- /** Graph group ids that must be expanded for `focusId` to exist. */- expand: string[];/** Drill-down content; `null` for epochs. */selection: Selection | null;}@@ -82,14 +82,12 @@ function ExpandToggle({}function SessionRow({- group,session,activeId,expanded,onToggle,onSelect,}: {- group: string;session: ViewSession;activeId: string | null;expanded: ReadonlySet<string>;@@ -113,8 +111,8 @@ function SessionRow({className={`outline-item${activeId === key ? " is-active" : ""}`}onClick={() =>onSelect({+ sessionId: session.sessionId,focusId: key,- expand: [group, key],selection: { type: "session", sessionId: session.sessionId },})}@@ -136,8 +134,8 @@ function SessionRow({className={`outline-item${activeId === id ? " is-active" : ""}`}onClick={() =>onSelect({+ sessionId: session.sessionId,focusId: id,- expand: [group, key],selection: {type: "node",sessionId: session.sessionId,@@ -236,7 +234,11 @@ export function Outline({type="button"className={`outline-item${activeId === group.id ? " is-active" : ""}`}onClick={() =>- onSelect({ focusId: group.id, expand: [group.id], selection: null })+ onSelect({+ sessionId: null,+ focusId: group.id,+ selection: null,+ })}><span className="label">{group.title}</span>@@ -248,7 +250,6 @@ export function Outline({{group.sessions.map((session) => (<SessionRowkey={session.sessionId}- group={group.id}session={session}activeId={activeId}expanded={expanded}diff --git a/packages/template/src/SessionMap.tsx b/packages/template/src/SessionMap.tsxnew file mode 100644index 0000000..63fa1b9--- /dev/null+++ b/packages/template/src/SessionMap.tsx@@ -0,0 +1,194 @@+import type { MouseEvent } from "react";+import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";+import { formatStamp } from "./format.js";+import { branchPath, type GitMessageRow, type GitRow, LANE_COLORS } from "./gitLayout.js";+import type { SessionGraph } from "./sessionLayout.js";++/**+ * Draws the project's sessions as a git graph (Story 8.7): one dot per session+ * in start order, lanes for branches of sessions, an epoch tag on each dot and+ * the session title as its label. Clicking a row opens that session's messages+ * in place. The geometry comes from `sessionLayout.ts`; this file only renders.+ */++function color(index: number): string {+ return `var(--l${index % LANE_COLORS})`;+}++/** A neutral, outlined epoch tag — deliberately unlike a branch label. */+function TagIcon() {+ return (+ <svg width="10" height="10" viewBox="0 0 16 16" aria-hidden="true" focusable="false">+ <path+ d="M2 2h5.2l6.3 6.3-5.2 5.2L2 7.2V2z"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.4"+ />+ <circle cx="5.2" cy="5.2" r="1.2" fill="currentColor" />+ </svg>+ );+}++function SessionRow({+ row,+ session,+ epochTitle,+ selected,+ onOpen,+ onContinue,+}: {+ row: GitMessageRow;+ session: ViewSession;+ epochTitle: string | null;+ selected: boolean;+ onOpen: (sessionId: string) => void;+ onContinue: (continues: NonNullable<ViewSession["messages"][number]["continues"]>) => void;+}) {+ const continues = session.messages[0]?.continues;+ const style = { top: row.y - row.height / 2, height: row.height };+ const count = session.messages.length;+ return (+ <button+ type="button"+ className={`git-row session-row${selected ? " is-selected" : ""}`}+ style={style}+ onClick={(event: MouseEvent) => {+ event.stopPropagation();+ onOpen(session.sessionId);+ }}+ title={session.status.goal || session.title}+ >+ <span className="git-time">{session.startedAt ? formatStamp(session.startedAt) : ""}</span>+ {epochTitle ? (+ <span className="epoch-tag" title={`Epoch: ${epochTitle}`}>+ <TagIcon />+ {epochTitle}+ </span>+ ) : null}+ <span className="git-title">{session.title || session.sessionId}</span>+ <span className="muted session-count">+ {count} message{count === 1 ? "" : "s"}+ </span>+ {session.unrecordedMessages ? (+ <span className="muted unrecorded" title="The SessionEnd catch-up is off">+ {session.unrecordedMessages} not recorded+ </span>+ ) : null}+ {continues ? (+ <span+ className="git-continues"+ title={`Open ${continues.sessionTitle} at ${continues.label ?? continues.id}`}+ onClick={(event: MouseEvent) => {+ event.stopPropagation();+ onContinue(continues);+ }}+ >+ ↑ continues {continues.sessionTitle} · {continues.label ?? continues.id}+ </span>+ ) : null}+ {row.head ? <span className="left-off">left off here</span> : null}+ </button>+ );+}++export function SessionMap({+ model,+ graph,+ selectedSessionId,+ onOpen,+ onContinue,+}: {+ model: LineageViewModel;+ graph: SessionGraph;+ selectedSessionId: string | null;+ onOpen: (sessionId: string) => void;+ onContinue: (sessionId: string, messageId: string) => void;+}) {+ const { git } = graph;+ const epochTitles = new Map(model.epochs.map((epoch) => [epoch.id, epoch.title]));+ const segments = new Map(git.segments.map((segment) => [segment.id, segment]));++ const open: (row: GitRow) => void = (row) => {+ if (row.kind === "message") onOpen(row.message.id);+ };++ return (+ <div className="git-graph session-map" 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];+ if (!previous) return null;+ return (+ <path+ key={`${row.segmentId}-${at}`}+ d={`M${x},${previous.y} L${x},${row.y}`}+ strokeWidth={2.5}+ />+ );+ })}+ </g>+ );+ })}+ {git.rows.map((row) => {+ if (row.kind !== "message") return null;+ const x = git.laneX[segments.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}+ className="session-dot"+ onClick={() => open(row)}+ />+ ) : (+ <circle+ key={row.message.id}+ cx={x}+ cy={row.y}+ r={4.5}+ fill={color(row.colorIndex)}+ className="session-dot"+ onClick={() => open(row)}+ />+ );+ })}+ </svg>+ <div className="git-rows" style={{ left: git.graphWidth + 8, width: git.rowWidth }}>+ {git.rows.map((row) => {+ const session = row.kind === "message" ? graph.sessions.get(row.message.id) : undefined;+ if (row.kind !== "message" || !session) return null;+ const epochTitle = session.epoch ? (epochTitles.get(session.epoch) ?? null) : null;+ return (+ <SessionRow+ key={row.message.id}+ row={row}+ session={session}+ epochTitle={epochTitle}+ selected={selectedSessionId === session.sessionId}+ onOpen={onOpen}+ onContinue={(continues) => onContinue(continues.sessionId, continues.id)}+ />+ );+ })}+ </div>+ </div>+ );+}diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex 9c80661..222cd6d 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -9,9 +9,9 @@ import { resumeCommand } from "../../cli/src/view/resume.js";import { formatTime, kindLabel } from "./format.js";import { layoutGitGraph } from "./gitLayout.js";import {+ nodeId as messageKey,messageNeighbors,type NodeDetail,- sessionGroupId,sessionId as sessionKey,toNodeDetail,} from "./graph.js";@@ -303,25 +303,22 @@ function BranchDetails({/** 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.messages, node.nodeId);- const group = sessionGroupId(model, session.sessionId);const go = (target: ViewNode | null) =>target? () =>onNavigate({- focusId: sessionKey(session.sessionId),- expand: group ? [group, sessionKey(session.sessionId)] : [],+ sessionId: session.sessionId,+ focusId: messageKey(sessionKey(session.sessionId), target.id),selection: {type: "node",sessionId: session.sessionId,@@ -356,7 +353,7 @@ function NodeDetails({const session = findSession(model, node.sessionId);return (<>- <MessageNav model={model} session={session} node={node} onNavigate={onNavigate} />+ <MessageNav session={session} node={node} onNavigate={onNavigate} />{session ? <BranchDetails session={session} branchId={branchId} /> : null}{node.summary ? (<section>@@ -468,13 +465,48 @@ function NodeDetails({);}+/**+ * The session's "squash message" (Story 8.7): what the whole session was for,+ * what it got done and what is still open.+ */function SessionDetails({ model, session }: { model: LineageViewModel; session: ViewSession }) {+ const { done, pending } = session.status;return (<><section><h3>Goal</h3><p>{session.status.goal || "No goal recorded."}</p></section>+ <section>+ <h3>Done</h3>+ {done.length > 0 ? (+ <ul className="drilldown-list">+ {done.map((item, index) => (+ <li key={`${index}-${item}`}>{item}</li>+ ))}+ </ul>+ ) : (+ <p className="muted">Nothing yet.</p>+ )}+ </section>+ <section>+ <h3>Pending</h3>+ {pending.length > 0 ? (+ <ul className="drilldown-list">+ {pending.map((item, index) => (+ <li+ key={`${index}-${item.text}`}+ className={item.needsUser ? "needs-user" : undefined}+ >+ {item.text}+ {item.needsUser ? <span className="badge">needs you</span> : null}+ </li>+ ))}+ </ul>+ ) : (+ <p className="muted">Nothing pending.</p>+ )}+ </section><section><h3>Next</h3><p>{session.status.next || "No next step recorded."}</p>diff --git a/packages/template/src/gitLayout.ts b/packages/template/src/gitLayout.tsindex b9c655c..1001596 100644--- a/packages/template/src/gitLayout.ts+++ b/packages/template/src/gitLayout.ts@@ -1,16 +1,41 @@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.+ * Lays a git graph out (Stories 8.2 and 8.7): one row per item in send order,+ * one lane per branch, branch starts curving out of the item 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.+ * The same code lays out both levels: a session's messages (a message is a+ * commit, `parent` is the message it reacts to) and the project's sessions (a+ * session is a commit, `parent` is the session it continues). Git terms: a root+ * starts something new, a branch is a chain of items with only one child each,+ * and `links` are returns to older items.*/+/**+ * What the layout reads from a row. `ViewNode` (a message) satisfies this, and+ * the session level maps each session onto it, so there is one layout engine.+ */+export interface GitNode {+ id: string;+ label?: string | undefined;+ title: string;+ summary?: string | undefined;+ at?: string | undefined;+ parent?: string | null | undefined;+ links?: string[] | undefined;+ branch?: ViewNode["branch"];+ continues?: ViewNode["continues"];+ unsummarized?: true | undefined;+ /**+ * When the item stops occupying its lane, as a timestamp. Session level only:+ * two sessions that overlap in time must get parallel lanes even when their+ * dots sit on different rows.+ */+ until?: string | undefined;+}+/** 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. */@@ -74,17 +99,17 @@ export interface GitReturn {export interface GitMessageRow {kind: "message";- message: ViewNode;+ message: GitNode;segmentId: string;colorIndex: number;/** Centre of the row on the canvas. */y: number;- /** First message of its branch: hollow ring and branch label. */+ /** First item 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. */+ /** "left off here": the newest message or session. */head: boolean;/** Row height: titles wrap instead of being cut, so long ones get taller rows. */height: number;@@ -122,6 +147,8 @@ export interface GitLayout {laneX: number[];/** Width of the channel + lanes area; the row text starts after it. */graphWidth: number;+ /** Width of the row text right of the dots. */+ rowWidth: number;/** Whole box: graph width, gap, then the row text. */width: number;height: number;@@ -135,6 +162,20 @@ export interface GitLayoutOptions {openAll?: boolean;/** Message that carries "left off here"; defaults to the newest message. */headId?: string | null;+ /**+ * Fold long branches (default true). The session level passes false: one dot+ * per session, and folding a chain of sessions would hide sessions.+ */+ fold?: boolean;+ /**+ * Where an item stops occupying its lane, in send-order index space. Session+ * level only: a session keeps its lane until `updatedAt`, so a session that+ * starts while another is still running gets a parallel lane even when the+ * two dots are not adjacent rows.+ */+ itemEnd?: (item: GitNode) => number | null;+ /** Width of the row text area; defaults to `ROW_WIDTH`. */+ rowWidth?: number;}interface RawRow {@@ -164,8 +205,9 @@ const ROW_FIXED = 106;* the row decides how many lines it needs.*/export function rowHeight(- message: ViewNode,+ message: GitNode,row: { first: boolean; branchTitle: string; returns: number; head: boolean },+ rowWidth = ROW_WIDTH,): number {const fixed =ROW_FIXED +@@ -176,7 +218,7 @@ export function rowHeight((message.unsummarized ? 116 : 0) +// The "↑ continues <session> · m67" mark sits in the row, next to the title.(message.continues ? 150 + message.continues.sessionTitle.length * 6.4 : 0);- const room = Math.max(120, ROW_WIDTH - fixed);+ const room = Math.max(120, rowWidth - fixed);const titleLines = Math.max(1, Math.ceil((message.title.length * TITLE_CHAR) / room));const branchLines = row.first? Math.max(1, Math.ceil((row.branchTitle.length * BRANCH_CHAR) / (BRANCH_MAX - 12)))@@ -185,7 +227,7 @@ export function rowHeight(}/** Parent ids that point forward, at themselves or outside the session become roots. */-function parentOf(message: ViewNode, index: Map<string, number>): string | null {+function parentOf(message: GitNode, index: Map<string, number>): string | null {const parent = message.parent;if (typeof parent !== "string") return null;const self = index.get(message.id) ?? 0;@@ -193,7 +235,7 @@ function parentOf(message: ViewNode, index: Map<string, number>): string | nullreturn at !== undefined && at < self ? parent : null;}-function branchOf(ids: string[], byId: Map<string, ViewNode>): GitBranch {+function branchOf(ids: string[], byId: Map<string, GitNode>): GitBranch {const first = byId.get(ids[0] ?? "");const last = byId.get(ids[ids.length - 1] ?? "");return {@@ -211,7 +253,8 @@ function branchOf(ids: string[], byId: Map<string, ViewNode>): GitBranch {};}-export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions = {}): GitLayout {+export function layoutGitGraph(messages: GitNode[], options: GitLayoutOptions = {}): GitLayout {+ const rowWidth = options.rowWidth ?? ROW_WIDTH;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[]>();@@ -263,10 +306,12 @@ export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions =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 fold = options.fold ?? true;const raw: RawRow[] = [];for (const segment of segments) {const folded =+ fold &&segment.ids.length > FOLD_LIMIT &&!openAll &&!unfolded.has(segment.id) &&@@ -330,12 +375,16 @@ export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions =if (row.gap) cursor += ROOT_GAP;const message = row.kind === "message" ? byId.get(row.id ?? "") : undefined;row.height = message- ? rowHeight(message, {- first: row.segment.ids[0] === message.id,- branchTitle: row.segment.branch.title,- returns: (message.links ?? []).filter((id) => segOf.has(id)).length,- head: message.id === headId,- })+ ? rowHeight(+ message,+ {+ first: row.segment.ids[0] === message.id,+ branchTitle: row.segment.branch.title,+ returns: (message.links ?? []).filter((id) => segOf.has(id)).length,+ head: message.id === headId,+ },+ rowWidth,+ ): ROW_HEIGHT;row.y = cursor + row.height / 2;cursor += row.height;@@ -344,7 +393,9 @@ export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions =});// 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.+ // any lane whose earlier occupants no longer span this row. Spans are in+ // send-order index space (monotonic with y), so both levels share this code;+ // `itemEnd` lets the session level keep a lane busy until `updatedAt`.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));@@ -352,9 +403,17 @@ export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions =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 parentIndex = segment.parentId === null ? null : (index.get(segment.parentId) ?? null);+ const start = parentIndex ?? index.get(segment.ids[0] ?? "") ?? 0;+ let end = (index.get(segment.ids[segment.ids.length - 1] ?? "") ?? 0) + 0.1;+ if (options.itemEnd) {+ for (const id of segment.ids) {+ const item = byId.get(id);+ const custom = item ? options.itemEnd(item) : null;+ if (custom !== null) end = Math.max(end, custom);+ }+ }+ const span: [number, number] = [start, end];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);@@ -363,7 +422,7 @@ export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions =segment.lane = lane;segment.parentLane = parent?.lane ?? null;segment.startY = first.y;- segment.parentY = parentRow?.y ?? null;+ segment.parentY = (segment.parentId === null ? null : rowOf.get(segment.parentId)?.y) ?? null;const list = occupancy.get(lane) ?? [];list.push(span);occupancy.set(lane, list);@@ -436,7 +495,8 @@ export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions =links,laneX,graphWidth,- width: graphWidth + ROW_GAP + ROW_WIDTH,+ rowWidth,+ width: graphWidth + ROW_GAP + rowWidth,height: cursor,headId,};diff --git a/packages/template/src/graph.ts b/packages/template/src/graph.tsindex b63cb49..61b8e6c 100644--- a/packages/template/src/graph.ts+++ b/packages/template/src/graph.ts@@ -1,53 +1,11 @@-import type { Edge as FlowEdge, Node as FlowNode } from "@xyflow/react";-import ELK, {- type ElkExtendedEdge,- type ELK as ElkInstance,- type ElkNode,-} from "elkjs/lib/elk.bundled.js";import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";-import { type GitLayout, layoutGitGraph } from "./gitLayout.js";/**- * 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.+ * Small helpers the map's UI shares: the "left off here" session, node labels,+ * and the panel's node detail. The layout lives in `gitLayout.ts` (both levels)+ * and `sessionLayout.ts` (the project's sessions).*/-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;-/** Wide enough that a collapsed session shows a readable title. */-const SESSION_WIDTH = 380;--export type EpochData = {- title: string;- count: number;- expanded: boolean;- hasChildren: boolean;-};--export type SessionData = {- title: string;- sessionId: string;- updatedAt: string;- goal: string;- 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 message. */export type NodeDetail = {kind: ViewNode["kind"];@@ -77,71 +35,21 @@ export function toNodeDetail(node: ViewNode, sessionId: string): NodeDetail {return { ...node, sessionId, nodeId: node.id };}-export type SessionFlowNode = FlowNode<SessionData, "session">;-export type EpochFlowNode = FlowNode<EpochData, "epoch">;--export type GraphNode = EpochFlowNode | SessionFlowNode;--export interface GraphLayout {- nodes: GraphNode[];- edges: FlowEdge[];- /** Wall-clock time spent inside `elk.layout`, in milliseconds. */- layoutMs: number;-}--export const UNASSIGNED_EPOCH_ID = "unassigned";--export function epochId(id: string): string {- return `epoch:${id}`;-}--export function sessionId(id: string): string {- return `session:${id}`;-}--/**- * 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}`;-}--const LAYOUT_OPTIONS = {- "elk.algorithm": "layered",- "elk.direction": "DOWN",- "elk.hierarchyHandling": "INCLUDE_CHILDREN",- "elk.spacing.nodeNode": "40",- "elk.layered.spacing.nodeNodeBetweenLayers": "48",- "elk.separateConnectedComponents": "true",-} as const;--function groupOptions() {- return {- ...LAYOUT_OPTIONS,- "elk.padding": `[top=${GROUP_HEADER + 8},left=${GROUP_PADDING},bottom=${GROUP_PADDING},right=${GROUP_PADDING}]`,- };-}-/** Where the work left off: the newest message of the most recently updated session. */export interface Head {- sessionKey: string;sessionId: string;messageId: string | null;- /** Epoch group the session belongs to. */- group: string;}-function latestSession(- model: LineageViewModel,-): { session: ViewSession; group: string } | undefined {- const candidates: { session: ViewSession; group: string }[] = [];- for (const epoch of model.epochs) {- for (const session of epoch.sessions) candidates.push({ session, group: epochId(epoch.id) });- }- for (const session of model.unassigned) candidates.push({ session, group: UNASSIGNED_EPOCH_ID });- return candidates.sort(- (a, b) => Date.parse(b.session.updatedAt) - Date.parse(a.session.updatedAt),+function time(value: string): number {+ const at = Date.parse(value);+ return Number.isNaN(at) ? Number.NEGATIVE_INFINITY : at;+}++function latestSession(model: LineageViewModel): ViewSession | undefined {+ const all = [...model.epochs.flatMap((epoch) => epoch.sessions), ...model.unassigned];+ return all.sort(+ (a, b) => time(b.updatedAt) - time(a.updatedAt) || a.sessionId.localeCompare(b.sessionId),)[0];}@@ -149,142 +57,30 @@ 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,+ sessionId: latest.sessionId,+ messageId: latest.messages[latest.messages.length - 1]?.id ?? null,};}-/**- * The map opens on the most recently updated session, with its epoch expanded,- * showing that session's git graph.- */-export function defaultExpanded(model: LineageViewModel): Set<string> {- 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 {- id: string;- title: string;- sessions: ViewSession[];-}--function toFlowEdge(edge: ElkExtendedEdge, existing: Set<string>): FlowEdge | null {- if (existing.has(edge.id)) return null;- existing.add(edge.id);- const [source] = edge.sources;- const [target] = edge.targets;- if (!source || !target) return null;- return { id: edge.id, source, target, type: "smoothstep" };-}--/** Links sibling boxes so the layered layout stacks them in model order. */-function chainEdges(ids: string[]): ElkExtendedEdge[] {- const edges: ElkExtendedEdge[] = [];- for (let i = 1; i < ids.length; i += 1) {- const source = ids[i - 1];- const target = ids[i];- if (source && target) {- edges.push({ id: `edge:${source}->${target}`, sources: [source], targets: [target] });- }- }- return edges;-}--interface Sized {- x: number;- y: number;- width: number;- height: number;-}--interface SessionSize {- width: number;- height: number;- git?: GitLayout;-}--function measureSession(open: boolean, git: GitLayout | null): SessionSize {- if (!open || !git) return { width: SESSION_WIDTH, height: GROUP_HEIGHT };- return {- width: Math.max(SESSION_WIDTH, git.width + GROUP_PADDING * 2),- height: GROUP_HEADER + 8 + git.height + GROUP_PADDING,- git,- };+/** The highlight key of a session in the outline and the map. */+export function sessionId(id: string): string {+ return `session:${id}`;}-function buildSession(- session: ViewSession,- expanded: ReadonlySet<string>,- meta: Map<string, string | null>,- parentId: string,- headId: string | null,- unfolded: ReadonlySet<string>,- openAll: boolean,-): { node: ElkNode; git?: GitLayout } {- const id = sessionId(session.sessionId);- meta.set(id, parentId);- 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 } : {}),- };+/** Outline group key of an epoch; epochs are only tags on the map now. */+export function epochId(id: string): string {+ return `epoch:${id}`;}-function buildEpoch(- group: Group,- expanded: ReadonlySet<string>,- meta: Map<string, string | null>,- 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) => {- 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() };-}+/** Outline group key for sessions with no epoch (or an unknown one). */+export const UNASSIGNED_EPOCH_ID = "unassigned";-function collectSizes(elk: ElkNode, out: Map<string, Sized>): void {- for (const child of elk.children ?? []) {- out.set(child.id, {- x: child.x ?? 0,- y: child.y ?? 0,- width: child.width ?? GROUP_WIDTH,- height: child.height ?? GROUP_HEIGHT,- });- collectSizes(child, out);- }+/**+ * 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}`;}/** The messages just before and after a message in its session, by send order. */@@ -296,144 +92,3 @@ export function messageNeighbors(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;-}--/**- * Lays out the whole map. Only expanded groups send their children to ELK, so- * the default (collapsed) view costs one small box per epoch and session.- */-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) => ({- id: epochId(epoch.id),- title: epoch.title,- sessions: epoch.sessions,- }));- if (model.unassigned.length > 0) {- groups.push({ id: UNASSIGNED_EPOCH_ID, title: "Unassigned", sessions: model.unassigned });- }-- const head = headOf(model);- const parents = new Map<string, string | null>();- const gits = new Map<string, GitLayout>();- const rootChildren = groups.map((group) =>- buildEpoch(group, expanded, parents, head, preferences.unfolded, preferences.openAll, gits),- );- const rootEdges = chainEdges(rootChildren.map((child) => child.id));-- const graph: ElkNode = {- id: "root",- layoutOptions: {- ...LAYOUT_OPTIONS,- "elk.padding": `[top=${ROOT_PADDING},left=${ROOT_PADDING},bottom=${ROOT_PADDING},right=${ROOT_PADDING}]`,- },- children: rootChildren,- edges: rootEdges,- };-- const started = performance.now();- const result = await elk.layout(graph);- const layoutMs = performance.now() - started;-- const sizes = new Map<string, Sized>();- collectSizes(result, sizes);- const seenEdges = new Set<string>();- const edges: FlowEdge[] = [];- const addEdge = (edge: ElkExtendedEdge): void => {- const flow = toFlowEdge(edge, seenEdges);- 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);-- const nodes: GraphNode[] = [];- const box = (id: string): Sized =>- sizes.get(id) ?? { x: 0, y: 0, width: GROUP_WIDTH, height: GROUP_HEIGHT };-- for (const group of groups) {- const epochExpanded = expanded.has(group.id);- const epochSize = box(group.id);- nodes.push({- id: group.id,- type: "epoch",- position: { x: epochSize.x, y: epochSize.y },- width: epochSize.width,- height: epochSize.height,- style: { width: epochSize.width, height: epochSize.height },- draggable: false,- connectable: false,- selectable: false,- data: {- title: group.title,- count: group.sessions.length,- expanded: epochExpanded,- hasChildren: group.sessions.length > 0,- },- });- if (!epochExpanded) continue;-- for (const session of group.sessions) {- 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",- parentId: parents.get(id) ?? group.id,- position: { x: sessionSize.x, y: sessionSize.y },- width: sessionSize.width,- height: sessionSize.height,- style: { width: sessionSize.width, height: sessionSize.height },- draggable: false,- connectable: false,- selectable: false,- data: {- title: session.title || session.sessionId,- sessionId: session.sessionId,- updatedAt: session.updatedAt,- goal: session.status.goal,- count: session.messages.length,- expanded: sessionExpanded,- hasChildren: session.messages.length > 0,- ...(git ? { git } : {}),- ...(session.unrecordedMessages ? { unrecorded: session.unrecordedMessages } : {}),- },- });- }- }-- return { nodes, edges, layoutMs };-}--/**- * 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- * layout does not contain it.- */-export function absolutePosition(- nodes: { id: string; position: { x: number; y: number }; parentId?: string }[],- id: string,-): { x: number; y: number } | null {- const byId = new Map(nodes.map((node) => [node.id, node]));- let node = byId.get(id);- if (!node) return null;- let x = 0;- let y = 0;- const seen = new Set<string>();- while (node && !seen.has(node.id)) {- seen.add(node.id);- x += node.position.x;- y += node.position.y;- node = node.parentId ? byId.get(node.parentId) : undefined;- }- return { x, y };-}diff --git a/packages/template/src/main.tsx b/packages/template/src/main.tsxindex d7e5322..0695c83 100644--- a/packages/template/src/main.tsx+++ b/packages/template/src/main.tsx@@ -21,7 +21,7 @@ async function fetchLatestModel(): Promise<PageModel | null> {/*** On the local server the page follows rebuilds: swapping the model in place- * keeps the graph's open topics, selection and viewport, which a reload would+ * keeps the map's open session, selection and viewport, which a reload would* lose. Over `file://` there is no server to ask, so nothing is subscribed.*/function Page({ initial }: { initial: PageModel }) {diff --git a/packages/template/src/sessionLayout.ts b/packages/template/src/sessionLayout.tsnew file mode 100644index 0000000..f71c8e1--- /dev/null+++ b/packages/template/src/sessionLayout.ts@@ -0,0 +1,87 @@+import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";+import { type GitLayout, type GitNode, layoutGitGraph } from "./gitLayout.js";+import { headOf } from "./graph.js";++/**+ * The project map's top level (Story 8.7): each session is one dot on a git+ * graph, laid out by the same engine as a session's messages. A session's+ * parent is the session its first message continues (8.6), so a new chat that+ * picks up earlier work grows out of that earlier session; everything else is a+ * root. Epochs are not boxes any more, just tags on the dots.+ */++/** Wider than a message row: a session row carries a title, a count and a tag. */+export const SESSION_ROW_WIDTH = 720;++function time(value: string | undefined): number {+ if (!value) return Number.NEGATIVE_INFINITY;+ const at = Date.parse(value);+ return Number.isNaN(at) ? Number.NEGATIVE_INFINITY : at;+}++/** The session a session hangs from: the one its first message continues. */+export function sessionParentOf(session: ViewSession, known: ReadonlySet<string>): string | null {+ const other = session.messages[0]?.continues?.sessionId;+ if (other === undefined || other === session.sessionId) return null;+ return known.has(other) ? other : null;+}++/** Every session of the map in start order, across epochs and unassigned. */+export function allSessions(model: LineageViewModel): ViewSession[] {+ const all = [...model.epochs.flatMap((epoch) => epoch.sessions), ...model.unassigned];+ return all.sort(+ (a, b) => time(a.startedAt) - time(b.startedAt) || a.sessionId.localeCompare(b.sessionId),+ );+}++export interface SessionGraph {+ /** Geometry of the session dots, lanes and rows. */+ git: GitLayout;+ sessions: Map<string, ViewSession>;+ /** The session each session hangs from; null for a root. */+ parents: Map<string, string | null>;+}++/**+ * Lays the sessions out as a git graph. A session occupies its lane from the+ * row it starts on until `updatedAt`, so two sessions that run at the same time+ * get parallel lanes even when their rows are not adjacent. Long chains never+ * fold: every session must stay visible.+ */+export function layoutSessionGraph(model: LineageViewModel): SessionGraph {+ const sessions = allSessions(model);+ const byId = new Map(sessions.map((session) => [session.sessionId, session]));+ const known = new Set(byId.keys());+ const parents = new Map<string, string | null>();+ const items: GitNode[] = sessions.map((session) => {+ const parent = sessionParentOf(session, known);+ parents.set(session.sessionId, parent);+ return {+ id: session.sessionId,+ title: session.title || session.sessionId,+ at: session.startedAt,+ until: session.updatedAt,+ parent,+ };+ });++ const starts = sessions.map((session) => time(session.startedAt));+ /** How many sessions had started by the time this one stopped running. */+ const endIndex = (item: GitNode): number | null => {+ const until = time(item.until);+ if (until === Number.NEGATIVE_INFINITY) return null;+ let end = 0;+ for (let at = 0; at < starts.length; at += 1) {+ if ((starts[at] ?? Number.NEGATIVE_INFINITY) <= until) end = at + 1;+ }+ return end;+ };++ const git = layoutGitGraph(items, {+ fold: false,+ rowWidth: SESSION_ROW_WIDTH,+ headId: headOf(model)?.sessionId ?? null,+ itemEnd: endIndex,+ });+ return { git, sessions: byId, parents };+}diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 8c1525f..bc201bf 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -127,11 +127,22 @@ ul {.map-toolbar {display: flex;+ align-items: center;justify-content: flex-end;gap: 8px;margin-top: 24px;}+.map-title {+ min-width: 0;+ margin-right: auto;+ overflow: hidden;+ color: var(--muted);+ font-size: 13px;+ text-overflow: ellipsis;+ white-space: nowrap;+}+body:has(.map-shell.is-expanded) {overflow: hidden;}@@ -325,80 +336,45 @@ body:has(.map-shell.is-expanded) {font-size: 11px;}-/* React Flow group nodes: epoch and session boxes that contain their children. */-.flow-group {- width: 100%;- height: 100%;- background: rgba(23, 26, 33, 0.72);- border: 1px solid var(--line);- border-radius: 10px;+/* The map draws its own git graph; React Flow only pans, zooms and frames it. */+.map-node .git-graph {+ margin: 0;}-.epoch-group {- background: rgba(20, 24, 32, 0.6);- border-color: #333c50;+/* Session rows at the project level (Story 8.7). */+.session-row {+ font-size: 13px;}-.group-head {- display: flex;- align-items: center;- gap: 8px;- height: 44px;- padding: 0 10px;+.session-dot {+ cursor: pointer;}-.group-title {- flex: 1;- min-width: 0;- overflow: hidden;- white-space: nowrap;- text-overflow: ellipsis;+.session-dot:hover {+ filter: brightness(1.3);}-.group-head .muted {+.session-count {flex: none;white-space: nowrap;}-.group-toggle {+/* An epoch is a tag on a session dot, not a box around sessions. */+.epoch-tag {+ display: inline-flex;flex: none;- width: 20px;- height: 20px;- padding: 0;- line-height: 1;+ align-items: center;+ gap: 4px;+ max-width: 160px;+ overflow: hidden;+ padding: 1px 6px;color: var(--muted);- background: #1d222c;+ font-size: 10px;+ line-height: 14px;+ white-space: nowrap;+ text-overflow: ellipsis;border: 1px solid var(--line);- border-radius: 5px;- cursor: pointer;-}--.group-toggle:hover {- color: var(--text);- border-color: var(--accent);-}--.group-toggle.is-empty {- display: inline-flex;- align-items: center;- justify-content: center;- cursor: default;-}--/* Edges attach here; handles stay invisible because layout decides the shape. */-.react-flow__handle.flow-handle {- width: 4px;- height: 4px;- min-width: 0;- min-height: 0;- pointer-events: none;- opacity: 0;- border: 0;- background: transparent;-}--.session-group:hover {- border-color: var(--accent);+ border-radius: 4px;}.left-off {diff --git a/packages/template/test/graph.test.ts b/packages/template/test/graph.test.tsindex ee73345..c126220 100644--- a/packages/template/test/graph.test.ts+++ b/packages/template/test/graph.test.ts@@ -1,12 +1,6 @@import { describe, expect, it } from "vitest";import type { LineageViewModel, ViewNode } from "../../cli/src/view/model.js";-import {- absolutePosition,- layoutGraph,- messageNeighbors,- sessionId,- toNodeDetail,-} from "../src/graph.js";+import { headOf, messageNeighbors, nodeId, sessionId, toNodeDetail } from "../src/graph.js";const AT = "2026-10-21T10:00:00.000Z";@@ -36,68 +30,44 @@ const model: LineageViewModel = {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("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);+describe("headOf", () => {+ it("marks the newest message of the most recently updated session", () => {+ expect(headOf(model)).toEqual({ sessionId: "s1", messageId: "m2" });});-});-describe("absolutePosition", () => {- const nodes = [- { id: "epoch", position: { x: 10, y: 20 } },- { id: "session", position: { x: 5, y: 40 }, parentId: "epoch" },- { id: "card", position: { x: 1, y: 2 }, parentId: "session" },- { id: "loop", position: { x: 1, y: 1 }, parentId: "loop" },- ];-- it("adds up the positions of every parent", () => {- expect(absolutePosition(nodes, "card")).toEqual({ x: 16, y: 62 });- expect(absolutePosition(nodes, "epoch")).toEqual({ x: 10, y: 20 });+ it("has no message for a session without any, and is null for an empty map", () => {+ const empty: LineageViewModel = {+ ...model,+ epochs: [+ {+ ...model.epochs[0]!,+ sessions: [{ ...model.epochs[0]!.sessions[0]!, messages: [] }],+ },+ ],+ };+ expect(headOf(empty)).toEqual({ sessionId: "s1", messageId: null });+ expect(headOf({ ...model, epochs: [], unassigned: [] })).toBeNull();});- it("is null for a node the layout does not hold, and survives a parent loop", () => {- expect(absolutePosition(nodes, "gone")).toBeNull();- expect(absolutePosition(nodes, "loop")).toEqual({ x: 1, y: 1 });+ it("picks the latest updatedAt across epochs and unassigned sessions", () => {+ const withUnassigned: LineageViewModel = {+ ...model,+ unassigned: [+ {+ ...model.epochs[0]!.sessions[0]!,+ sessionId: "u1",+ updatedAt: "2026-10-23T00:00:00.000Z",+ messages: [message("m9")],+ },+ ],+ };+ expect(headOf(withUnassigned)).toEqual({ sessionId: "u1", messageId: "m9" });});});@@ -126,8 +96,9 @@ describe("toNodeDetail", () => {});});-describe("sessionId", () => {- it("prefixes the React Flow session group id", () => {+describe("ids", () => {+ it("prefixes the outline and map keys", () => {expect(sessionId("abc")).toBe("session:abc");+ expect(nodeId("session:abc", "m1")).toBe("node:session:abc:m1");});});diff --git a/packages/template/test/outline.test.ts b/packages/template/test/outline.test.tsindex dc41625..ff49494 100644--- a/packages/template/test/outline.test.ts+++ b/packages/template/test/outline.test.ts@@ -1,6 +1,5 @@import { describe, expect, it } from "vitest";import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";-import { defaultExpanded, headOf, sessionGroupId } from "../src/graph.js";import { outlinePath } from "../src/Outline.js";const AT = "2026-10-21T10:00:00.000Z";@@ -63,51 +62,3 @@ describe("outlinePath", () => {expect(outlinePath(model, "node:session:s1:gone")).toBeNull();});});--describe("headOf", () => {- const latest: LineageViewModel = {- ...model,- epochs: [- {- id: "e1",- title: "Epoch one",- createdAt: AT,- sessions: [- {- ...session("s1", "e1", [- message("m1"),- message("m2", "2026-10-21T10:01:00.000Z", "m1"),- ]),- updatedAt: "2026-10-22T00:00:00.000Z",- },- ],- },- ],- };-- it("marks the newest message of the most recently updated session", () => {- expect(headOf(latest)).toEqual({- sessionKey: "session:s1",- sessionId: "s1",- messageId: "m2",- group: "epoch:e1",- });- expect(defaultExpanded(latest)).toEqual(new Set(["epoch:e1", "session:s1"]));- });-- 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("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/packages/template/test/sessionLayout.test.ts b/packages/template/test/sessionLayout.test.tsnew file mode 100644index 0000000..be073e6--- /dev/null+++ b/packages/template/test/sessionLayout.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from "vitest";+import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";+import { allSessions, layoutSessionGraph, sessionParentOf } from "../src/sessionLayout.js";++/** Minutes after 2026-10-24T10:00Z, so spans are easy to read. */+function at(minutes: number): string {+ return new Date(Date.UTC(2026, 9, 24, 10, minutes)).toISOString();+}++function message(id: string, continues?: ViewNode["continues"]): ViewNode {+ return {+ id,+ kind: "message",+ title: id,+ at: at(0),+ ...(continues ? { parent: null, continues } : {}),+ };+}++function session(+ sessionId: string,+ startedAt: number,+ updatedAt: number,+ continues?: { sessionId: string; id: string; sessionTitle: string },+): ViewSession {+ return {+ sessionId,+ agent: "claude-code",+ title: `Session ${sessionId}`,+ epoch: "e1",+ startedAt: at(startedAt),+ updatedAt: at(updatedAt),+ status: { goal: "", done: [], pending: [], next: "" },+ messages: [+ message(+ "h1",+ continues+ ? {+ sessionId: continues.sessionId,+ sessionTitle: continues.sessionTitle,+ id: continues.id,+ }+ : undefined,+ ),+ ],+ transcriptAvailable: true,+ };+}++function modelOf(sessions: ViewSession[]): LineageViewModel {+ return {+ kind: "lineage",+ schema: 1,+ project: { name: "p", path: "/tmp/p", generatedAt: at(0) },+ status: { goal: "", done: [], pending: [], next: "", lastActivity: null },+ epochs: [{ id: "e1", title: "Epoch one", createdAt: at(0), sessions }],+ unassigned: [],+ };+}++describe("sessionParentOf", () => {+ it("hangs a session from the session its first message continues", () => {+ const earlier = session("a", 0, 60);+ const later = session("b", 120, 180, { sessionId: "a", id: "h1", sessionTitle: "Session a" });+ expect(sessionParentOf(later, new Set(["a", "b"]))).toBe("a");+ expect(sessionParentOf(earlier, new Set(["a", "b"]))).toBeNull();+ });++ it("is a root when the earlier session is not in the map", () => {+ const later = session("b", 120, 180, { sessionId: "gone", id: "h1", sessionTitle: "Gone" });+ expect(sessionParentOf(later, new Set(["b"]))).toBeNull();+ });+});++describe("layoutSessionGraph", () => {+ it("lists every session in start order across epochs and unassigned", () => {+ const model = modelOf([session("late", 60, 120), session("early", 0, 30)]);+ model.unassigned = [session("scratch", 30, 40)];+ expect(allSessions(model).map((session) => session.sessionId)).toEqual([+ "early",+ "scratch",+ "late",+ ]);+ });++ it("runs a child session in the parent's lane", () => {+ const earlier = session("a", 0, 60);+ const later = session("b", 90, 120, { sessionId: "a", id: "h1", sessionTitle: "Session a" });+ const graph = layoutSessionGraph(modelOf([earlier, later]));+ expect(graph.parents.get("b")).toBe("a");+ expect(graph.git.segments.map((segment) => segment.ids)).toEqual([["a", "b"]]);+ expect(graph.git.laneX).toHaveLength(1);+ });++ it("gives sessions that run at the same time parallel lanes", () => {+ // b starts while a is still running and does not continue it.+ const graph = layoutSessionGraph(modelOf([session("a", 0, 90), session("b", 30, 60)]));+ expect(graph.git.segments.map((segment) => segment.lane)).toEqual([0, 1]);+ expect(graph.git.laneX).toHaveLength(2);+ });++ it("reuses a lane once the earlier session has stopped", () => {+ const graph = layoutSessionGraph(modelOf([session("a", 0, 30), session("b", 60, 90)]));+ expect(graph.git.segments.map((segment) => segment.lane)).toEqual([0, 0]);+ });++ it("never folds a chain of sessions: every session keeps its row", () => {+ const chain = [session("s1", 0, 10)];+ for (let n = 2; n <= 7; n += 1) {+ chain.push(+ session(`s${n}`, (n - 1) * 20, (n - 1) * 20 + 10, {+ sessionId: `s${n - 1}`,+ id: "h1",+ sessionTitle: `Session s${n - 1}`,+ }),+ );+ }+ const graph = layoutSessionGraph(modelOf(chain));+ expect(graph.git.rows).toHaveLength(7);+ expect(graph.git.rows.every((row) => row.kind === "message")).toBe(true);+ });++ it("marks the most recently updated session as HEAD", () => {+ const graph = layoutSessionGraph(modelOf([session("a", 0, 200), session("b", 60, 90)]));+ expect(graph.git.headId).toBe("a");+ const head = graph.git.rows.find((row) => row.kind === "message" && row.message.id === "a");+ expect(head?.head).toBe(true);+ });+});