Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(record): hang each message from the message it reacts to
Erene72dc7f91c21
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 49a1022..31b52f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Lineage records: each message node now hangs from the earlier message it reacts to (or is a new root), with up to five `links` back to other messages and a `branch` summary (title, asked, outcome, open) on the first message of each branch. `session write` moves a parent that is not an earlier message to the previous message and drops links that are not earlier messages, with a warning; `session show` hints each unrecorded message with `gapMinutes`, `resumed` (a `/clear` or a resume in between) and `commitBetween` (a commit this session made), and lists the last recorded messages with their parent.+### Fixed- `open` adds an initialized project that is missing from the global registry (for example one set up inside a sandbox with its own home) back before serving it; the local map server only shows registered projects, so such a map returned "not found". When the registry cannot be written, `open` opens the file instead.diff --git a/packages/cli/skills/lineage/SKILL.md b/packages/cli/skills/lineage/SKILL.mdindex 54321c5..458e113 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, 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.+description: Record or update this session's lineage for codelineage, one node per user message with what came of it, each hanging from the earlier message it reacts to, with a summary at each branch start, 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/**)---@@ -49,7 +49,8 @@ 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 fromthe transcript, so do not send `at`.- `kind`: `"message"`.-- `parent`: the id of the topic it belongs to (see below).+- `parent`: the id of the earlier message it reacts to (see below), or `null`+ for a new root.- `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 along paste; name what it is.@@ -73,23 +74,49 @@ one of them; skip none, even a short "ok" or "go on".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.+## Hang each message from the one it reacts to++The map is a git-like graph of the user's messages: every message grows from an+earlier one, and a thread that starts something new is a root.++- Default: `parent` is the previous message. Most messages react to the last+ answer.+- `parent: null` only when the message would make sense as the first message of+ a new chat and does not rely on the previous answer.+- An explicit return to an older thread ("back to the representation question"):+ set `parent` to that thread's message and put the previous message in `links`.+- When unsure, use the previous message. A wrong "continue" only hides a branch;+ a wrong branch breaks the chain.+- `links`: up to 5 earlier messages of this session that this one returns to or+ builds on besides its parent. They show as dashed arrows. The CLI drops a+ link or parent that is not an earlier message, so a mistyped one is not fatal.+- `newMessages` hints help, but are hints, not rules: `gapMinutes` since the+ previous message, `resumed` (a `/clear`, a resume or a new process came in+ between), `commitBetween` (this session committed between them). The wording+ decides. `lastMessages` lists the last recorded messages with their parent.++## Summarize each branch++A branch starts at a root or where a message gets a second child. Its first+message carries a `branch` object, short, in the conversation's language:++```json+{+ "title": "What this thread is about, in a few words",+ "asked": "What the user set out to do in this thread",+ "outcome": "What came of it, so far",+ "open": "What is still open; may be empty"+}+```++- Write or update it when the branch ends (a new branch or root starts, or a+ message returns to an older thread) or when you update the session status at+ the end — not on every turn, to keep the update cheap.+- Only the first message of a branch carries a `branch`.++New records send no `phase` nodes: topics are no longer the skeleton. Old+records that still have `phase`, `step`, `decision` and `question` nodes keep+rendering; 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/session.ts b/packages/cli/src/commands/session.tsindex 621d568..ad232af 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -4,10 +4,16 @@ 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 { MESSAGE_ID, SessionInput } from "../schema/session.js";+import { MESSAGE_ID, type Session, 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 {+ type Loaded,+ loadConfig,+ loadProject,+ loadSession,+ updateSession,+} from "../store/stores.js";import {countUserLines,excerpt,@@ -195,12 +201,11 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promiif (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) }));+ view.newMessages = newMessages(messages, recorded);} else {view.newMessages = null;}+ view.lastMessages = lastMessages(loaded);// A format change would otherwise look like "nothing written yet" forever.if (transcript && transcript.messages.length === 0) {const userLines = await countUserLines(transcript.file).catch(() => 0);@@ -212,3 +217,43 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promiview.inbox = projectPaths(given).inbox(sessionId);io.out(JSON.stringify(view, null, 2));}++/** How many recorded messages `session show` repeats for picking a parent. */+const LAST_MESSAGES = 5;++/**+ * The user's messages with no node yet, with the cheap hints the agent uses to+ * decide a parent: the gap since the previous message, a `/clear` or resume in+ * between, and a commit this session made between them. Hints, not rules.+ */+function newMessages(messages: UserMessage[], recorded: Set<string>): Record<string, unknown>[] {+ return messages+ .map((message, i) => {+ const previous = i > 0 ? messages[i - 1] : undefined;+ const gapMinutes = previous+ ? Math.max(0, Math.round((Date.parse(message.at) - Date.parse(previous.at)) / 60_000))+ : undefined;+ return { message, gapMinutes };+ })+ .filter(({ message }) => !recorded.has(message.id))+ .map(({ message, gapMinutes }) => ({+ id: message.id,+ at: message.at,+ text: excerpt(message.text),+ ...(gapMinutes === undefined ? {} : { gapMinutes }),+ ...(message.resumed ? { resumed: true } : {}),+ ...(message.commitBetween ? { commitBetween: true } : {}),+ }));+}++/** The last few recorded messages (id, title, parent) so the agent can pick a parent. */+function lastMessages(+ loaded: Loaded<Session>,+): { id: string; title: string; parent: string | null }[] {+ if (!loaded.found || !loaded.ok) return [];+ return loaded.data.nodes+ .filter((n) => n.kind === "message" && MESSAGE_ID.test(n.id))+ .sort((a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1)))+ .slice(-LAST_MESSAGES)+ .map(({ id, title, parent }) => ({ id, title, parent }));+}diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.tsindex fc2108b..3470c93 100644--- a/packages/cli/src/schema/merge.ts+++ b/packages/cli/src/schema/merge.ts@@ -1,4 +1,10 @@-import { type LineageNode, SESSION_SCHEMA, type Session, type SessionInput } from "./session.js";+import {+ type LineageNode,+ MESSAGE_ID,+ SESSION_SCHEMA,+ type Session,+ type SessionInput,+} from "./session.js";export interface MergeResult {session: Session;@@ -30,12 +36,30 @@ export function mergeSession(};const nodes = new Map<string, LineageNode>(base.nodes.map((n) => [n.id, n]));- for (const { parent, ...n } of input.nodes ?? []) {+ const messageNumbers = new Map<string, number>();+ for (const n of [...base.nodes, ...(input.nodes ?? [])]) {+ const number = messageNumber(n);+ if (number !== null) messageNumbers.set(n.id, number);+ }+ const messageWarnings: string[] = [];+ for (const { parent, links, ...n } of input.nodes ?? []) {const prev = nodes.get(n.id);+ const own = n.kind === "message" ? messageNumber(n) : null;+ const nextParent =+ parent !== undefined && own !== null+ ? checkParent(n.id, parent, own, messageNumbers, messageWarnings)+ : parent === undefined+ ? (prev?.parent ?? null)+ : parent;+ const nextLinks =+ links !== undefined && own !== null+ ? checkLinks(n.id, links, own, messageNumbers, messageWarnings)+ : links;const next: LineageNode = {...prev,...n,- parent: parent === undefined ? (prev?.parent ?? null) : parent,+ parent: nextParent,+ ...(nextLinks === undefined ? {} : { links: nextLinks }),};// Nodes recorded before these stamps existed keep no addedAt: their order stays as stored.const addedAt = prev ? prev.addedAt : now;@@ -55,10 +79,72 @@ export function mergeSession(nodes: [...nodes.values()],updatedAt: now,};- const warnings = repairTree(merged.nodes);+ const warnings = [...messageWarnings, ...repairTree(merged.nodes)];return { session: merged, warnings };}+/** The number in a message node's id (`m7` → 7), or null for any other node. */+function messageNumber(node: { id: string; kind: string }): number | null {+ if (node.kind !== "message" || !MESSAGE_ID.test(node.id)) return null;+ return Number(node.id.slice(1));+}++function isEarlierMessage(numbers: Map<string, number>, id: string, own: number): boolean {+ const number = numbers.get(id);+ return number !== undefined && number < own;+}++/** The recorded message just before `own` by number, or null when there is none. */+function previousMessage(numbers: Map<string, number>, own: number): string | null {+ let best: string | null = null;+ let bestNumber = 0;+ for (const [id, number] of numbers) {+ if (number < own && number > bestNumber) {+ best = id;+ bestNumber = number;+ }+ }+ return best;+}++/**+ * A message's parent is the earlier message it reacts to; anything else (a+ * forward reference, a self-parent, a removed message id) falls back to the+ * previous message so the chain stays in time order. Old records whose message+ * parents are phase ids are left alone: this only checks what the agent sends now.+ */+function checkParent(+ id: string,+ parent: string | null,+ own: number,+ numbers: Map<string, number>,+ warnings: string[],+): string | null {+ if (parent === null || isEarlierMessage(numbers, parent, own)) return parent;+ const fallback = previousMessage(numbers, own);+ warnings.push(+ fallback === null+ ? `message ${id}: parent ${parent} is not an earlier message of this session, moved to root`+ : `message ${id}: parent ${parent} is not an earlier message of this session, using ${fallback}`,+ );+ return fallback;+}++/** Links point at earlier messages too; a forward or unknown one is dropped. */+function checkLinks(+ id: string,+ links: string[],+ own: number,+ numbers: Map<string, number>,+ warnings: string[],+): string[] {+ return links.filter((link) => {+ if (isEarlierMessage(numbers, link, own)) return true;+ warnings.push(`message ${id}: link ${link} is not an earlier message of this session, dropped`);+ return false;+ });+}+const NODE_FIELDS = ["parent","kind",@@ -70,6 +156,8 @@ const NODE_FIELDS = ["alternatives","commits","files",+ "links",+ "branch","work","agentDecisions",] as const;diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.tsindex 2065929..1d39b02 100644--- a/packages/cli/src/schema/session.ts+++ b/packages/cli/src/schema/session.ts@@ -30,8 +30,24 @@ export const AgentDecision = z.object({/** Message node ids follow the order of the user's messages in the transcript. */export const MESSAGE_ID = /^m[1-9][0-9]*$/;+/**+ * The summary a branch carries on its first message: what the thread asked,+ * what came of it and what is still open.+ */+export const BranchSummary = z.object({+ title: z.string().min(1).max(80),+ asked: z.string().min(1).max(300),+ outcome: z.string().min(1).max(600),+ /** May be empty: a thread can leave nothing open. */+ open: z.string().max(300).default(""),+});+export const LineageNode = z.object({id: Slug,+ /**+ * For a message: the id of the earlier message it reacts to (`m3` for `m7`),+ * or null for a new root. For other kinds: the node it belongs to.+ */parent: Slug.nullable().default(null),kind: NodeKind,title: z.string().min(1).max(200),@@ -48,6 +64,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: earlier messages it returns to or builds on besides its parent. */+ links: z.array(Slug).max(5).optional(),+ /** For the first message of a branch: the summary of that thread. */+ branch: BranchSummary.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. */@@ -103,6 +123,7 @@ export const SessionInput = z.object({});export type LineageNode = z.infer<typeof LineageNode>;+export type BranchSummary = z.infer<typeof BranchSummary>;export type AgentDecision = z.infer<typeof AgentDecision>;export type Status = z.infer<typeof Status>;export type Session = z.infer<typeof Session>;diff --git a/packages/cli/src/transcript.ts b/packages/cli/src/transcript.tsindex 1669181..683b24d 100644--- a/packages/cli/src/transcript.ts+++ b/packages/cli/src/transcript.ts@@ -11,6 +11,10 @@ export interface UserMessage {/** When the user sent it, from the transcript. */at: string;text: string;+ /** A `/clear`, a resume or a new process came between this message and the previous one. */+ resumed?: boolean;+ /** The agent ran `git commit` between the previous message and this one. */+ commitBetween?: boolean;}/**@@ -132,6 +136,19 @@ export function displayTurn(turn: ChatTurn, roots: string[]): ChatTurn {const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);+/**+ * `git commit`, also behind options like `-C dir`. A hint, not a decision: a+ * command that merely mentions a commit (`git log --grep commit`) may match.+ */+const GIT_COMMIT = /(?:^|[\s;&|])git(?:\s+[^\s;&|]+)*\s+commit\b/;++/** A `/clear` written by the user or by the CLI as a local command. */+const CLEAR = /<command-name>\s*\/clear\s*<\/command-name>/;++/** The uuid chain fields, read from every line without parsing it. */+const LINE_UUID = /"uuid":"([^"]+)"/;+const LINE_PARENT = /"parentUuid":"([^"]+)"/;+/** 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;@@ -157,8 +174,27 @@ function addAssistant(turn: ChatTurn, line: Record<string, unknown>): void {*/export async function readConversation(file: string): Promise<ChatTurn[]> {const turns: ChatTurn[] = [];+ /** Uuids already read, to notice a chain that starts again (a resumed process). */+ const seen = new Set<string>();+ let pendingResume = false;+ let pendingCommit = false;const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });for await (const raw of lines) {+ // A /clear line is a local command, not a message, but it breaks the thread.+ if (raw.includes("<command-name>") && CLEAR.test(raw)) pendingResume = true;+ // A resume or a new process can append a chain whose parent is not in this+ // file (system lines sit in the chain too, so every line counts). A resume+ // that continues the chain cannot be told apart.+ const uuid = LINE_UUID.exec(raw)?.[1];+ const parent = LINE_PARENT.exec(raw)?.[1];+ if (+ seen.size > 0 &&+ parent !== undefined &&+ !seen.has(parent) &&+ !raw.includes('"isSidechain":true')+ )+ pendingResume = true;+ if (uuid !== undefined) seen.add(uuid);// 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;@@ -168,27 +204,55 @@ export async function readConversation(file: string): Promise<ChatTurn[]> {} catch {continue;}+ // Another line type may still carry `"type":"user"` in nested text.+ if (line.type !== "user" && line.type !== "assistant") continue;const current = turns.at(-1);if (line.type === "assistant") {if (current) addAssistant(current, line);+ if (current && hasCommit(line)) pendingCommit = true;continue;}const text = messageText(line);if (text === null || typeof line.timestamp !== "string") continue;+ const first = turns.length === 0;turns.push({id: `m${turns.length + 1}`,at: line.timestamp,text,replies: [],tools: { commands: 0, files: [], other: 0 },+ ...(!first && pendingResume ? { resumed: true } : {}),+ ...(!first && pendingCommit ? { commitBetween: true } : {}),});+ pendingResume = false;+ pendingCommit = false;}return turns;}+/** Whether an assistant line ran a `git commit`. */+function hasCommit(line: Record<string, unknown>): boolean {+ if (line.isSidechain) return false;+ const content = (line.message as { content?: unknown } | undefined)?.content;+ if (!Array.isArray(content)) return false;+ return content.some(+ (block) =>+ block?.type === "tool_use" &&+ block.name === "Bash" &&+ typeof block.input?.command === "string" &&+ GIT_COMMIT.test(block.input.command),+ );+}+/** 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 }));+ return (await readConversation(file)).map(({ id, at, text, resumed, commitBetween }) => ({+ id,+ at,+ text,+ ...(resumed ? { resumed: true } : {}),+ ...(commitBetween ? { commitBetween: true } : {}),+ }));}/**diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.tsindex f31e6ae..5a4a2a4 100644--- a/packages/cli/test/build.test.ts+++ b/packages/cli/test/build.test.ts@@ -585,7 +585,11 @@ describe("codelineage build", () => {nodes: [{ id: "m2", kind: "message", title: "Second message", parent: "topic" }],}),);- expect(io.warnings).toEqual([]);+ // A message no longer hangs from a topic: the parent falls back to the+ // previous message, with a warning (8.1).+ expect(io.warnings).toEqual([+ expect.stringMatching(/m2: parent topic is not an earlier message of this session, using m1/),+ ]);const after = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });expect(after.epochs[0]?.sessions[0]?.nodes.map((n) => n.title)).toEqual(["Topic"]);});diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.tsindex 7f1c51b..d9eb1c9 100644--- a/packages/cli/test/schema.test.ts+++ b/packages/cli/test/schema.test.ts@@ -45,6 +45,57 @@ describe("Session schema", () => {expect(r.success).toBe(false);});+ it("keeps message links and a branch summary, and old records still parse", () => {+ const s = Session.parse({+ schema: 1,+ sessionId: "abc",+ startedAt: T0,+ updatedAt: T0,+ nodes: [+ {+ id: "m1",+ parent: null,+ kind: "message",+ title: "Start",+ branch: { title: "Setup", asked: "set it up", outcome: "done" },+ },+ { id: "m2", parent: "m1", kind: "message", title: "Next", links: ["m1"] },+ // An old record: a phase topic and a message whose parent is that phase.+ { id: "topic", parent: null, kind: "phase", title: "Old topic" },+ { id: "m3", parent: "topic", kind: "message", title: "Old message" },+ ],+ });+ expect(s.nodes[0]?.branch).toEqual({+ title: "Setup",+ asked: "set it up",+ outcome: "done",+ open: "",+ });+ expect(s.nodes[1]?.links).toEqual(["m1"]);+ expect(s.nodes[3]?.parent).toBe("topic");+ });++ it("limits links to five and branch texts to their lengths", () => {+ const message = (extra: object) => ({+ sessionId: "abc",+ nodes: [{ id: "m1", kind: "message", title: "x", ...extra }],+ });+ expect(input(message({ links: ["a", "b", "c", "d", "e"] })).nodes?.[0]?.links).toHaveLength(5);+ expect(SessionInput.safeParse(message({ links: ["a", "b", "c", "d", "e", "f"] })).success).toBe(+ false,+ );+ expect(+ SessionInput.safeParse(+ message({ branch: { title: "t".repeat(81), asked: "a", outcome: "o" } }),+ ).success,+ ).toBe(false);+ expect(+ SessionInput.safeParse(+ message({ branch: { title: "t", asked: "a", outcome: "o", open: "" } }),+ ).success,+ ).toBe(true);+ });+it("exports a JSON Schema for the agent input", () => {const js = sessionInputJsonSchema() as { required?: string[]; properties?: object };expect(js.required).toEqual(["sessionId"]);diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.tsindex 2c3001e..0d5a696 100644--- a/packages/cli/test/session.test.ts+++ b/packages/cli/test/session.test.ts@@ -106,6 +106,30 @@ describe("session write", () => {expect(await loadSession(root, "s1")).toMatchObject({ ok: true, data: { epoch: "nope" } });});+ it("repairs a message parent to the previous message and drops bad links", async () => {+ await write({+ sessionId: "s1",+ nodes: [+ { id: "m1", kind: "message", title: "One" },+ { id: "m2", kind: "message", title: "Two", parent: "m9" },+ { id: "m3", kind: "message", title: "Three", parent: "m3", links: ["m9", "m1", "m2"] },+ ],+ });+ const s = await loadSession(root, "s1");+ const nodes = s.found && s.ok ? s.data.nodes : [];+ expect(nodes.map((n) => [n.id, n.parent])).toEqual([+ ["m1", null],+ ["m2", "m1"],+ ["m3", "m2"],+ ]);+ expect(nodes[2]?.links).toEqual(["m1", "m2"]);+ expect(io.warnings).toEqual([+ expect.stringMatching(/m2: parent m9 is not an earlier message of this session, using m1/),+ expect.stringMatching(/m3: parent m3 is not an earlier message of this session, using m2/),+ expect.stringMatching(/m3: link m9 is not an earlier message of this session, dropped/),+ ]);+ });+it("rejects invalid JSON and schema mismatches", async () => {await expect(write("{nope")).rejects.toThrow(/not valid JSON/);await expect(write({ sessionId: "../x" })).rejects.toThrow(/sessionId:/);@@ -165,6 +189,7 @@ describe("session show", () => {epochs: [{ id: "e2e", title: "E2E" }],session: null,newMessages: null,+ lastMessages: [],inbox: join(root, ".codelineage", "inbox", "s1.json"),});@@ -209,7 +234,7 @@ ${line("second", 2)}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" },+ { id: "m2", at: "2026-10-23T10:02:00.000Z", text: "second", gapMinutes: 1 },],});@@ -230,7 +255,54 @@ ${line("second", 2)}io.lines.length = 0;await sessionShow(root, "s1", io);expect(shown().newMessages).toEqual([- { id: "m2", at: "2026-10-23T10:02:00.000Z", text: "second" },+ { id: "m2", at: "2026-10-23T10:02:00.000Z", text: "second", gapMinutes: 1 },+ ]);+ expect(shown().lastMessages).toEqual([+ { id: "m1", title: "First", parent: null },+ { id: "m9", title: "Made up", parent: null },+ ]);+ });++ it("hints the gap, a /clear and this session's commits for each new message", 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 user = (text: string, at: string) =>+ JSON.stringify({+ type: "user",+ timestamp: at,+ message: { role: "user", content: text },+ });+ const commit = JSON.stringify({+ type: "assistant",+ timestamp: "2026-10-23T10:05:00.000Z",+ message: {+ role: "assistant",+ content: [{ type: "tool_use", name: "Bash", input: { command: "git commit -m x" } }],+ },+ });+ await writeFile(+ join(folder, "s1.jsonl"),+ [+ user("first", "2026-10-23T10:00:00.000Z"),+ commit,+ user("second", "2026-10-23T10:30:00.000Z"),+ user("<command-name>/clear</command-name>", "2026-10-23T10:40:00.000Z"),+ user("third", "2026-10-23T11:00:00.000Z"),+ ].join("\n"),+ );++ await sessionShow(root, "s1", io);+ expect(shown().newMessages).toEqual([+ { id: "m1", at: "2026-10-23T10:00:00.000Z", text: "first" },+ {+ id: "m2",+ at: "2026-10-23T10:30:00.000Z",+ text: "second",+ gapMinutes: 30,+ commitBetween: true,+ },+ { id: "m3", at: "2026-10-23T11:00:00.000Z", text: "third", gapMinutes: 30, resumed: true },]);});diff --git a/packages/cli/test/transcript.test.ts b/packages/cli/test/transcript.test.tsindex 7e689f0..5e72375 100644--- a/packages/cli/test/transcript.test.ts+++ b/packages/cli/test/transcript.test.ts@@ -107,6 +107,26 @@ describe("readConversation", () => {]);expect(turns[0]?.tools).toEqual({ commands: 1, files: ["/p/a.ts"], other: 2 });});++ it("marks the message after a broken uuid chain as resumed", async () => {+ const file = join(await tempDir(), "s1.jsonl");+ const lines = [+ { ...user("first", { uuid: "u1", parentUuid: null }, 1) },+ {+ type: "assistant",+ uuid: "a1",+ parentUuid: "u1",+ timestamp: at(2),+ message: { content: [] },+ },+ // A resumed process appends a message whose parent is not in this file.+ { ...user("second", { uuid: "u2", parentUuid: "elsewhere" }, 3) },+ ];+ await writeFile(file, lines.map((line) => JSON.stringify(line)).join("\n"));+ const turns = await readConversation(file);+ expect(turns[0]?.resumed).toBeUndefined();+ expect(turns[1]?.resumed).toBe(true);+ });});describe("displayTurn", () => {