Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat(view): order the map by time and mark where the work left off

Eren9a92de53b770
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e138a0..61ab437 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Map shows where the work left off: `session write` now stamps each node it adds or changes (`touchedAt`, set by the CLI and never taken from agent input), and the map opens the branches down to the nodes the last write of the latest session added or changed, marks each "left off here" and frames that session.
- Claude Code plugin skeleton: the `codelineage` npm package is also the plugin (`.claude-plugin/plugin.json`, bundled `dist/cli.js`), and the repository root carries a `codelineage` marketplace that installs it from npm.
- `/codelineage:lineage` skill: injects this session's compact record and the project's epochs, asks the agent for only what is new or changed, and has it save the JSON with the Write tool and run `session write --file … --consume` (JSON piped through a shell heredoc is blocked by Claude Code's command checks). It is pre-approved for exactly those two actions and answers "up to date" when nothing changed.
@@ -15,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `codelineage session write --consume`: deletes the `--file` input once the record is saved and keeps it when the write fails. `gitPolicy=commit` now also ignores `.codelineage/inbox/`.
### Changed
+- Map orders topics left to right, and items top to bottom, by when their thread began: `session write` stamps each new node with `addedAt` (set by the CLI, never by the agent), and a topic starts at its earliest item, so renaming or moving topics no longer scrambles the order. Nodes recorded before the stamp keep their stored order, first.
- Map cards size themselves to their text: titles and summaries wrap onto as many lines as they need instead of being cut off with "…", and the cards below move down to make room.
- Map opens like layers of an onion: sessions run down the page in time order, and inside the latest session only its top-level topics show, side by side as columns with an "N items inside" count; an opened topic lists its items down its column, nested ones indented, and any node with children expands and collapses on click (selecting a nested item in the outline opens every layer above it). Phases are labelled "topic", and collapsed session boxes are wide enough for their titles.
- `/codelineage:lineage` skill: organizes nodes by topic instead of by time (topics and sub-topics at any depth, time order kept inside each), reuses existing topics and moves misplaced nodes by resending them with the right `parent`.
diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.ts
index a385666..a0a452f 100644
--- a/packages/cli/src/schema/merge.ts
+++ b/packages/cli/src/schema/merge.ts
@@ -32,10 +32,17 @@ export function mergeSession(
const nodes = new Map<string, LineageNode>(base.nodes.map((n) => [n.id, n]));
for (const { parent, ...n } of input.nodes ?? []) {
const prev = nodes.get(n.id);
- nodes.set(n.id, {
+ const next: LineageNode = {
...prev,
...n,
parent: parent === undefined ? (prev?.parent ?? null) : parent,
+ };
+ // Nodes recorded before these stamps existed keep no addedAt: their order stays as stored.
+ const addedAt = prev ? prev.addedAt : now;
+ nodes.set(n.id, {
+ ...next,
+ ...(addedAt === undefined ? {} : { addedAt }),
+ touchedAt: prev && sameNode(prev, next) ? prev.touchedAt : now,
});
}
@@ -52,6 +59,13 @@ export function mergeSession(
return { session: merged, warnings };
}
+const NODE_FIELDS = ["parent", "kind", "title", "summary", "why", "at"] as const;
+
+/** A resent node that changed nothing keeps its touch time. */
+function sameNode(a: LineageNode, b: LineageNode): boolean {
+ return NODE_FIELDS.every((field) => a[field] === b[field]);
+}
+
/** Re-roots nodes whose parent is missing or that sit on a cycle. Mutates in place. */
export function repairTree(nodes: LineageNode[]): string[] {
const warnings: string[] = [];
diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.ts
index 09836c2..095c110 100644
--- a/packages/cli/src/schema/session.ts
+++ b/packages/cli/src/schema/session.ts
@@ -14,6 +14,10 @@ export const LineageNode = z.object({
summary: z.string().max(2000).optional(),
why: z.string().max(2000).optional(),
at: IsoDate.optional(),
+ /** When `session write` first added this node; set by the CLI, never by the agent. */
+ addedAt: IsoDate.optional(),
+ /** When `session write` last added or changed this node; set by the CLI, never by the agent. */
+ touchedAt: IsoDate.optional(),
});
export const PendingItem = z.object({
@@ -41,7 +45,9 @@ export const Session = z.object({
});
/** In input, a missing parent keeps the stored one (null for a new node). */
-export const LineageNodeInput = LineageNode.extend({ parent: Slug.nullable().optional() });
+export const LineageNodeInput = LineageNode.omit({ addedAt: true, touchedAt: true }).extend({
+ parent: Slug.nullable().optional(),
+});
/**
* What the agent sends to `session write`. Everything but the id is optional;
diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.ts
index 2619602..d71d3e4 100644
--- a/packages/cli/src/view/lineage.ts
+++ b/packages/cli/src/view/lineage.ts
@@ -12,8 +12,8 @@ import {
} from "./model.js";
/**
- * Turns a session's flat node list into the nested tree the graph draws. Order is
- * preserved. A missing parent, a self-reference or a cycle becomes a root, so no
+ * 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.
*/
export function buildNodeTree(nodes: LineageNode[]): ViewNode[] {
@@ -44,6 +44,8 @@ export function buildNodeTree(nodes: LineageNode[]): ViewNode[] {
...(node.summary === undefined ? {} : { summary: node.summary }),
...(node.why === undefined ? {} : { why: node.why }),
...(node.at === undefined ? {} : { at: node.at }),
+ ...(node.addedAt === undefined ? {} : { addedAt: node.addedAt }),
+ ...(node.touchedAt === undefined ? {} : { touchedAt: node.touchedAt }),
children,
};
};
@@ -51,7 +53,32 @@ export function buildNodeTree(nodes: LineageNode[]): ViewNode[] {
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 tree;
+ return byStart(tree);
+}
+
+/**
+ * When a node's thread began: its own or any descendant's addedAt, whichever is
+ * earliest. Unstamped nodes predate the stamps, so they count as earliest of all.
+ */
+function startOf(node: ViewNode): string {
+ let start = node.addedAt ?? "";
+ for (const child of node.children) {
+ const childStart = startOf(child);
+ if (childStart < start) start = childStart;
+ }
+ return start;
+}
+
+/**
+ * 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);
}
/** A session counts as active while it was updated within this window. */
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index fa8a438..ad8d152 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -20,6 +20,10 @@ export interface ViewNode {
summary?: string;
why?: string;
at?: string;
+ /** When the node was first added. */
+ addedAt?: string;
+ /** When the node was last added or changed; marks where the work left off. */
+ touchedAt?: string;
/** Nested children, already ordered as the graph should draw them. */
children: ViewNode[];
}
diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.ts
index 69e3856..5e8b84c 100644
--- a/packages/cli/test/build.test.ts
+++ b/packages/cli/test/build.test.ts
@@ -49,6 +49,22 @@ function session(over: Partial<Session> & { sessionId: string }): Session {
}
describe("buildNodeTree", () => {
+ 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));
+ });
+
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 }),
diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.ts
index 02fe167..b40043a 100644
--- a/packages/cli/test/schema.test.ts
+++ b/packages/cli/test/schema.test.ts
@@ -97,6 +97,30 @@ describe("parseVersioned", () => {
});
describe("mergeSession", () => {
+ it("stamps nodes when they are added or changed, never from agent input", () => {
+ const node = { id: "a", kind: "step", title: "A", touchedAt: "2000-01-01T00:00:00.000Z" };
+ const first = mergeSession(undefined, input({ sessionId: "s1", nodes: [node] }), T0).session;
+ expect(first.nodes[0]?.touchedAt).toBe(T0);
+ expect(first.nodes[0]?.addedAt).toBe(T0);
+ const same = mergeSession(first, input({ sessionId: "s1", nodes: [node] }), T1).session;
+ expect(same.nodes[0]?.touchedAt).toBe(T0);
+ const moved = mergeSession(
+ first,
+ input({ sessionId: "s1", nodes: [{ ...node, title: "A2" }] }),
+ T1,
+ ).session;
+ expect(moved.nodes[0]?.touchedAt).toBe(T1);
+ expect(moved.nodes[0]?.addedAt).toBe(T0);
+ // a node stored before the stamps existed never gets a made-up addedAt
+ const legacy = {
+ ...first,
+ nodes: [{ id: "a", parent: null, kind: "step" as const, title: "A" }],
+ };
+ expect(
+ mergeSession(legacy, input({ sessionId: "s1", nodes: [node] }), T1).session.nodes[0],
+ ).not.toHaveProperty("addedAt");
+ });
+
it("creates a new session owned by the CLI timestamps", () => {
const { session } = mergeSession(undefined, input({ sessionId: "s1", title: "x" }), T0);
expect(session).toMatchObject({ schema: 1, startedAt: T0, updatedAt: T0, title: "x" });
diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsx
index f32c094..0417b58 100644
--- a/packages/template/src/Graph.tsx
+++ b/packages/template/src/Graph.tsx
@@ -30,6 +30,7 @@ import {
type EpochFlowNode,
type GraphNode,
type LineageFlowNode,
+ lastTouched,
layoutGraph,
type SessionFlowNode,
TREE_LEFT,
@@ -136,13 +137,14 @@ function SessionNode({ id, data }: NodeProps<SessionFlowNode>) {
function LineageBox({ id, data }: NodeProps<LineageFlowNode>) {
return (
- <div className={`lineage-box kind-${data.kind}`}>
+ <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.hasChildren && !data.expanded ? (
<p className="lineage-count">{itemsInside(data.count)}</p>
) : data.at ? (
@@ -179,10 +181,13 @@ function Flow({ model }: { model: LineageViewModel }) {
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. */
- const pendingFocus = useRef<string | null>(null);
+ // Open on the session where the work left off, framed around it.
+ const pendingFocus = useRef<string | null>(lastTouched(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(Number.NEGATIVE_INFINITY);
+ 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 } = useReactFlow();
diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsx
index 431613e..3c7997f 100644
--- a/packages/template/src/SidePanel.tsx
+++ b/packages/template/src/SidePanel.tsx
@@ -5,7 +5,7 @@ import { formatTime, kindLabel } from "./format.js";
import type { LineageData } from "./graph.js";
/** What the drill-down shows of a node; the expand state stays in the graph. */
-export type NodeDetail = Omit<LineageData, "count" | "expanded" | "hasChildren">;
+export type NodeDetail = Omit<LineageData, "count" | "expanded" | "hasChildren" | "isLast">;
/** What the drill-down shows: a graph node or a whole session. */
export type Selection = { type: "node"; node: NodeDetail } | { type: "session"; sessionId: string };
diff --git a/packages/template/src/graph.ts b/packages/template/src/graph.ts
index e87c0e5..bcffb01 100644
--- a/packages/template/src/graph.ts
+++ b/packages/template/src/graph.ts
@@ -30,6 +30,8 @@ const ROOT_PADDING = 48;
const INDENT = 32;
const ROW_GAP = 16;
const COLUMN_GAP = 24;
+/** The "left off here" badge under the last touched card's title. */
+const LEFT_OFF_BADGE = 20;
/** Wide enough that a collapsed session shows a readable title. */
const SESSION_WIDTH = 380;
@@ -66,6 +68,8 @@ export type LineageData = {
count: number;
expanded: boolean;
hasChildren: boolean;
+ /** The most recently added or changed node: where the work left off. */
+ isLast: boolean;
};
export type EpochFlowNode = FlowNode<EpochData, "epoch">;
@@ -115,25 +119,67 @@ function groupOptions() {
};
}
+export interface LastTouched {
+ 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[];
+}
+
/**
- * The map opens on the most recently updated session, with its epoch expanded,
- * showing only that session's top-level topics; deeper layers open on click.
+ * Where the work left off: the nodes touched by the last write of the most recently
+ * updated session. One write stamps all its nodes at once, so they are all marked
+ * rather than guessing which of them came last.
*/
-export function defaultExpanded(model: LineageViewModel): Set<string> {
+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);
+ if (node.touchedAt) {
+ found.push({ key, ancestors, at: node.touchedAt });
+ if (node.touchedAt > newest) newest = node.touchedAt;
+ }
+ visit(node.children, [...ancestors, key]);
+ }
+ };
+ 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 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 epoch.sessions) candidates.push({ session, group: epochId(epoch.id) });
}
- for (const session of model.unassigned) {
- candidates.push({ session, group: UNASSIGNED_EPOCH_ID });
- }
- const latest = candidates.sort(
+ 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),
)[0];
+}
+
+/**
+ * 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.
+ */
+export function defaultExpanded(model: LineageViewModel): Set<string> {
+ const latest = latestSession(model);
if (!latest) return new Set();
- return new Set([latest.group, sessionId(latest.session.sessionId)]);
+ // 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 ?? [])]);
}
interface Group {
@@ -215,6 +261,7 @@ 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[] = [];
@@ -227,7 +274,7 @@ export function placeSessionNodes(
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);
+ const height = nodeHeight(node, open) + (lastKeys.has(id) ? LEFT_OFF_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);
@@ -252,6 +299,7 @@ function buildSession(
parentId: string,
meta: Map<string, string | null>,
placements: Map<string, Placement>,
+ lastKeys: ReadonlySet<string>,
): ElkNode {
const id = sessionId(session.sessionId);
meta.set(id, parentId);
@@ -259,7 +307,12 @@ function buildSession(
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));
+ 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 };
}
@@ -269,13 +322,14 @@ function buildEpoch(
expanded: ReadonlySet<string>,
meta: Map<string, string | null>,
placements: Map<string, Placement>,
+ lastKeys: ReadonlySet<string>,
): 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),
+ buildSession(session, expanded, group.id, meta, placements, lastKeys),
);
const edges = chainEdges(children.map((child) => child.id));
return { id: group.id, children, edges, layoutOptions: groupOptions() };
@@ -322,9 +376,12 @@ 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 parents = new Map<string, string | null>();
const placements = new Map<string, Placement>();
- const rootChildren = groups.map((group) => buildEpoch(group, expanded, parents, placements));
+ const rootChildren = groups.map((group) =>
+ buildEpoch(group, expanded, parents, placements, lastKeys),
+ );
const rootEdges = chainEdges(rootChildren.map((child) => child.id));
const graph: ElkNode = {
@@ -410,7 +467,7 @@ export async function layoutGraph(
},
});
if (!sessionExpanded) continue;
- collectFlowNodes(session.nodes, id, session.sessionId, nodes, sizes, expanded);
+ collectFlowNodes(session.nodes, id, session.sessionId, nodes, sizes, expanded, lastKeys);
}
}
@@ -424,6 +481,7 @@ function collectFlowNodes(
out: GraphNode[],
sizes: Map<string, Sized>,
expanded: ReadonlySet<string>,
+ lastKeys: ReadonlySet<string>,
): void {
for (const node of nodes) {
const id = nodeId(parent, node.id);
@@ -450,8 +508,9 @@ function collectFlowNodes(
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);
+ if (open) collectFlowNodes(node.children, parent, sessionId, out, sizes, expanded, lastKeys);
}
}
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index 71e4876..dae4166 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -455,6 +455,22 @@ body:has(.map-shell.is-expanded) {
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;
+ padding: 1px 6px;
+ color: var(--warn);
+ border: 1px solid var(--warn);
+ border-radius: 999px;
+ font-size: 10px;
+ line-height: 14px;
+}
+
.lineage-box p.lineage-count {
color: var(--accent);
}
diff --git a/packages/template/test/graph.test.ts b/packages/template/test/graph.test.ts
index d46f201..7183087 100644
--- a/packages/template/test/graph.test.ts
+++ b/packages/template/test/graph.test.ts
@@ -46,4 +46,9 @@ describe("placeSessionNodes", () => {
it("gives an empty session a minimal box", () => {
expect(placeSessionNodes([], "s").boxes.size).toBe(0);
});
+
+ 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);
+ });
});
diff --git a/packages/template/test/outline.test.ts b/packages/template/test/outline.test.ts
index 25abf97..6551b26 100644
--- a/packages/template/test/outline.test.ts
+++ b/packages/template/test/outline.test.ts
@@ -1,5 +1,6 @@
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 { outlinePath } from "../src/Outline.js";
const AT = "2026-10-21T10:00:00.000Z";
@@ -64,3 +65,47 @@ describe("outlinePath", () => {
expect(outlinePath(model, "session:missing")).toBeNull();
});
});
+
+describe("lastTouched", () => {
+ const touched = (n: ViewNode, at: string): ViewNode => ({ ...n, touchedAt: at });
+ const withTouches: LineageViewModel = {
+ ...model,
+ epochs: [
+ {
+ id: "e1",
+ title: "Epoch one",
+ createdAt: AT,
+ 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"),
+ ]),
+ updatedAt: "2026-10-22T00:00:00.000Z",
+ },
+ ],
+ },
+ ],
+ };
+
+ it("finds the newest touched node in the latest session, with the branch above it", () => {
+ expect(lastTouched(withTouches)).toEqual({
+ sessionKey: "session:s1",
+ nodeKeys: ["node:session:s1:n2"],
+ ancestors: ["epoch:e1", "session:s1", "node:session:s1:n1"],
+ });
+ expect(defaultExpanded(withTouches).has("node:session:s1:n1")).toBe(true);
+ });
+
+ 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("is empty when nothing has a touch time yet", () => {
+ expect(lastTouched(model)).toBeNull();
+ expect(lastTouched({ ...model, epochs: [], unassigned: [] })).toBeNull();
+ });
+});