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.

chore: pre-run snapshot 20261023-231351

Eren4b3649cd6942
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4bacef3..cc3907f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- The map shows the conversation: a message's drill-down has the message as the user wrote it and the agent's written replies (tool output left out, tool use counted in one line), with buttons to step to the previous or next message across topics. `build` reads it from the Claude Code transcript into `lineage.html` only, which is never committed; session files still hold no raw text. Long entries open folded; a deleted transcript is said so.
+- The map is the user's messages: each message the user wrote becomes one node (`kind: "message"`, ids `m1`, `m2`, … in transcript order), titled in the user's words with what came of it, grouped under topics and ordered by when it was sent. `session show` reads the session's Claude Code transcript and lists the messages that have no node yet, and `session write` takes their times from it. The agent's own work moves into the node's detail (`work`, `agentDecisions` with reasons and rejected options, `commits`, `files`), "left off here" marks only the last message, and the `/codelineage:lineage` skill is rewritten for this. Older records keep their step, decision and question nodes.
- Git worktree support: a Claude Code session in a linked worktree (`claude -w`) now records into the main checkout's `.codelineage/` when it is git-ignored (a worktree with its own committed copy keeps it), found by reading `.git` files without running git. Hooks, `session write/show`, `epoch add`, `build` and `open` all resolve it; the session keeps the worktree path and branch, and the map's drill-down shows them.
- Decision detail in the record and the map: nodes take `decidedBy` (`user`, `agent` or `agreed`), `alternatives` (options considered and rejected, with the reason), `commits` and `files`; decision cards show their reason and a short line such as "agreed · 1 commit · 2 options rejected", and the drill-down panel lists the rejected options, the commits and files, who decided, and when the node was recorded and last changed. The `/codelineage:lineage` skill asks the agent to fill them in.
- 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.
@@ -27,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `commander`, `zod` and `@inquirer/prompts` moved to `devDependencies`: they are bundled into `dist/cli.js`, so installing the package pulls in no runtime dependencies.
### Fixed
+- Map: opening or closing a session or topic no longer zooms the whole map out to fit; the zoom stays and the clicked box keeps its place on screen. The mouse wheel now scrolls the map; Ctrl+wheel or a pinch zooms.
- Status card: goal, done, pending and next now come from the most recently updated session that recorded a status, so a newer session without one no longer blanks the card; last activity still tracks the newest session.
- `codelineage build` printed each skipped-session warning twice (once for the map, once for the panel); the panel now stays quiet about the project just built.
- Collapsed session headers in the map show a short date (full time on hover), so the session title is no longer cut off after a few characters.
diff --git a/packages/cli/skills/lineage/SKILL.md b/packages/cli/skills/lineage/SKILL.md
index 1bac54a..54321c5 100644
--- a/packages/cli/skills/lineage/SKILL.md
+++ b/packages/cli/skills/lineage/SKILL.md
@@ -1,6 +1,6 @@
---
name: lineage
-description: Record or update this session's lineage for codelineage, covering the goal, the decisions and their reasons, the steps, open questions and what comes next. Use it when the user asks to record the session or its lineage, or when a codelineage hook asks for an update.
+description: Record or update this session's lineage for codelineage, one node per user message with what came of it, grouped by topic, plus the goal, open items and what comes next. Use it when the user asks to record the session or its lineage, or when a codelineage hook asks for an update.
allowed-tools: Bash(node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" *) Edit(/${CLAUDE_PROJECT_DIR}/.codelineage/inbox/**)
---
@@ -16,8 +16,8 @@ This is the current record for this session (the output of `codelineage session
"codelineage is not set up in this project yet; run `npx codelineage init` here first."
- If `sessionError` is set, tell the user the session record is unreadable and
quote the error. Then stop. Never write over it.
-- If nothing meaningful happened since the record was last updated, reply
- "Lineage is up to date." and stop.
+- If `newMessages` is empty and nothing else changed since the record was last
+ updated, reply "Lineage is up to date." and stop.
## Then send only what is new or changed
@@ -36,43 +36,60 @@ Build one JSON object:
- `pending`: `{ "text": "…", "needsUser": true }` for anything waiting on the
user, and `needsUser: false` for work that is simply not done yet.
- `next`: the next concrete step.
-- `nodes`: only new nodes, or existing ones whose title, summary, reason or
- parent changed. Nodes you leave out are kept, and so are fields you leave out.
- - `id`: a short, stable slug. Reuse an existing id to change that node.
- - `kind`: `phase` (a topic), `step` (a concrete action), `decision` (a choice
- that was made, with the reason in `why`) or `question` (an open question).
- - `parent`: the id of the topic the node belongs to, or `null` for a
- top-level topic.
- - `title`: up to about ten words. `summary` and `why`: one or two sentences
- each; enough that someone returning days later understands it without the
- conversation.
- - For a `decision`, also send when known:
- - `decidedBy`: `"user"` (the user asked for it or picked it), `"agent"`
- (you decided on your own) or `"agreed"` (you proposed it and the user
- approved).
- - `alternatives`: options that were considered and not taken, each as
- `{ "option": "…", "why": "…" }` with the reason it was rejected, including
- an approach that was tried and then reverted.
- - For any node, when the work reached the code:
- - `commits`: short hashes of the commits that carry it out.
- - `files`: the main files it touched, relative to the project (a few, not
- every file).
-
-## Organize the nodes by topic, not by time
-
-The map opens like layers of an onion: first the session's top-level topics,
-then a click reveals what is inside each one. Order within a layer is the order
-in which things were added, so time is kept inside every topic.
-
-- A topic (`phase`) names what the work is about, such as "Permissions" or "Map
- layout", never when it happened ("First part", "Open decisions").
-- Put each new step, decision or question under the topic it belongs to. Open
- a sub-topic (a `phase` whose parent is a topic) once a topic holds several
- distinct threads; nest as deep as the work needs.
+- `nodes`: only new nodes, or existing ones whose fields changed. Nodes you
+ leave out are kept, and so are fields you leave out.
+
+## The map is the user's messages
+
+Each message the user wrote is one node on the map. `newMessages` in the record
+lists the user's messages that have no node yet, in order, with their id (`m1`,
+`m2`, …), time and the start of their text. Send one `message` node for every
+one of them; skip none, even a short "ok" or "go on".
+
+- `id`: exactly the message's id from `newMessages`. The CLI takes the time from
+ the transcript, so do not send `at`.
+- `kind`: `"message"`.
+- `parent`: the id of the topic it belongs to (see below).
+- `title`: the message in a few words, in the user's own wording where possible
+ ("Continue with Epic 4", "Why does auto mode keep stopping?"). Never copy a
+ long paste; name what it is.
+- `summary`: one or two sentences on what came of it: the answer, the result or
+ the state it left. Someone returning days later should understand it without
+ the conversation.
+- When the message itself made a decision (the user asked for something, picked
+ an option or approved a proposal): `decidedBy` (`"user"` or `"agreed"`), the
+ reason in `why`, and the options not taken in `alternatives`, each as
+ `{ "option": "…", "why": "…" }`.
+- Your own work goes inside the message node that caused it, never in nodes of
+ its own:
+ - `work`: short items for what you did (looked up, changed, tested).
+ - `agentDecisions`: choices you made on your own while doing it, each as
+ `{ "title": "…", "why": "…", "alternatives": [ … ] }`.
+ - `commits`: short hashes of the commits that carry it out; `files`: the main
+ files it touched, relative to the project (a few, not every file).
+- Work that continued over several messages belongs to the message where it
+ ended up; update an earlier message node only to correct it.
+
+If `newMessages` is `null`, the transcript could not be read. Then record only
+`status` and leave the nodes alone.
+
+## Group the messages by topic
+
+The map opens like layers of an onion: first the session's topics, then a click
+reveals the messages inside each one, in the order they were written.
+
+- A topic is a node with `kind: "phase"`, an `id` of your choice (a short slug,
+ never `m` followed by a number), a `title` naming what the work is about, such
+ as "Permissions" or "Map layout", never when it happened, and `parent: null`
+ for a top-level topic.
+- Put each message under the topic it belongs to. Open a sub-topic (a `phase`
+ whose parent is a topic) once a topic holds several distinct threads.
- Reuse an existing topic before creating a new one. If an earlier node sits
under the wrong topic, send it again (with its `kind` and `title`) and the
right `parent`.
- Keep the top level short: a handful of topics per session.
+- Records from before messages became the nodes also hold `step`, `decision`
+ and `question` nodes. Leave them as they are and do not add new ones.
Write titles and text in the conversation's language when `language` is `"auto"`,
and in that language otherwise. JSON keys stay in English.
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 5fa7819..c46aef3 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -1,14 +1,16 @@
import { CliError, type Io } from "../io.js";
import { redactDeep } from "../redact.js";
+import type { Session } from "../schema/session.js";
import { atomicWrite } from "../store/fs.js";
import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import { loadAllSessions, loadProject } from "../store/stores.js";
+import { type ChatTurn, displayTurn, readConversation } from "../transcript.js";
import { buildViewModel, embedViewModel } from "../view/lineage.js";
import type { LineageViewModel } from "../view/model.js";
import { buildPanel } from "../view/panel.js";
import { TEMPLATE_HTML } from "../view/template.js";
-import { collectTranscriptIds } from "../view/transcripts.js";
+import { collectTranscripts } from "../view/transcripts.js";
export interface BuildOptions {
dir: string;
@@ -19,6 +21,35 @@ export interface BuildOptions {
quiet?: boolean;
}
+/**
+ * The conversation of every session that records messages and still has its
+ * transcript. It goes into the page only, never into a session file. A transcript
+ * that cannot be read leaves that session without a chat, with a warning.
+ */
+async function readChats(
+ sessions: Session[],
+ transcripts: ReadonlyMap<string, string>,
+ root: string,
+ io: Io,
+): Promise<Map<string, ChatTurn[]>> {
+ const chats = new Map<string, ChatTurn[]>();
+ for (const session of sessions) {
+ const file = transcripts.get(session.sessionId);
+ if (!file || !session.nodes.some((node) => node.kind === "message")) continue;
+ try {
+ const roots = [session.worktree?.path, root].filter((r): r is string => Boolean(r));
+ const turns = await readConversation(file);
+ chats.set(
+ session.sessionId,
+ turns.map((turn) => displayTurn(turn, roots)),
+ );
+ } catch (err) {
+ io.warn(`could not read the conversation of ${session.sessionId}: ${(err as Error).message}`);
+ }
+ }
+ return chats;
+}
+
/**
* Rebuilds `.codelineage/lineage.html` from `project.json` and every session file,
* then refreshes the global panel. One unreadable session is a warning, never a
@@ -34,12 +65,15 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
for (const warning of project.warnings) io.warn(warning);
const paths = projectPaths(root);
+ const sessions = await loadAllSessions(root, io.warn);
+ const transcripts = await collectTranscripts(io.env);
const model = buildViewModel({
project: project.data,
- sessions: await loadAllSessions(root, io.warn),
+ sessions,
path: root,
generatedAt: io.now(),
- transcripts: await collectTranscriptIds(io.env),
+ transcripts: new Set(transcripts.keys()),
+ chats: await readChats(sessions, transcripts, root, io),
});
// The skill already avoids secrets; this is the safety net before rendering.
const redacted = redactDeep(model);
diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.ts
index 68fe3cb..30092e4 100644
--- a/packages/cli/src/commands/session.ts
+++ b/packages/cli/src/commands/session.ts
@@ -4,10 +4,11 @@ import { CliError, type Io } from "../io.js";
import { redactDeep } from "../redact.js";
import { Slug } from "../schema/common.js";
import { mergeSession } from "../schema/merge.js";
-import { SessionInput } from "../schema/session.js";
+import { MESSAGE_ID, SessionInput } from "../schema/session.js";
import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import { loadConfig, loadProject, loadSession, updateSession } from "../store/stores.js";
+import { excerpt, findTranscript, readUserMessages, type UserMessage } from "../transcript.js";
import { buildProject } from "./build.js";
export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {
@@ -54,7 +55,8 @@ export async function sessionWrite(
throw new CliError(`input does not match the session schema: ${issues.join("; ")}`);
}
- const { value: input, count } = redactDeep(parsed.data);
+ const { value: redacted, count } = redactDeep(parsed.data);
+ const input = await stampMessageTimes(redacted, io);
if (count > 0) io.warn(`redacted ${count} secret-looking value(s)`);
if (input.epoch && !project.data.epochs.some((e) => e.id === input.epoch)) {
io.warn(
@@ -81,10 +83,54 @@ export async function sessionWrite(
}
}
+/** The session's user messages, or null when its transcript cannot be read. */
+async function userMessages(
+ sessionId: string,
+ env: NodeJS.ProcessEnv,
+): Promise<UserMessage[] | null> {
+ const file = await findTranscript(sessionId, env);
+ if (!file) return null;
+ try {
+ return await readUserMessages(file);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Message nodes take their time from the transcript, so their order on the map
+ * is the order the user wrote them, whatever the agent sent. Without a
+ * transcript the agent's `at` stays.
+ */
+async function stampMessageTimes(input: SessionInput, io: Io): Promise<SessionInput> {
+ const ids = (input.nodes ?? []).filter((n) => n.kind === "message").map((n) => n.id);
+ if (ids.length === 0) return input;
+ for (const id of ids) {
+ if (!MESSAGE_ID.test(id))
+ io.warn(`message node ${id}: expected an id like m1 from \`session show\``);
+ }
+ const messages = await userMessages(input.sessionId, io.env);
+ if (!messages) return input;
+ const times = new Map(messages.map((m) => [m.id, m.at]));
+ for (const id of ids) {
+ if (MESSAGE_ID.test(id) && !times.has(id))
+ io.warn(`message node ${id}: no such message in the transcript`);
+ }
+ return {
+ ...input,
+ nodes: input.nodes?.map((n) => {
+ const at = n.kind === "message" ? times.get(n.id) : undefined;
+ return at ? { ...n, at } : n;
+ }),
+ };
+}
+
/**
* What the skill injects before the agent updates its record: the project's
- * epochs, the summary language and a compact view of this session (node ids,
- * parents, kinds and titles, without summaries, which merging keeps anyway).
+ * epochs, the summary language, a compact view of this session (node ids,
+ * parents, kinds and titles, without summaries, which merging keeps anyway) and
+ * the user's messages from the transcript that have no node yet, so the agent
+ * cannot skip or reorder one.
* Always exits 0 for an uninitialized project or an unreadable record, because a
* failing injected command aborts the whole skill; the JSON says what is wrong.
*
@@ -130,6 +176,16 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi
} else if (loaded.found) {
view.sessionError = loaded.error;
}
+ const messages = await userMessages(sessionId, io.env);
+ if (messages) {
+ const recorded = new Set(loaded.found && loaded.ok ? loaded.data.nodes.map((n) => n.id) : []);
+ view.messageCount = messages.length;
+ view.newMessages = messages
+ .filter((m) => !recorded.has(m.id))
+ .map(({ id, at, text }) => ({ id, at, text: excerpt(text) }));
+ } else {
+ view.newMessages = null;
+ }
view.inbox = projectPaths(given).inbox(sessionId);
io.out(JSON.stringify(view, null, 2));
}
diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.ts
index 1da8dcf..fc2108b 100644
--- a/packages/cli/src/schema/merge.ts
+++ b/packages/cli/src/schema/merge.ts
@@ -70,6 +70,8 @@ const NODE_FIELDS = [
"alternatives",
"commits",
"files",
+ "work",
+ "agentDecisions",
] as const;
/** A resent node that changed nothing keeps its touch time. */
diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.ts
index 2060f51..2065929 100644
--- a/packages/cli/src/schema/session.ts
+++ b/packages/cli/src/schema/session.ts
@@ -3,7 +3,12 @@ import { IsoDate, Slug } from "./common.js";
export const SESSION_SCHEMA = 1;
-export const NodeKind = z.enum(["phase", "step", "decision", "question"]);
+/**
+ * `message` is one user message, numbered from the transcript (`m1`, `m2`, …);
+ * `phase` is a topic. `step`, `decision` and `question` are the agent's own
+ * items from records written before messages became the nodes.
+ */
+export const NodeKind = z.enum(["phase", "message", "step", "decision", "question"]);
export type NodeKind = z.infer<typeof NodeKind>;
/** Who made a decision: the user, the agent alone, or the user approving the agent's proposal. */
@@ -15,6 +20,16 @@ export const Alternative = z.object({
why: z.string().max(500).default(""),
});
+/** A choice the agent made on its own while working on a message. */
+export const AgentDecision = z.object({
+ title: z.string().min(1).max(200),
+ why: z.string().max(500).default(""),
+ alternatives: z.array(Alternative).max(10).optional(),
+});
+
+/** Message node ids follow the order of the user's messages in the transcript. */
+export const MESSAGE_ID = /^m[1-9][0-9]*$/;
+
export const LineageNode = z.object({
id: Slug,
parent: Slug.nullable().default(null),
@@ -33,6 +48,10 @@ export const LineageNode = z.object({
.optional(),
/** Files this work touched, relative to the project. */
files: z.array(z.string().min(1).max(300)).max(30).optional(),
+ /** For a message: what the agent did about it, in short items. */
+ work: z.array(z.string().min(1).max(300)).max(20).optional(),
+ /** For a message: choices the agent made on its own along the way. */
+ agentDecisions: z.array(AgentDecision).max(10).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. */
@@ -84,6 +103,7 @@ export const SessionInput = z.object({
});
export type LineageNode = z.infer<typeof LineageNode>;
+export type AgentDecision = z.infer<typeof AgentDecision>;
export type Status = z.infer<typeof Status>;
export type Session = z.infer<typeof Session>;
export type SessionInput = z.infer<typeof SessionInput>;
diff --git a/packages/cli/src/transcript.ts b/packages/cli/src/transcript.ts
new file mode 100644
index 0000000..4a0559c
--- /dev/null
+++ b/packages/cli/src/transcript.ts
@@ -0,0 +1,222 @@
+import { createReadStream } from "node:fs";
+import { access, readdir } from "node:fs/promises";
+import { join } from "node:path";
+import { createInterface } from "node:readline";
+import { claudeConfigDir } from "./view/transcripts.js";
+
+/** One message the user typed, numbered in transcript order. */
+export interface UserMessage {
+ /** `m1`, `m2`, …: the node id the message gets on the map. */
+ id: string;
+ /** When the user sent it, from the transcript. */
+ at: string;
+ text: string;
+}
+
+/**
+ * The transcript of a session, `projects/<encoded cwd>/<id>.jsonl`. The encoded
+ * directory is searched rather than derived, since a resumed or worktree session
+ * may live under another project's folder. Null when there is none.
+ */
+export async function findTranscript(
+ sessionId: string,
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<string | null> {
+ const projectsDir = join(claudeConfigDir(env), "projects");
+ let dirs;
+ try {
+ dirs = await readdir(projectsDir, { withFileTypes: true });
+ } catch {
+ return null;
+ }
+ for (const dir of dirs) {
+ if (!dir.isDirectory()) continue;
+ const file = join(projectsDir, dir.name, `${sessionId}.jsonl`);
+ try {
+ await access(file);
+ return file;
+ } catch {}
+ }
+ return null;
+}
+
+/** Lines Claude Code writes as user turns that the user did not type as a message. */
+const NOT_A_MESSAGE =
+ /^\s*<(bash-input|bash-stdout|bash-stderr|local-command-[a-z]+|command-message)>/;
+const COMMAND = /^\s*<command-name>([^<]*)<\/command-name>/;
+const COMMAND_ARGS = /<command-args>([\s\S]*?)<\/command-args>/;
+
+/**
+ * The text of a user line when it is a message the user typed, else null. Tool
+ * results, injected skill text (`isMeta`), compaction summaries, subagent turns,
+ * shell (`!`) input and output, and slash commands without arguments are not
+ * messages; a slash command with arguments counts as "/name args".
+ */
+export function messageText(line: Record<string, unknown>): string | null {
+ if (line.type !== "user") return null;
+ if (line.isMeta || line.isCompactSummary || line.isSidechain) return null;
+ const origin = line.origin as { kind?: unknown } | undefined;
+ if (origin && origin.kind !== "human") return null;
+ const content = (line.message as { content?: unknown } | undefined)?.content;
+ let text: string;
+ if (typeof content === "string") {
+ text = content;
+ } else if (Array.isArray(content)) {
+ if (content.some((block) => block?.type === "tool_result")) return null;
+ text = content
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
+ .map((block) => block.text as string)
+ .join("\n");
+ if (text.trim() === "" && content.some((block) => block?.type === "image")) text = "[image]";
+ } else {
+ return null;
+ }
+ if (NOT_A_MESSAGE.test(text)) return null;
+ const command = COMMAND.exec(text);
+ if (command) {
+ const args = COMMAND_ARGS.exec(text)?.[1]?.trim() ?? "";
+ return args === "" ? null : `${command[1]?.trim()} ${args}`;
+ }
+ return text.trim() === "" ? null : text;
+}
+
+/** What the agent did with tools during one turn, without their output. */
+export interface ToolUse {
+ /** Shell commands run. */
+ commands: number;
+ /** Files written or edited, as the agent named them. */
+ files: string[];
+ /** Any other tool calls (reads, searches, web, subagents…). */
+ other: number;
+}
+
+/** One user message and what the agent wrote back before the next one. */
+export interface ChatTurn extends UserMessage {
+ /** The agent's written replies, in order; tool output never appears here. */
+ replies: string[];
+ tools: ToolUse;
+}
+
+/** The longest text one chat entry keeps on the map; the rest is cut with a note. */
+export const CHAT_TEXT_LIMIT = 20_000;
+
+function capped(text: string): string {
+ if (text.length <= CHAT_TEXT_LIMIT) return text;
+ return `${text.slice(0, CHAT_TEXT_LIMIT)}\n\n[… ${text.length - CHAT_TEXT_LIMIT} more characters not shown]`;
+}
+
+/**
+ * A turn as the map shows it: reminders the harness injected are dropped, paste
+ * markers become a plain label, very long text is cut, and edited files are shown
+ * relative to the project (or the worktree the session ran in).
+ */
+export function displayTurn(turn: ChatTurn, roots: string[]): ChatTurn {
+ const text = turn.text
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "")
+ .replace(
+ /<pasted_content[^>]*>([\s\S]*?)<\/pasted_content[^>]*>/g,
+ "\n[Pasted]\n$1\n[/Pasted]\n",
+ )
+ .trim();
+ const relative = (file: string): string => {
+ for (const root of roots) if (file.startsWith(`${root}/`)) return file.slice(root.length + 1);
+ return file;
+ };
+ return {
+ ...turn,
+ text: capped(text),
+ replies: turn.replies.map(capped),
+ tools: { ...turn.tools, files: turn.tools.files.map(relative) },
+ };
+}
+
+const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
+
+/** Records the agent's text and tool calls of one assistant line on the current turn. */
+function addAssistant(turn: ChatTurn, line: Record<string, unknown>): void {
+ if (line.isSidechain) return;
+ const content = (line.message as { content?: unknown } | undefined)?.content;
+ if (!Array.isArray(content)) return;
+ for (const block of content) {
+ if (block?.type === "text" && typeof block.text === "string" && block.text.trim() !== "") {
+ turn.replies.push(block.text);
+ } else if (block?.type === "tool_use") {
+ const path = (block.input as { file_path?: unknown } | undefined)?.file_path;
+ if (block.name === "Bash") turn.tools.commands += 1;
+ else if (EDIT_TOOLS.has(block.name) && typeof path === "string") {
+ if (!turn.tools.files.includes(path)) turn.tools.files.push(path);
+ } else turn.tools.other += 1;
+ }
+ }
+}
+
+/**
+ * Reads the conversation from a transcript: each message the user typed, in
+ * order, with the agent's written replies and a count of its tool calls up to
+ * the next message. Unparseable lines are skipped.
+ */
+export async function readConversation(file: string): Promise<ChatTurn[]> {
+ const turns: ChatTurn[] = [];
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
+ for await (const raw of lines) {
+ // Most lines are tool output, attachments or API records; skip them unparsed.
+ const user = raw.includes('"type":"user"');
+ if (!user && !raw.includes('"type":"assistant"')) continue;
+ let line: Record<string, unknown>;
+ try {
+ line = JSON.parse(raw);
+ } catch {
+ continue;
+ }
+ const current = turns.at(-1);
+ if (line.type === "assistant") {
+ if (current) addAssistant(current, line);
+ continue;
+ }
+ const text = messageText(line);
+ if (text === null || typeof line.timestamp !== "string") continue;
+ turns.push({
+ id: `m${turns.length + 1}`,
+ at: line.timestamp,
+ text,
+ replies: [],
+ tools: { commands: 0, files: [], other: 0 },
+ });
+ }
+ return turns;
+}
+
+/** Reads the user's messages from a transcript, in order. */
+export async function readUserMessages(file: string): Promise<UserMessage[]> {
+ return (await readConversation(file)).map(({ id, at, text }) => ({ id, at, text }));
+}
+
+/** Up to this many characters of a message go to the agent. */
+export const EXCERPT_LENGTH = 300;
+
+const PASTE = /<pasted_content[^>]*>([\s\S]*?)<\/pasted_content[^>]*>/g;
+
+/** Text on one line, whitespace collapsed. */
+function oneLine(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+/**
+ * A short, single-line view of a message for the agent to title it. System
+ * reminders are dropped; a paste is named by its first words, unless the
+ * message is nothing but pastes, which then show as far as the limit allows.
+ */
+export function excerpt(text: string, max = EXCERPT_LENGTH): string {
+ const withoutReminders = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, " ");
+ const own = oneLine(withoutReminders.replace(PASTE, " "));
+ const cleaned =
+ own === ""
+ ? `[pasted] ${oneLine([...withoutReminders.matchAll(PASTE)].map((m) => m[1]).join(" "))}`
+ : oneLine(
+ withoutReminders.replace(PASTE, (_, body: string) => {
+ const first = oneLine(body).slice(0, 80);
+ return ` [pasted: ${first}…] `;
+ }),
+ );
+ return cleaned.length <= max ? cleaned : `${cleaned.slice(0, max - 1)}…`;
+}
diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.ts
index b337093..b34e719 100644
--- a/packages/cli/src/view/lineage.ts
+++ b/packages/cli/src/view/lineage.ts
@@ -6,6 +6,7 @@ import {
type PageModel,
type StatusCard,
VIEW_SCHEMA,
+ type ViewChatTurn,
type ViewEpoch,
type ViewNode,
type ViewSession,
@@ -48,6 +49,8 @@ export function buildNodeTree(nodes: LineageNode[]): ViewNode[] {
...(node.alternatives?.length ? { alternatives: node.alternatives } : {}),
...(node.commits?.length ? { commits: node.commits } : {}),
...(node.files?.length ? { files: node.files } : {}),
+ ...(node.work?.length ? { work: node.work } : {}),
+ ...(node.agentDecisions?.length ? { agentDecisions: node.agentDecisions } : {}),
...(node.addedAt === undefined ? {} : { addedAt: node.addedAt }),
...(node.touchedAt === undefined ? {} : { touchedAt: node.touchedAt }),
children,
@@ -61,11 +64,12 @@ export function buildNodeTree(nodes: LineageNode[]): ViewNode[] {
}
/**
- * 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.
+ * When a node's thread began: its own or any descendant's start, whichever is
+ * earliest. A message starts when the user sent it, other nodes when they were
+ * added. Unstamped nodes predate the stamps, so they count as earliest of all.
*/
function startOf(node: ViewNode): string {
- let start = node.addedAt ?? "";
+ let start = (node.kind === "message" ? node.at : undefined) ?? node.addedAt ?? "";
for (const child of node.children) {
const childStart = startOf(child);
if (childStart < start) start = childStart;
@@ -146,7 +150,11 @@ export function statusCard(sessions: Session[], now: string): StatusCard {
};
}
-function toViewSession(session: Session, transcripts?: ReadonlySet<string>): ViewSession {
+function toViewSession(
+ session: Session,
+ transcripts?: ReadonlySet<string>,
+ chat?: ViewChatTurn[],
+): ViewSession {
return {
sessionId: session.sessionId,
agent: session.agent,
@@ -160,6 +168,7 @@ function toViewSession(session: Session, transcripts?: ReadonlySet<string>): Vie
// record is shown as resumable rather than pretending the transcript is gone.
transcriptAvailable: transcripts === undefined ? true : transcripts.has(session.sessionId),
...(session.worktree ? { worktree: session.worktree } : {}),
+ ...(chat ? { chat } : {}),
};
}
@@ -176,6 +185,8 @@ export interface ViewModelInput {
generatedAt: string;
/** Session ids whose Claude Code transcript still exists; omit to skip the check. */
transcripts?: ReadonlySet<string>;
+ /** Each session's conversation from its transcript, shown in the drill-down. */
+ chats?: ReadonlyMap<string, ViewChatTurn[]>;
}
/**
@@ -190,7 +201,7 @@ export function buildViewModel(input: ViewModelInput): LineageViewModel {
const sessions = [...input.sessions].sort(byStartedAt);
for (const session of sessions) {
- const view = toViewSession(session, input.transcripts);
+ const view = toViewSession(session, input.transcripts, input.chats?.get(session.sessionId));
const bucket = session.epoch === null ? undefined : buckets.get(session.epoch);
(bucket ?? unassigned).push(view);
}
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index cb0dec2..3f2ecd7 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -24,6 +24,14 @@ export interface ViewNode {
alternatives?: { option: string; why: string }[];
commits?: string[];
files?: string[];
+ /** For a message: what the agent did about it. */
+ work?: string[];
+ /** For a message: choices the agent made on its own. */
+ agentDecisions?: {
+ title: string;
+ why: string;
+ alternatives?: { option: string; why: string }[] | undefined;
+ }[];
/** When the node was first added. */
addedAt?: string;
/** When the node was last added or changed; marks where the work left off. */
@@ -50,6 +58,19 @@ export interface StatusCard extends ViewStatus {
lastActivity: string | null;
}
+/** One user message and the agent's written answer, read from the transcript at build time. */
+export interface ViewChatTurn {
+ /** Same id as the message node it belongs to (`m1`, `m2`, …). */
+ id: string;
+ at: string;
+ /** The user's message as written, without injected reminders. */
+ text: string;
+ /** The agent's written replies until the next message; tool output is never included. */
+ replies: string[];
+ /** What the agent did with tools in that turn, counted, not shown. */
+ tools: { commands: number; files: string[]; other: number };
+}
+
export interface ViewSession {
sessionId: string;
agent: string;
@@ -63,6 +84,11 @@ export interface ViewSession {
transcriptAvailable: boolean;
/** The linked git worktree the session ran in, if any. */
worktree?: { path: string; branch: string | null };
+ /**
+ * The conversation, for sessions that record messages and still have their
+ * transcript. It lives only in the generated page, never in the session file.
+ */
+ chat?: ViewChatTurn[];
}
export interface ViewEpoch {
diff --git a/packages/cli/src/view/transcripts.ts b/packages/cli/src/view/transcripts.ts
index b26246d..8a192bd 100644
--- a/packages/cli/src/view/transcripts.ts
+++ b/packages/cli/src/view/transcripts.ts
@@ -8,33 +8,41 @@ export function claudeConfigDir(env: NodeJS.ProcessEnv = process.env): string {
}
/**
- * Session ids that still have a transcript under `projects/<encoded>/*.jsonl`.
+ * Every transcript under `projects/<encoded>/*.jsonl`, by session id.
* Best effort: an unreadable Claude home means "none found", never a failed build.
*/
-export async function collectTranscriptIds(
+export async function collectTranscripts(
env: NodeJS.ProcessEnv = process.env,
-): Promise<Set<string>> {
- const ids = new Set<string>();
+): Promise<Map<string, string>> {
+ const found = new Map<string, string>();
const projectsDir = join(claudeConfigDir(env), "projects");
let projectDirs;
try {
projectDirs = await readdir(projectsDir, { withFileTypes: true });
} catch {
- return ids;
+ return found;
}
for (const entry of projectDirs) {
if (!entry.isDirectory()) continue;
+ const dir = join(projectsDir, entry.name);
let files: string[];
try {
- files = await readdir(join(projectsDir, entry.name));
+ files = await readdir(dir);
} catch {
continue;
}
for (const file of files) {
- if (file.endsWith(".jsonl")) ids.add(file.slice(0, -".jsonl".length));
+ if (file.endsWith(".jsonl")) found.set(file.slice(0, -".jsonl".length), join(dir, file));
}
}
- return ids;
+ return found;
+}
+
+/** Session ids that still have a transcript. */
+export async function collectTranscriptIds(
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<Set<string>> {
+ return new Set((await collectTranscripts(env)).keys());
}
diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.ts
index e441cf6..5e3cfde 100644
--- a/packages/cli/test/build.test.ts
+++ b/packages/cli/test/build.test.ts
@@ -79,6 +79,27 @@ describe("buildNodeTree", () => {
expect(tree[2]?.addedAt).toBe(t(9));
});
+ it("orders messages by when the user sent them and carries the agent's work", () => {
+ const t = (h: number) => `2026-10-23T${String(h).padStart(2, "0")}:00:00.000Z`;
+ const [topic] = buildNodeTree([
+ node("topic", "phase", "Topic", null, { addedAt: t(1) }),
+ // Written in one go, so the add time cannot tell their order.
+ node("m2", "message", "Second", "topic", { at: t(3), addedAt: t(5) }),
+ node("m1", "message", "First", "topic", {
+ at: t(2),
+ addedAt: t(5),
+ work: ["did a thing"],
+ agentDecisions: [{ title: "Chose x", why: "simpler" }],
+ }),
+ ]);
+ expect(topic?.children.map((n) => n.id)).toEqual(["m1", "m2"]);
+ expect(topic?.children[0]).toMatchObject({
+ work: ["did a thing"],
+ agentDecisions: [{ title: "Chose x", why: "simpler" }],
+ });
+ expect(topic?.children[1]).not.toHaveProperty("work");
+ });
+
it("nests children in order and keeps optional fields only when present", () => {
const tree = buildNodeTree([
node("a", "phase", "A", null, { summary: "phase one", at: T0 }),
@@ -418,6 +439,52 @@ describe("codelineage build", () => {
expect(embedded(html)).toEqual(model);
});
+ it("puts the conversation of message sessions into the map, never into the record", async () => {
+ const folder = join(dir, "claude", "projects", "-proj");
+ await mkdir(folder, { recursive: true });
+ const lines = [
+ {
+ type: "user",
+ timestamp: T0,
+ message: { content: "Fix the card <system-reminder>x</system-reminder>" },
+ },
+ {
+ type: "assistant",
+ message: {
+ content: [
+ { type: "text", text: "Done, key sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123" },
+ { type: "tool_use", name: "Edit", input: { file_path: join(root, "src/a.ts") } },
+ ],
+ },
+ },
+ ];
+ const transcript = lines.map((line) => JSON.stringify(line)).join("\n");
+ await writeFile(join(folder, "s1.jsonl"), transcript);
+ await writeFile(join(folder, "s2.jsonl"), transcript);
+ await saveSession(
+ "s1",
+ session({ sessionId: "s1", epoch: "e1", nodes: [node("m1", "message", "Fix it")] }),
+ );
+ await saveSession(
+ "s2",
+ session({ sessionId: "s2", epoch: "e1", nodes: [node("a", "step", "Old record")] }),
+ );
+
+ const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
+ const [s1, s2] = model.epochs[0]?.sessions ?? [];
+ expect(s1?.chat).toEqual([
+ {
+ id: "m1",
+ at: T0,
+ text: "Fix the card",
+ replies: ["Done, key [REDACTED]"],
+ tools: { commands: 0, files: ["src/a.ts"], other: 0 },
+ },
+ ]);
+ expect(s2).not.toHaveProperty("chat");
+ expect(await readFile(paths().session("s1"), "utf8")).not.toContain("Fix the card");
+ });
+
it("builds without printing when quiet and survives a missing sessions directory", async () => {
await rm(paths().sessions, { recursive: true });
await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.ts
index 0c783dd..0be6a12 100644
--- a/packages/cli/test/session.test.ts
+++ b/packages/cli/test/session.test.ts
@@ -164,6 +164,7 @@ describe("session show", () => {
language: "tr",
epochs: [{ id: "e2e", title: "E2E" }],
session: null,
+ newMessages: null,
inbox: join(root, ".codelineage", "inbox", "s1.json"),
});
@@ -186,6 +187,71 @@ describe("session show", () => {
});
});
+ it("lists the user's messages that have no node yet, and stamps their time on write", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ const folder = join(dir, "claude", "projects", "-p");
+ await mkdir(folder, { recursive: true });
+ const line = (text: string, m: number) =>
+ JSON.stringify({
+ type: "user",
+ timestamp: `2026-10-23T10:0${m}:00.000Z`,
+ message: { role: "user", content: text },
+ });
+ await writeFile(
+ join(folder, "s1.jsonl"),
+ `${line("first", 1)}
+${line("second", 2)}
+`,
+ );
+
+ await sessionShow(root, "s1", io);
+ expect(shown()).toMatchObject({
+ messageCount: 2,
+ newMessages: [
+ { id: "m1", at: "2026-10-23T10:01:00.000Z", text: "first" },
+ { id: "m2", at: "2026-10-23T10:02:00.000Z", text: "second" },
+ ],
+ });
+
+ const writeIo = fakeIo(envFor(dir));
+ await sessionWrite({ dir: root }, writeIo, async () =>
+ JSON.stringify({
+ sessionId: "s1",
+ nodes: [
+ { id: "m1", kind: "message", title: "First", at: "2020-01-01T00:00:00.000Z" },
+ { id: "m9", kind: "message", title: "Made up" },
+ ],
+ }),
+ );
+ expect(writeIo.warnings).toEqual([expect.stringMatching(/m9: no such message/)]);
+ const saved = await loadSession(root, "s1");
+ expect(saved.found && saved.ok && saved.data.nodes[0]?.at).toBe("2026-10-23T10:01:00.000Z");
+
+ io.lines.length = 0;
+ await sessionShow(root, "s1", io);
+ expect(shown().newMessages).toEqual([
+ { id: "m2", at: "2026-10-23T10:02:00.000Z", text: "second" },
+ ]);
+ });
+
+ it("treats an unreadable transcript as none and warns about a message id it cannot use", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ // A directory where the transcript should be: found, but reading it fails.
+ await mkdir(join(dir, "claude", "projects", "-p", "s1.jsonl"), { recursive: true });
+ await sessionShow(root, "s1", io);
+ expect(shown().newMessages).toBeNull();
+
+ const writeIo = fakeIo(envFor(dir));
+ await sessionWrite({ dir: root }, writeIo, async () =>
+ JSON.stringify({ sessionId: "s1", nodes: [{ id: "first", kind: "message", title: "F" }] }),
+ );
+ expect(writeIo.warnings).toEqual([
+ expect.stringMatching(/first: expected an id like m1/),
+ // The map build that follows the write cannot read it either.
+ expect.stringMatching(/could not read the conversation of s1/),
+ ]);
+ });
+
it("flags an unreadable record instead of hiding it", async () => {
await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
await writeFile(join(root, ".codelineage", "sessions", "s1.json"), "{nope");
diff --git a/packages/cli/test/transcript.test.ts b/packages/cli/test/transcript.test.ts
new file mode 100644
index 0000000..7e689f0
--- /dev/null
+++ b/packages/cli/test/transcript.test.ts
@@ -0,0 +1,171 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ CHAT_TEXT_LIMIT,
+ displayTurn,
+ excerpt,
+ findTranscript,
+ messageText,
+ readConversation,
+ readUserMessages,
+} from "../src/transcript.js";
+import { envFor, tempDir } from "./helpers.js";
+
+const at = (m: number) => `2026-10-23T10:${String(m).padStart(2, "0")}:00.000Z`;
+
+/** A user line as Claude Code writes it. */
+function user(content: unknown, extra: Record<string, unknown> = {}, m = 0) {
+ return { type: "user", timestamp: at(m), message: { role: "user", content }, ...extra };
+}
+
+describe("messageText", () => {
+ it.each([
+ [
+ "typed text",
+ user("Continue with Epic 4", { origin: { kind: "human" } }),
+ "Continue with Epic 4",
+ ],
+ ["text and image blocks", user([{ type: "text", text: "look" }, { type: "image" }]), "look"],
+ ["an image alone", user([{ type: "image" }]), "[image]"],
+ [
+ "a slash command with arguments",
+ user("<command-name>/create-story</command-name><command-args>4.5</command-args>"),
+ "/create-story 4.5",
+ ],
+ ])("keeps %s", (_, line, text) => {
+ expect(messageText(line)).toBe(text);
+ });
+
+ it.each([
+ ["an assistant line", { type: "assistant", message: { content: "x" } }],
+ ["a tool result", user([{ type: "tool_result", content: "out" }])],
+ ["injected skill text", user([{ type: "text", text: "Base directory" }], { isMeta: true })],
+ ["a compaction summary", user("This session is being continued", { isCompactSummary: true })],
+ ["a subagent turn", user("task", { isSidechain: true })],
+ ["a non-human origin", user("note", { origin: { kind: "task-notification" } })],
+ ["shell input", user("<bash-input>ls</bash-input>")],
+ ["shell output", user("<bash-stdout>x</bash-stdout><bash-stderr></bash-stderr>")],
+ ["local command output", user("<local-command-stdout>Bye</local-command-stdout>")],
+ ["a slash command without arguments", user("<command-name>/exit</command-name>")],
+ ["empty text", user(" ")],
+ ["content of another shape", user({ text: "x" })],
+ ])("drops %s", (_, line) => {
+ expect(messageText(line)).toBeNull();
+ });
+});
+
+describe("readUserMessages", () => {
+ it("numbers the typed messages in order and skips broken lines", async () => {
+ const dir = await tempDir();
+ const file = join(dir, "s1.jsonl");
+ const lines = [
+ JSON.stringify(user("first", {}, 1)),
+ JSON.stringify({ type: "assistant", timestamp: at(2), message: { content: [] } }),
+ JSON.stringify(user([{ type: "tool_result", content: "x" }], {}, 3)),
+ '{"type":"user", broken',
+ JSON.stringify(user("second", {}, 4)),
+ ];
+ await writeFile(file, `${lines.join("\n")}\n`);
+ expect(await readUserMessages(file)).toEqual([
+ { id: "m1", at: at(1), text: "first" },
+ { id: "m2", at: at(4), text: "second" },
+ ]);
+ });
+});
+
+describe("readConversation", () => {
+ it("gives each message the agent's written replies and counts its tools", async () => {
+ const dir = await tempDir();
+ const file = join(dir, "s1.jsonl");
+ const agent = (content: unknown[], extra: Record<string, unknown> = {}) => ({
+ type: "assistant",
+ message: { content },
+ ...extra,
+ });
+ const lines = [
+ agent([{ type: "text", text: "before any message" }]),
+ user("first", {}, 1),
+ agent([{ type: "text", text: "Looking." }]),
+ agent([{ type: "tool_use", name: "Bash", input: { command: "ls" } }]),
+ agent([{ type: "tool_use", name: "Edit", input: { file_path: "/p/a.ts" } }]),
+ agent([{ type: "tool_use", name: "Write", input: { file_path: "/p/a.ts" } }]),
+ agent([{ type: "tool_use", name: "Edit", input: {} }]),
+ agent([{ type: "tool_use", name: "Read", input: { file_path: "/p/b.ts" } }]),
+ agent([{ type: "text", text: "from a subagent" }], { isSidechain: true }),
+ agent([{ type: "text", text: " " }]),
+ { type: "assistant", message: { content: "not a list" } },
+ user([{ type: "tool_result", content: "x" }], {}, 2),
+ agent([{ type: "text", text: "Done." }]),
+ user("second", {}, 3),
+ ];
+ await writeFile(file, lines.map((line) => JSON.stringify(line)).join("\n"));
+ const turns = await readConversation(file);
+ expect(turns.map((t) => [t.id, t.text, t.replies])).toEqual([
+ ["m1", "first", ["Looking.", "Done."]],
+ ["m2", "second", []],
+ ]);
+ expect(turns[0]?.tools).toEqual({ commands: 1, files: ["/p/a.ts"], other: 2 });
+ });
+});
+
+describe("displayTurn", () => {
+ const turn = (text: string, replies: string[] = []) => ({
+ id: "m1",
+ at: at(1),
+ text,
+ replies,
+ tools: { commands: 0, files: ["/p/w/x.ts", "/p/y.ts", "/elsewhere/z.ts"], other: 0 },
+ });
+
+ it("drops reminders, labels pastes and shows files relative to the project", () => {
+ const shown = displayTurn(
+ turn(
+ '<system-reminder>hidden</system-reminder>see <pasted_content id="a">log</pasted_content id="a">',
+ ),
+ ["/p/w", "/p"],
+ );
+ expect(shown.text).toBe("see \n[Pasted]\nlog\n[/Pasted]");
+ expect(shown.tools.files).toEqual(["x.ts", "y.ts", "/elsewhere/z.ts"]);
+ });
+
+ it("cuts very long text with a note", () => {
+ const long = "x".repeat(CHAT_TEXT_LIMIT + 5);
+ const shown = displayTurn(turn(long, [long]), []);
+ expect(shown.text).toMatch(/\[… 5 more characters not shown\]$/);
+ expect(shown.replies[0]).toMatch(/5 more characters/);
+ });
+});
+
+describe("findTranscript", () => {
+ it("finds the session under any project folder, or returns null", async () => {
+ const dir = await tempDir();
+ const env = envFor(dir);
+ expect(await findTranscript("s1", env)).toBeNull();
+ const folder = join(dir, "claude", "projects", "-some-project");
+ await mkdir(folder, { recursive: true });
+ await writeFile(join(folder, "s1.jsonl"), "");
+ expect(await findTranscript("s1", env)).toBe(join(folder, "s1.jsonl"));
+ expect(await findTranscript("s2", env)).toBeNull();
+ });
+});
+
+describe("excerpt", () => {
+ it("collapses whitespace, names pastes and drops reminders", () => {
+ const text =
+ 'see\n\n<pasted_content id="a">\nError: boom\nat line 2\n</pasted_content>' +
+ "<system-reminder>secret context</system-reminder> please";
+ expect(excerpt(text)).toBe("see [pasted: Error: boom at line 2…] please");
+ });
+
+ it("shows a message that is only a paste as the pasted text", () => {
+ const text =
+ '\n\n<pasted_content id="a">\n Continue with\n Epic 4\n</pasted_content id="a">\n';
+ expect(excerpt(text)).toBe("[pasted] Continue with Epic 4");
+ });
+
+ it("cuts long text with an ellipsis", () => {
+ expect(excerpt("x".repeat(400))).toHaveLength(300);
+ expect(excerpt("x".repeat(400)).endsWith("…")).toBe(true);
+ });
+});
diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsx
index 30a0bbb..98b0ca7 100644
--- a/packages/template/src/Graph.tsx
+++ b/packages/template/src/Graph.tsx
@@ -26,6 +26,7 @@ import type { LineageViewModel } from "../../cli/src/view/model.js";
import { cardMeta, cardText, formatDate, formatTime, itemsInside, kindLabel } from "./format.js";
import { useFullscreen } from "./fullscreen.js";
import {
+ absolutePosition,
defaultExpanded,
type EpochFlowNode,
type GraphNode,
@@ -147,7 +148,7 @@ function LineageBox({ id, data }: NodeProps<LineageFlowNode>) {
{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 ? (
+ ) : data.at && data.kind !== "message" ? (
<time dateTime={data.at}>{formatTime(data.at)}</time>
) : cardText(data) ? (
<p>{cardText(data)}</p>
@@ -170,6 +171,7 @@ function minimapColor(node: GraphNode): string {
const kind = node.data.kind;
if (kind === "decision") return "#4b3a72";
if (kind === "question") return "#5a4526";
+ if (kind === "message") return "#1f3a4a";
return "#1f2a3d";
}
@@ -191,7 +193,11 @@ function Flow({ model }: { model: LineageViewModel }) {
);
/** The first run belongs to mount; only React to the user toggling the outline. */
const firstOutlineToggle = useRef(true);
- const { fitView } = useReactFlow();
+ 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) => {
@@ -218,6 +224,18 @@ function Flow({ model }: { model: LineageViewModel }) {
.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 focus = pendingFocus.current;
@@ -233,10 +251,11 @@ function Flow({ model }: { model: LineageViewModel }) {
return () => {
cancelled = true;
};
- }, [model, expanded, scheduleFocus]);
+ }, [model, expanded, scheduleFocus, getViewport, setViewport]);
useEffect(() => {
- if (!layout) return;
+ 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 });
@@ -256,14 +275,19 @@ function Flow({ model }: { model: LineageViewModel }) {
return () => clearTimeout(timer);
}, [showOutline, fitView]);
- const toggle = useCallback((id: string) => {
- setExpanded((previous) => {
- const next = new Set(previous);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
- }, []);
+ 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 actions = useMemo(() => ({ toggle }), [toggle]);
const closePanel = useCallback(() => setSelection(null), []);
const toggleOutline = useCallback(() => setShowOutline((value) => !value), []);
@@ -320,6 +344,7 @@ function Flow({ model }: { model: LineageViewModel }) {
defaultEdgeOptions={{ style: { stroke: "#4f5b74", strokeWidth: 1.5 } }}
onNodeClick={onNodeClick}
fitView
+ panOnScroll
minZoom={0.05}
maxZoom={2}
nodesDraggable={false}
@@ -366,7 +391,12 @@ function Flow({ model }: { model: LineageViewModel }) {
) : null}
<div className="graph-canvas">
{content}
- <DrillDown model={model} selection={selection} onClose={closePanel} />
+ <DrillDown
+ model={model}
+ selection={selection}
+ onClose={closePanel}
+ onNavigate={selectFromOutline}
+ />
</div>
</div>
</div>
diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsx
index 4d9856d..4540e4e 100644
--- a/packages/template/src/SidePanel.tsx
+++ b/packages/template/src/SidePanel.tsx
@@ -1,8 +1,15 @@
-import { useEffect, useRef, useState } from "react";
-import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";
+import { type ReactNode, useEffect, useRef, useState } from "react";
+import type { LineageViewModel, ViewChatTurn, ViewSession } from "../../cli/src/view/model.js";
import { resumeCommand } from "../../cli/src/view/resume.js";
import { formatTime, kindLabel } from "./format.js";
-import type { NodeDetail } from "./graph.js";
+import {
+ messageNeighbors,
+ type NodeDetail,
+ nodeId,
+ sessionId as sessionKey,
+ toNodeDetail,
+} from "./graph.js";
+import type { OutlineTarget } from "./Outline.js";
/** What the drill-down shows: a graph node or a whole session. */
export type Selection = { type: "node"; node: NodeDetail } | { type: "session"; sessionId: string };
@@ -145,10 +152,126 @@ const DECIDED_LABEL = {
agreed: "You, approving the agent's proposal",
} as const;
-function NodeDetails({ model, node }: { model: LineageViewModel; node: NodeDetail }) {
+/** Above this length a chat entry opens folded, with a button to show the rest. */
+const FOLD_AT = 1200;
+
+function LongText({ text }: { text: string }) {
+ const [open, setOpen] = useState(false);
+ if (text.length <= FOLD_AT || open) return <p className="chat-text">{text}</p>;
+ return (
+ <>
+ <p className="chat-text">{text.slice(0, FOLD_AT)}…</p>
+ <button type="button" className="chat-more" onClick={() => setOpen(true)}>
+ Show all ({text.length.toLocaleString()} characters)
+ </button>
+ </>
+ );
+}
+
+function toolLine(tools: ViewChatTurn["tools"]): string {
+ const parts: string[] = [];
+ if (tools.commands > 0)
+ parts.push(`ran ${tools.commands} command${tools.commands === 1 ? "" : "s"}`);
+ const files = tools.files.length;
+ if (files > 0) parts.push(`edited ${files} file${files === 1 ? "" : "s"}`);
+ if (tools.other > 0) parts.push(`${tools.other} other tool call${tools.other === 1 ? "" : "s"}`);
+ return parts.join(", ");
+}
+
+/** The message as the user wrote it and the agent's written answer, from the transcript. */
+function Conversation({ session, id }: { session: ViewSession | undefined; id: string }) {
+ if (!session) return null;
+ const turn = session.chat?.find((entry) => entry.id === id);
+ let body: ReactNode;
+ if (turn) {
+ const tools = toolLine(turn.tools);
+ body = (
+ <>
+ <div className="chat-entry chat-user">
+ <div className="chat-who">You · {formatTime(turn.at)}</div>
+ <LongText text={turn.text} />
+ </div>
+ <div className="chat-entry chat-agent">
+ <div className="chat-who">Agent</div>
+ {turn.replies.length === 0 ? (
+ <p className="muted">No written reply.</p>
+ ) : (
+ turn.replies.map((reply, index) => (
+ <LongText key={`${turn.id}-${index}`} text={reply} />
+ ))
+ )}
+ {tools ? (
+ <p className="chat-tools" title={turn.tools.files.join("\n")}>
+ {tools}
+ </p>
+ ) : null}
+ </div>
+ </>
+ );
+ } else if (!session.transcriptAvailable) {
+ body = (
+ <p className="muted">
+ The conversation is gone: Claude Code has deleted this session's transcript. The summary
+ above is what remains.
+ </p>
+ );
+ } else {
+ body = <p className="muted">This message was not found in the transcript.</p>;
+ }
+ return (
+ <section className="chat">
+ <h3>Conversation</h3>
+ {body}
+ </section>
+ );
+}
+
+/** Previous and next message of the session, so the chat can be read in order. */
+function MessageNav({
+ session,
+ node,
+ onNavigate,
+}: {
+ session: ViewSession | undefined;
+ node: NodeDetail;
+ onNavigate: ((target: OutlineTarget) => void) | undefined;
+}) {
+ if (!session || !onNavigate || node.kind !== "message") return null;
+ const { previous, next } = messageNeighbors(session.nodes, node.nodeId);
+ const go = (target: typeof previous) =>
+ target
+ ? () =>
+ onNavigate({
+ focusId: nodeId(sessionKey(session.sessionId), target.id),
+ expand: [],
+ selection: { type: "node", node: toNodeDetail(target, session.sessionId) },
+ })
+ : undefined;
+ return (
+ <nav className="message-nav" aria-label="Messages">
+ <button type="button" disabled={!previous} onClick={go(previous)} title={previous?.title}>
+ ← Previous message
+ </button>
+ <button type="button" disabled={!next} onClick={go(next)} title={next?.title}>
+ Next message →
+ </button>
+ </nav>
+ );
+}
+
+function NodeDetails({
+ model,
+ node,
+ onNavigate,
+}: {
+ model: LineageViewModel;
+ node: NodeDetail;
+ onNavigate: ((target: OutlineTarget) => void) | undefined;
+}) {
const session = findSession(model, node.sessionId);
return (
<>
+ <MessageNav session={session} node={node} onNavigate={onNavigate} />
{node.summary ? (
<section>
<h3>Summary</h3>
@@ -161,6 +284,39 @@ function NodeDetails({ model, node }: { model: LineageViewModel; node: NodeDetai
<p>{node.why}</p>
</section>
) : null}
+ {node.work?.length ? (
+ <section>
+ <h3>What the agent did</h3>
+ <ul className="drilldown-list">
+ {node.work.map((item) => (
+ <li key={item}>{item}</li>
+ ))}
+ </ul>
+ </section>
+ ) : null}
+ {node.agentDecisions?.length ? (
+ <section>
+ <h3>Decided by the agent on its own</h3>
+ <ul className="drilldown-list">
+ {node.agentDecisions.map((decision) => (
+ <li key={decision.title}>
+ <strong>{decision.title}</strong>
+ {decision.why ? <> — {decision.why}</> : null}
+ {decision.alternatives?.length ? (
+ <ul>
+ {decision.alternatives.map((alt) => (
+ <li key={alt.option}>
+ Not: {alt.option}
+ {alt.why ? <> — {alt.why}</> : null}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ </section>
+ ) : null}
{node.alternatives?.length ? (
<section>
<h3>Considered and rejected</h3>
@@ -195,9 +351,12 @@ function NodeDetails({ model, node }: { model: LineageViewModel; node: NodeDetai
) : null}
</section>
) : null}
+ {node.kind === "message" ? <Conversation session={session} id={node.nodeId} /> : null}
<dl className="drilldown-meta">
{node.decidedBy ? <Field label="Decided by">{DECIDED_LABEL[node.decidedBy]}</Field> : null}
- <Field label="Recorded">{formatTime(node.at ?? node.addedAt ?? null)}</Field>
+ <Field label={node.kind === "message" ? "Sent" : "Recorded"}>
+ {formatTime(node.at ?? node.addedAt ?? null)}
+ </Field>
{node.touchedAt && node.touchedAt !== node.addedAt ? (
<Field label="Last changed">{formatTime(node.touchedAt)}</Field>
) : null}
@@ -244,10 +403,13 @@ export function DrillDown({
model,
selection,
onClose,
+ onNavigate,
}: {
model: LineageViewModel;
selection: Selection | null;
onClose: () => void;
+ /** Moves the selection to another node and reveals it on the map. */
+ onNavigate?: (target: OutlineTarget) => void;
}) {
useEffect(() => {
if (!selection) return;
@@ -294,7 +456,7 @@ export function DrillDown({
</button>
</header>
<div className="drilldown-body">
- <NodeDetails model={model} node={node} />
+ <NodeDetails model={model} node={node} onNavigate={onNavigate} />
</div>
</aside>
);
diff --git a/packages/template/src/format.ts b/packages/template/src/format.ts
index b7a545f..bfde55a 100644
--- a/packages/template/src/format.ts
+++ b/packages/template/src/format.ts
@@ -14,9 +14,9 @@ export function formatDate(iso: string | null): string {
: date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
-/** Phases are shown as topics: the map groups a session by what the work is about. */
+/** Phases are shown as topics, messages as what the user said. */
export function kindLabel(kind: string): string {
- return kind === "phase" ? "topic" : kind;
+ return kind === "phase" ? "topic" : kind === "message" ? "you" : kind;
}
/** The line a collapsed topic shows in place of its summary. */
@@ -31,9 +31,12 @@ export function cardMeta(node: {
decidedBy?: keyof typeof DECIDED_BY | undefined;
commits?: string[] | undefined;
alternatives?: unknown[] | undefined;
+ agentDecisions?: unknown[] | undefined;
}): string {
const parts: string[] = [];
if (node.decidedBy) parts.push(DECIDED_BY[node.decidedBy]);
+ const own = node.agentDecisions?.length ?? 0;
+ if (own > 0) parts.push(`${own} agent decision${own === 1 ? "" : "s"}`);
const commits = node.commits?.length ?? 0;
if (commits > 0) parts.push(`${commits} commit${commits === 1 ? "" : "s"}`);
const rejected = node.alternatives?.length ?? 0;
diff --git a/packages/template/src/graph.ts b/packages/template/src/graph.ts
index c25d8a2..2376cc1 100644
--- a/packages/template/src/graph.ts
+++ b/packages/template/src/graph.ts
@@ -67,15 +67,19 @@ export type NodeDetail = {
alternatives?: ViewNode["alternatives"];
commits?: string[];
files?: string[];
+ work?: ViewNode["work"];
+ agentDecisions?: ViewNode["agentDecisions"];
addedAt?: string;
touchedAt?: string;
/** Owning session, so the drill-down panel can show and resume it. */
sessionId: string;
+ /** The node's id in its session, which for a message is also its chat turn's id. */
+ nodeId: string;
};
export function toNodeDetail(node: ViewNode, sessionId: string): NodeDetail {
- const { id: _id, children: _children, ...detail } = node;
- return { ...detail, sessionId };
+ const { id, children: _children, ...detail } = node;
+ return { ...detail, sessionId, nodeId: id };
}
export type LineageData = NodeDetail & {
@@ -143,9 +147,10 @@ export interface LastTouched {
}
/**
- * 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.
+ * Where the work left off, in the most recently updated session: its last user
+ * message when it has messages, else the nodes touched by its last write (one
+ * write stamps all its nodes at once, so they are all marked rather than
+ * guessing which of them came last).
*/
export function lastTouched(model: LineageViewModel): LastTouched | null {
const latest = latestSession(model);
@@ -156,13 +161,15 @@ export function lastTouched(model: LineageViewModel): LastTouched | null {
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;
+ const at = byMessage ? (node.kind === "message" ? node.at : undefined) : node.touchedAt;
+ if (at) {
+ found.push({ key, ancestors, at });
+ if (at > newest) newest = at;
}
visit(node.children, [...ancestors, key]);
}
};
+ const byMessage = hasMessage(latest.session.nodes);
visit(latest.session.nodes, []);
const last = found.filter((entry) => entry.at === newest);
if (last.length === 0) return null;
@@ -171,6 +178,10 @@ export function lastTouched(model: LineageViewModel): LastTouched | null {
return { sessionKey, nodeKeys: last.map((entry) => entry.key), ancestors: [...ancestors] };
}
+function hasMessage(nodes: ViewNode[]): boolean {
+ return nodes.some((node) => (node.kind === "message" && node.at) || hasMessage(node.children));
+}
+
function latestSession(
model: LineageViewModel,
): { session: ViewSession; group: string } | undefined {
@@ -238,7 +249,7 @@ function nodeHeight(node: ViewNode, open: boolean): number {
const body =
hasChildren && !open
? itemsInside(countNodes(node.children))
- : node.at
+ : node.at && node.kind !== "message"
? formatTime(node.at)
: cardText(node);
const meta = cardMeta(node);
@@ -526,3 +537,46 @@ function collectFlowNodes(
if (open) collectFlowNodes(node.children, parent, sessionId, out, sizes, expanded, lastKeys);
}
}
+
+/**
+ * Where a node sits on the canvas: its own position plus every parent's, since
+ * React Flow positions children relative to their `parentId`. Null when the
+ * 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 };
+}
+
+/** The messages just before and after a message in its session, by when they were sent. */
+export function messageNeighbors(
+ nodes: ViewNode[],
+ id: string,
+): { previous: ViewNode | null; next: ViewNode | null } {
+ const messages: ViewNode[] = [];
+ const visit = (list: ViewNode[]): void => {
+ for (const node of list) {
+ if (node.kind === "message") messages.push(node);
+ visit(node.children);
+ }
+ };
+ visit(nodes);
+ messages.sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));
+ const index = messages.findIndex((node) => node.id === id);
+ if (index < 0) return { previous: null, next: null };
+ return { previous: messages[index - 1] ?? null, next: messages[index + 1] ?? null };
+}
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index 101f311..b6cbd6f 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -432,6 +432,10 @@ body:has(.map-shell.is-expanded) {
border-left-color: var(--warn);
}
+.lineage-box.kind-message {
+ border-left-color: #9ece6a;
+}
+
.lineage-head {
display: flex;
align-items: flex-start;
@@ -509,6 +513,11 @@ body:has(.map-shell.is-expanded) {
color: var(--warn);
}
+.kind.kind-message {
+ background: #23331d;
+ color: #9ece6a;
+}
+
.empty,
.error {
color: var(--muted);
@@ -524,7 +533,7 @@ body:has(.map-shell.is-expanded) {
z-index: 10;
display: flex;
flex-direction: column;
- width: min(380px, calc(100% - 24px));
+ width: min(460px, calc(100% - 24px));
background: rgba(20, 23, 30, 0.97);
border: 1px solid var(--line);
border-radius: 10px;
@@ -792,3 +801,71 @@ time {
height: 480px;
}
}
+
+.message-nav {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: 14px;
+}
+
+.message-nav button,
+.chat-more {
+ padding: 4px 10px;
+ font: inherit;
+ font-size: 12px;
+ color: var(--text);
+ background: #1f2430;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ cursor: pointer;
+}
+
+.message-nav button:hover:not(:disabled),
+.chat-more:hover {
+ border-color: var(--accent);
+}
+
+.message-nav button:disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+
+.chat-entry {
+ margin-top: 8px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ border-left: 3px solid var(--line);
+ background: #1a1e27;
+}
+
+.chat-user {
+ border-left-color: #9ece6a;
+}
+
+.chat-agent {
+ border-left-color: var(--accent);
+}
+
+.chat-who {
+ margin-bottom: 4px;
+ font-size: 11px;
+ color: var(--muted);
+}
+
+.drilldown-body .chat-text {
+ white-space: pre-wrap;
+ font-size: 13px;
+ line-height: 1.5;
+}
+
+.chat-text + .chat-text {
+ margin-top: 8px;
+}
+
+.drilldown-body .chat-tools {
+ margin-top: 6px;
+ font-size: 12px;
+ color: var(--muted);
+ font-style: italic;
+}
diff --git a/packages/template/test/graph.test.ts b/packages/template/test/graph.test.ts
index 7183087..f1e3935 100644
--- a/packages/template/test/graph.test.ts
+++ b/packages/template/test/graph.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
import type { ViewNode } from "../../cli/src/view/model.js";
-import { placeSessionNodes, TREE_LEFT } from "../src/graph.js";
+import {
+ absolutePosition,
+ messageNeighbors,
+ placeSessionNodes,
+ TREE_LEFT,
+ toNodeDetail,
+} from "../src/graph.js";
function node(id: string, children: ViewNode[] = []): ViewNode {
return { id, kind: "phase", title: id, children };
@@ -52,3 +58,55 @@ describe("placeSessionNodes", () => {
expect(marked.boxes.get("node:s:a1")?.height).toBeGreaterThan(box("a1")?.height ?? 0);
});
});
+
+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("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 });
+ });
+});
+
+describe("messageNeighbors", () => {
+ const message = (id: string, at?: string): ViewNode => ({
+ id,
+ kind: "message",
+ title: id,
+ children: [],
+ ...(at ? { at } : {}),
+ });
+ const tree: ViewNode[] = [
+ {
+ ...node("a"),
+ children: [message("m3", "2026-01-01T03:00:00Z"), message("m1", "2026-01-01T01:00:00Z")],
+ },
+ { ...node("b"), children: [message("m2", "2026-01-01T02:00:00Z"), message("mx")] },
+ ];
+
+ it("finds the messages before and after, by send time across topics", () => {
+ const { previous, next } = messageNeighbors(tree, "m2");
+ expect([previous?.id, next?.id]).toEqual(["m1", "m3"]);
+ expect(messageNeighbors(tree, "m3").next).toBeNull();
+ });
+
+ it("returns nothing for a node that is not a message", () => {
+ expect(messageNeighbors(tree, "a")).toEqual({ previous: null, next: null });
+ });
+});
+
+describe("toNodeDetail", () => {
+ it("keeps the node's own id next to its session", () => {
+ expect(toNodeDetail(node("x"), "s1")).toMatchObject({ nodeId: "x", sessionId: "s1" });
+ });
+});
diff --git a/packages/template/test/outline.test.ts b/packages/template/test/outline.test.ts
index 6551b26..c07106b 100644
--- a/packages/template/test/outline.test.ts
+++ b/packages/template/test/outline.test.ts
@@ -104,6 +104,16 @@ describe("lastTouched", () => {
expect(lastTouched(tie)?.nodeKeys).toEqual(["node:session:s1:n2", "node:session:s1:n3"]);
});
+ it("marks only the last user message once the session has messages", () => {
+ const withMessages = structuredClone(withTouches);
+ const s1 = withMessages.epochs[0]?.sessions[0];
+ s1?.nodes[0]?.children.push(
+ { ...node("m1", "First"), kind: "message", at: "2026-10-21T10:30:00.000Z", touchedAt: AT },
+ { ...node("m2", "Second"), kind: "message", at: "2026-10-21T10:40:00.000Z", touchedAt: AT },
+ );
+ expect(lastTouched(withMessages)?.nodeKeys).toEqual(["node:session:s1:m2"]);
+ });
+
it("is empty when nothing has a touch time yet", () => {
expect(lastTouched(model)).toBeNull();
expect(lastTouched({ ...model, epochs: [], unassigned: [] })).toBeNull();
diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.md
index 178b5eb..9395071 100644
--- a/specs/codelineage-mvp.md
+++ b/specs/codelineage-mvp.md
@@ -17,15 +17,25 @@ The agent itself records a structured summary of its session as it works. A CLI
these records into static HTML:
- **Project map** (one per project): project → epoch (feature/epic) → session →
- topic → sub-topics (any depth) → step/decision/question. It opens like layers of
- an onion: time runs down the page (sessions in order), a session's top-level
- topics sit side by side as columns ordered by when they began, and an opened
- topic lists its items down its column in the order they were added. Every node
- with children expands and collapses; the latest session opens with its topics
- closed except the branches to the nodes its last write added or changed, which
- are marked "left off here". Cards size themselves to their text. A click opens
- a drill-down panel with the full text, who decided, the options considered and
- rejected, the commits and files, and a `claude --resume <id>` copy button.
+ topic → sub-topics (any depth) → the user's messages. The map is a minimap of
+ the chat: one node per message the user wrote, titled in the user's words and
+ saying what came of it; the agent's work on it (steps, its own decisions with
+ their reasons, commits, files) lives in that node's detail, not in nodes of its
+ own. It opens like layers of an onion: time runs down the page (sessions in
+ order), a session's top-level topics sit side by side as columns ordered by when
+ they began, and an opened topic lists its messages down its column in the order
+ the user sent them. Every node with children expands and collapses; the latest
+ session opens with its topics closed except the branch to its last message,
+ which is marked "left off here". Cards size themselves to their text. A click
+ opens a drill-down panel with the full text, who decided, the options considered
+ and rejected, what the agent did and decided on its own, the commits and files,
+ the conversation itself (the message as written and the agent's written
+ replies, tool output left out and tool use counted), previous/next message
+ buttons, and a `claude --resume <id>` copy button. `build` reads the
+ conversation from the transcript into `lineage.html` only (never committed, see
+ Privacy); session files never hold raw text. Records from before messages became
+ the nodes keep their step/decision/question nodes and their old "left off"
+ mark (the nodes of the last write).
- **Status card** at the top of every project: goal, done, pending (flags items
waiting on the user), next step, last activity. With parallel sessions, goal and
next come from the most recently updated session; `needsUser` items are merged
@@ -42,7 +52,7 @@ Sessions are not a separate view. A session is a level of the project tree.
- No server. Every output is a self-contained HTML file opened over `file://`.
- Not a code/architecture visualizer (that is the job of omm, Archify and similar tools).
- Not an agent monitor ("who is running, who is waiting" belongs to tools like Herdr).
-- No live updates. The view refreshes on rebuild.
+- No editing from the map. It is read-only; the local server only serves it and refreshes open pages on rebuild.
## Data model
@@ -50,8 +60,7 @@ Sessions are not a separate view. A session is a level of the project tree.
<project>/.codelineage/
project.json # project name, epochs[], schema version
sessions/<session-id>.json # one file per session (see Concurrency)
- state/<session-id>.json # hook state: turn counter, last recorded turn, pending tail
- snapshots/<session-id>-<ts>.jsonl # transcript copy taken before compaction
+ state/<session-id>.json # hook state: turn counter
locks/ # lock files
lineage.html # generated
@@ -80,21 +89,32 @@ Session file (schema v1, sketch):
"nodes": [
{ "id": "n1", "parent": null, "kind": "phase", "title": "…", "summary": "…",
"addedAt": "…", "touchedAt": "…" },
- { "id": "n2", "parent": "n1", "kind": "decision", "title": "…", "why": "…",
- "decidedBy": "agreed",
+ { "id": "m3", "parent": "n1", "kind": "message", "title": "…", "summary": "…",
+ "at": "…", "why": "…", "decidedBy": "agreed",
"alternatives": [{ "option": "…", "why": "rejected because …" }],
+ "work": ["…"],
+ "agentDecisions": [{ "title": "…", "why": "…", "alternatives": [] }],
"commits": ["322259a"], "files": ["src/…"],
"addedAt": "…", "touchedAt": "…" }
]
}
```
-`kind` is one of `phase | step | decision | question`; a `phase` is a topic and is
-shown as one. Nodes are grouped by topic, not by time, and nest to any depth through
+`kind` is one of `phase | message | step | decision | question`; a `phase` is a topic
+and is shown as one, a `message` is one user message. Message ids are `m1`, `m2`, …
+in the order of the user's messages in the Claude Code transcript; `session show`
+reads the transcript and lists the messages that have no node yet (id, time and an
+excerpt; pastes are named, not copied), so the agent cannot skip or reorder one,
+and `session write` sets a message's `at` from the transcript. Tool results,
+injected skill text, compaction summaries, subagent turns, `!` shell lines and
+slash commands without arguments are not messages. Raw message text never enters
+the record, only the agent's title and summary. `step`, `decision` and `question`
+are kept for records written before messages became the nodes. Nodes are grouped by topic, not by time, and nest to any depth through
`parent`. `decidedBy` is `user | agent | agreed`. `addedAt` (first write) and
`touchedAt` (last change) are stamped by `session write` and never taken from agent
input; a resent node that changed nothing keeps its `touchedAt`. Siblings are
-ordered by when their thread began (the earliest `addedAt` in their subtree);
+ordered by when their thread began (the earliest start in their subtree: a
+message's `at`, any other node's `addedAt`);
nodes recorded before the stamps existed keep their stored order, first. Epochs live in `project.json`.
The agent picks an existing epoch or adds one through the CLI (`codelineage epoch add`),
which does a locked, atomic write.
@@ -154,21 +174,24 @@ Behavior verified against the Claude Code hooks docs (2026-10-21):
itself, so `init` offers to add it to the user settings (install question 3).
- **Compaction (safety net).** PreCompact output never reaches the model and it cannot
make the agent act; it can only block compaction, and blocking an auto-compact
- triggered by a context-limit error fails the request. So:
- - PreCompact never blocks. It copies the transcript to `snapshots/` and marks the
- session as needing an update.
- - PostCompact stores `compact_summary` in the session's state as a raw note.
- - SessionStart with `source: "compact"` tells the agent (via `additionalContext`)
- to run the skill, using the compact summary and the snapshot.
-- **Session end catch-up.** Turns after the last update are lost when the user exits,
- runs `/clear` or switches with `/resume`. SessionEnd cannot make the agent act and
- plugin hooks get a 1.5 s budget, so the hook only records the pending tail in
- `state/` and spawns a detached `codelineage backfill <session-id> --tail`, then
- returns. The catch-up summarizes only the unrecorded turns with a headless run and
- merges them into the session file. Setting: `sessionEndCatchUp` (`on` by default,
- `off` = no tokens spent; the tail is shown as "not recorded").
- - Fallback: if the detached process dies, the pending tail stays in `state/`; the
- next `build` or the next session start in that project retries it.
+ triggered by a context-limit error fails the request. Compaction does not shorten
+ the transcript (verified 2026-10-23: it appends a `compact_boundary` line and the
+ summary, every earlier line stays), and message nodes are read from the
+ transcript, so no message is lost and no snapshot is taken. Only SessionStart
+ with `source: "compact"` acts: when user messages have no node yet, it asks the
+ agent (via `additionalContext`) to run the skill, which works from the compact
+ summary already in its context. No PreCompact or PostCompact hook.
+- **Session end catch-up.** Messages after the last update have no node when the
+ user exits, runs `/clear` or switches with `/resume`. SessionEnd cannot make the
+ agent act and plugin hooks get a 1.5 s budget, so the hook only spawns a detached
+ `codelineage backfill <session-id> --tail` and returns. The catch-up reads the
+ transcript, takes the user messages with no node together with the agent's replies
+ and actions after each, summarizes them with a headless run by the skill's rules
+ and writes them through `session write`. Setting: `sessionEndCatchUp` (`on` by
+ default; `off` = no tokens spent, and the map shows "N messages not recorded").
+ - Fallback: the tail is not stored anywhere; it is whatever messages still have no
+ node, so if the detached process dies, the next session start in that project
+ finds them again and retries.
- Verified (Claude Code 2.1.300, Linux): a child started from SessionEnd with
`spawn(…, { detached: true, stdio: "ignore" }).unref()` outlives both the hook
and Claude Code exiting, and is reparented to the init process.
@@ -196,13 +219,13 @@ Each update costs agent tokens (the user's subscription or API usage).
|---|---|
| `codelineage init` | Creates `.codelineage/`, registers the project, asks the install questions |
| `codelineage build [dir]` | Regenerates `lineage.html` and `panel.html` |
-| `codelineage open [dir]` | Builds, then opens the map (or the panel if no dir is given) |
+| `codelineage open [dir]` | Builds, then opens the map (or the panel if no dir is given) through the local map server, starting it in the background if it is not running. The open page refreshes itself whenever the map is rebuilt, keeping open topics, selection and zoom. Falls back to opening the file when the server cannot start. |
| `codelineage epoch add <id> <title>` | Adds an epoch (locked write) |
| `codelineage config get/set <key> [value]` | Reads or changes settings |
| `codelineage session show <id>` | Prints the compact record the skill injects (epochs, language, status, node ids/titles, inbox path) as JSON. Never fails for an uninitialized project. |
| `codelineage session write` | Reads session JSON from stdin or `--file` (the skill uses `--file <inbox> --consume`), validates, redacts, merges and writes it under the session lock, then builds. |
| `codelineage backfill [dir]` | Summarizes past transcripts of that project by running the agent headless, one session at a time. Estimates cost and asks first. Selection: `--pick` (default: lists sessions with date, first prompt and estimated cost), `--last <n>`, `--since <date>`, `--all`. |
-| `codelineage backfill <session-id> --tail` | Summarizes only the unrecorded turns of one session. Started by the SessionEnd hook. |
+| `codelineage backfill <session-id> --tail` | Summarizes only the user messages of one session that have no node yet. Started by the SessionEnd hook. |
## Install questions (`init` and first plugin run)
@@ -223,6 +246,8 @@ Each update costs agent tokens (the user's subscription or API usage).
Default: none. Picking or all runs `backfill` with a cost estimate first.
Settings in `config.json`: `language`, `updateEveryTurns`, `sessionEndCatchUp`,
+`catchUpModel` (model for the headless catch-up and backfill, default `haiku`),
+`serverPort` (local map server, default 4747),
`gitPolicy`, `agents`.
## Privacy
@@ -230,6 +255,9 @@ Settings in `config.json`: `language`, `updateEveryTurns`, `sessionEndCatchUp`,
- The skill tells the agent never to record secrets, credentials, tokens or personal
data. It records decisions and rationale, not raw content.
- `build` runs a redaction pass (common key and token patterns) before writing HTML.
+- The map (`lineage.html`) shows the conversation read from the local transcript. It
+ is never committed under any `gitPolicy`, so raw chat stays on the machine that
+ already holds the transcript; session files keep only titles and summaries.
- Default `gitPolicy` is `ignore`, because sharing has to be a deliberate choice.
## Edge cases
@@ -275,13 +303,18 @@ Settings in `config.json`: `language`, `updateEveryTurns`, `sessionEndCatchUp`,
`open`, `epoch add`, `config`
2. HTML template: status card, graph with drill-down, outline, resume button
3. Panel
-4. Claude Code plugin: skill; Stop, PreCompact, PostCompact, SessionStart and
- SessionEnd hooks; recursion guard
+4. Claude Code plugin: skill; Stop, SessionStart and SessionEnd hooks; recursion
+ guard
5. `backfill` (project selection and `--tail` catch-up)
+6. Live map: rebuild after every turn (messages not summarized yet shown at once)
+ and a local map server as the default way `open` shows a map: one background
+ server per user on `127.0.0.1`, serving only registered projects' maps and the
+ panel, refreshing open pages on change, exiting after 30 idle minutes; opening
+ the file directly is only the fallback when it cannot start.
## Later
- Codex adapter (its hooks and session retention still need research)
-- Optional local server for live refresh and editing settings from the panel
+- Editing settings from the panel (needs writes through the local server)
- A Herdr usage section in the README
- Video or other "explainer" outputs