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): close each session with one pass that splits threads and writes where it left off
Erenffcfdada62aa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7f770da..5faa194 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Added+- A session-end pass: when a session ends, the side model (Haiku by default) reads the whole session once, splits it into threads and says what each grew from. The parents follow from that, so a detour becomes a side branch and a return to earlier work hangs from where that work stopped; before, the side model chained nearly every message to the previous one. The same call writes each thread's summary and one line on where the session left off (`leftOff`). It costs about a cent per session and keeps every parent and note the main agent wrote. Run it on any recorded session with `cogit backfill <session-id> --tail --close`.+- In side-only mode the session-end pass also hangs a session's first message from the earlier session it continues, which the side model never did before.+### Changed+- A new session's first message is offered the eight most recent other sessions, each with where it left off, its branches and the message each branch ends at, instead of the last three messages of three sessions. Work from further back or the middle of a session can now be continued.+- The side model's prompt now includes what the agent did in each turn: the questions it asked with their options, the files it edited and its steps. It finds the agent's decisions and the topic of a turn in these.## [0.20.0] - 2026-10-28### Addeddiff --git a/docs/format.md b/docs/format.mdindex 0e00fd5..7a1aef8 100644--- a/docs/format.md+++ b/docs/format.md@@ -108,6 +108,7 @@ slug (`[A-Za-z0-9][A-Za-z0-9_.-]{0,127}`), normally the agent's session id."pending": [{"text": "…", "needsUser": true}],"next": "…"},+ "leftOff": "…","nodes": [{"id": "h3f9a2c1b0d4",@@ -127,6 +128,9 @@ slug (`[A-Za-z0-9][A-Za-z0-9_.-]{0,127}`), normally the agent's session id.- `author` is git `user.name` (else the OS user), set on the first write. Olderrecords have none.- `worktree` is set by the CLI when the session ran in a linked worktree.+- `leftOff` is one line on where the session left off, written by the session-end+ pass, so a later session can tell whether it continues this one. Older records+ have none.- `addedAt` and `touchedAt` on a node are stamped by `session write`, never takenfrom agent input. A resent node that changes nothing keeps `touchedAt`.diff --git a/docs/schema/session-input.json b/docs/schema/session-input.jsonindex 505137d..d51956d 100644--- a/docs/schema/session-input.json+++ b/docs/schema/session-input.json@@ -71,6 +71,10 @@}}},+ "leftOff": {+ "type": "string",+ "maxLength": 400+ },"nodes": {"type": "array","items": {diff --git a/docs/schema/session.json b/docs/schema/session.jsonindex 2212c4b..72c5a24 100644--- a/docs/schema/session.json+++ b/docs/schema/session.json@@ -103,6 +103,10 @@],"additionalProperties": false},+ "leftOff": {+ "type": "string",+ "maxLength": 400+ },"nodes": {"default": [],"type": "array",diff --git a/packages/cli/skills/record/SKILL.md b/packages/cli/skills/record/SKILL.mdindex c43c2d3..c6f9463 100644--- a/packages/cli/skills/record/SKILL.md+++ b/packages/cli/skills/record/SKILL.md@@ -66,8 +66,10 @@ Every message grows from an earlier one; a thread that starts something new is a- Default: the previous message. `parent: null` only if it would work as a new chat's firstmessage. Back to an older thread: that message is the parent, the previous one goes in `links`.- A first message continuing earlier work: `parent` is `<sessionId>:<stable id>`;- `candidates` lists the last messages of the most recent other sessions. The target must be- a message of an earlier session of this project.+ `candidates` lists the most recent other sessions: where each left off (`leftOff`), its+ branches with the message each ends at (`last`), and its last messages. Read `leftOff`+ first, then the branches; the usual target is a branch's `last`. The target must be a+ message of an earlier session of this project.- Unsure: use the previous message. A wrong "continue" hides a branch; a wrong branch breaksthe chain.- `links`: up to 5 earlier messages it builds on besides the parent.diff --git a/packages/cli/src/agents/claude/transcripts.ts b/packages/cli/src/agents/claude/transcripts.tsindex a89a27f..1bb2d86 100644--- a/packages/cli/src/agents/claude/transcripts.ts+++ b/packages/cli/src/agents/claude/transcripts.ts@@ -159,7 +159,12 @@ export function displayTurn(turn: ChatTurn, roots: string[]): ChatTurn {...turn,text: capped(text),replies: turn.replies.map(capped),- tools: { ...turn.tools, files: turn.tools.files.map(relative) },+ // Steps and questions feed the recorder only; the map keeps the counts.+ tools: {+ commands: turn.tools.commands,+ files: turn.tools.files.map(relative),+ other: turn.tools.other,+ },};}@@ -172,6 +177,14 @@ const CLEAR = /<command-name>\s*\/clear\s*<\/command-name>/;const LINE_UUID = /"uuid":"([^"]+)"/;const LINE_PARENT = /"parentUuid":"([^"]+)"/;+/** Keeps a step or question list short and free of repeats. */+const LIST_LIMIT = 40;++function addOnce(tools: ToolUse, key: "steps" | "asks", text: string): void {+ const list = tools[key] ?? [];+ if (list.length < LIST_LIMIT && !list.includes(text)) tools[key] = [...list, text.slice(0, 300)];+}+/** 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;@@ -181,11 +194,27 @@ function addAssistant(turn: ChatTurn, line: Record<string, unknown>): void {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") {+ const input = (block.input ?? {}) as Record<string, unknown>;+ const path = input.file_path;+ if (block.name === "Bash") {+ turn.tools.commands += 1;+ if (typeof input.description === "string" && input.description.trim() !== "")+ addOnce(turn.tools, "steps", input.description.trim());+ } 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;+ } else {+ turn.tools.other += 1;+ if (block.name === "AskUserQuestion" && Array.isArray(input.questions))+ for (const q of input.questions as { question?: unknown; options?: unknown }[]) {+ if (typeof q?.question !== "string") continue;+ const options = Array.isArray(q.options)+ ? (q.options as { label?: unknown }[])+ .map((o) => o?.label)+ .filter((label): label is string => typeof label === "string")+ : [];+ addOnce(turn.tools, "asks", `${q.question} [${options.join(" | ")}]`);+ }+ }}}}diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.tsindex 9e0302d..033c53b 100644--- a/packages/cli/src/agents/types.ts+++ b/packages/cli/src/agents/types.ts@@ -28,6 +28,14 @@ export interface ToolUse {files: string[];/** Any other tool calls (reads, searches, web, subagents…). */other: number;+ /**+ * What the shell commands were for, in the agent's own words (their+ * descriptions, never the commands). Only for the recorder's prompt; the map+ * does not show it.+ */+ steps?: string[];+ /** Questions the agent asked the user, with their options. Only for the recorder's prompt. */+ asks?: string[];}/** One user message and what the agent wrote back before the next one. */diff --git a/packages/cli/src/commands/backfill.ts b/packages/cli/src/commands/backfill.tsindex f40dc74..6e01dc8 100644--- a/packages/cli/src/commands/backfill.ts+++ b/packages/cli/src/commands/backfill.ts@@ -9,6 +9,7 @@ import { LockBusyError, withLock } from "../store/lock.js";import { projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";import { loadConfig, loadProject, loadSession } from "../store/stores.js";+import { closeSession } from "./close.js";import { sessionWrite } from "./session.js";/** How much of one message or reply goes into the prompt. */@@ -30,9 +31,26 @@ function turnBlock(turn: ChatTurn): string {`USER: ${cut(turn.text)}`,`AGENT: ${agent}`,`TOOLS: ${tools}`,+ ...actionLines(turn),].join("\n");}+/**+ * What the agent actually did in a turn, beyond its words: the questions it+ * asked with their options, the files it edited and its steps. The recorder+ * finds the agent's choices and the topic of a turn in these.+ */+export function actionLines(turn: ChatTurn): string[] {+ const lines: string[] = [];+ const asks = turn.tools.asks ?? [];+ if (asks.length > 0) lines.push(`ASKED THE USER: ${asks.slice(0, 5).join(" ; ")}`);+ if (turn.tools.files.length > 0)+ lines.push(`FILES EDITED: ${turn.tools.files.slice(0, 12).join(", ")}`);+ const steps = turn.tools.steps ?? [];+ if (steps.length > 0) lines.push(`STEPS: ${steps.slice(0, 15).join(" ; ")}`);+ return lines;+}+function recordPart(record: Session | undefined): string {if (!record || record.nodes.length === 0) return "The record has no nodes yet.";const lines = record.nodes.map(@@ -90,7 +108,7 @@ export function catchUpPrompt(): string {return ["You add the missing part of a cogit lineage record, a map of the user's messages.",- "Below are the user's messages that have no node yet, each followed by the agent's written replies and a count of its tool calls.",+ "Below are the user's messages that have no node yet, each followed by the agent's written replies and what the agent did: the questions it asked the user with their options, the files it edited and its steps. Use these to find the agent's technical decisions and what it rejected.","",rules(language, messageSummaries, recorder),"",@@ -148,7 +166,7 @@ function claudeBin(): string {* Runs the agent once, headless and without session persistence, with the prompt* on stdin. Resolves with stdout; a missing binary or a failed run rejects.*/-function runClaude(prompt: string, model: string, env: NodeJS.ProcessEnv): Promise<string> {+export function runClaude(prompt: string, model: string, env: NodeJS.ProcessEnv): Promise<string> {return new Promise((resolve, reject) => {const child = spawn(claudeBin(),@@ -210,7 +228,12 @@ async function missingTurns(* its answer through `session write` (validation, redaction, stamping, build).* A busy session lock means another catch-up already runs, which is not an error.*/-export async function backfillTail(dir: string, sessionId: string, io: Io): Promise<void> {+export async function backfillTail(+ dir: string,+ sessionId: string,+ io: Io,+ opts: { close?: boolean } = {},+): Promise<void> {const { root } = await resolveProjectRoot(dir);const project = await loadProject(root);if (!project.found) throw new CliError(`${root} is not initialized; run \`cogit init\` first`);@@ -230,6 +253,7 @@ export async function backfillTail(dir: string, sessionId: string, io: Io): Prom}if (turns.length === 0) {io.out(`session ${sessionId} has nothing left to record`);+ if (opts.close === true) await closeSession(root, sessionId, io);// Story 9.3: `recordCommit: auto` still commits what an earlier update wrote.await maybeAutoCommit(root, sessionId, io.env);return;@@ -251,6 +275,8 @@ export async function backfillTail(dir: string, sessionId: string, io: Io): Prom// Story 12.1: a side run fills empty fields and new nodes; it never rewrites// what the main agent wrote.await sessionWrite({ dir: root, by: "side" }, io, async () => JSON.stringify(payload));+ // At the session end the closing pass reads the whole session once it is all recorded.+ if (opts.close === true) await closeSession(root, sessionId, io);// The session end wrote the last messages after the last code commit; auto// mode commits exactly those record files now (Story 9.3).await maybeAutoCommit(root, sessionId, io.env);diff --git a/packages/cli/src/commands/close.ts b/packages/cli/src/commands/close.tsnew file mode 100644index 0000000..d8bf207--- /dev/null+++ b/packages/cli/src/commands/close.ts@@ -0,0 +1,297 @@+import { type ChatTurn, defaultAgent } from "../agents/index.js";+import type { Io } from "../io.js";+import { hashTurns, upgradeSessionIds } from "../messages.js";+import { parseMessageRef } from "../schema/common.js";+import { BranchSummary, type Session, Status } from "../schema/session.js";+import { applyEvents, readEvents } from "../store/events.js";+import { loadConfig, loadSession } from "../store/stores.js";+import { actionLines, agentRecord, resultText, runClaude } from "./backfill.js";+import { type CandidateSession, candidateSessions, sessionWrite } from "./session.js";++/**+ * The session-end pass (the "closing link"). One side-model call over the whole+ * session: it splits the session into threads and says what each grew from;+ * the parents follow from that in code, so the model never has to pick a parent+ * id per message (which it does poorly: it defaults to "the previous one"). The+ * same call writes the branch summaries (L1) and the one line on where the+ * session left off (L0).+ */++/** One thread as the model returns it. */+export interface Thread {+ name: string;+ /** Ranges of labels, e.g. "m7-m15, m19-m33": a thread can pause for a detour. */+ messages: string;+ /** The message the thread starts from; null for a brand-new start. */+ from?: string | null;+ asked?: string;+ outcome?: string;+ open?: string;+}++/** How much of a message and a reply the pass reads: the gist is enough to tell topics apart. */+const USER_LIMIT = 400;+const REPLY_LIMIT = 220;++function clip(text: string, limit: number): string {+ const flat = text.replace(/\s+/g, " ").trim();+ return flat.length > limit ? `${flat.slice(0, limit)}…` : flat;+}++/** The labels a range list names, in the order given, limited to the known ones. */+export function threadMembers(spec: string, known: ReadonlySet<string>): string[] {+ const out: string[] = [];+ for (const match of spec.matchAll(/m(\d+)(?:\s*[-–]\s*m?(\d+))?/g)) {+ const from = Number(match[1]);+ const to = match[2] === undefined ? from : Number(match[2]);+ for (let n = from; n <= Math.min(to, from + 10_000); n += 1)+ if (known.has(`m${n}`)) out.push(`m${n}`);+ }+ return out;+}++/**+ * Parents from threads, by label, for every message after the first:+ * - the same thread as the previous message: the previous message;+ * - back to a thread seen before: that thread's latest message;+ * - the first message of a new thread: its `from` when that is an earlier+ * message, a root when `from` is null, else the previous message.+ * A message no thread names keeps the previous message.+ */+export function deriveParents(order: string[], threads: Thread[]): Map<string, string | null> {+ const known = new Set(order);+ const threadOf = new Map<string, number>();+ threads.forEach((thread, index) => {+ for (const label of threadMembers(thread.messages, known))+ if (!threadOf.has(label)) threadOf.set(label, index);+ });+ const position = new Map(order.map((label, at) => [label, at]));+ const latest = new Map<number, string>();+ const parents = new Map<string, string | null>();+ order.forEach((label, at) => {+ const thread = threadOf.get(label);+ if (at > 0) {+ const previous = order[at - 1] as string;+ let parent: string | null = previous;+ if (thread !== undefined && thread !== threadOf.get(previous)) {+ const seen = latest.get(thread);+ if (seen !== undefined) parent = seen;+ else {+ const from = threads[thread]?.from;+ if (from === null) parent = null;+ else if (typeof from === "string") {+ const target = from.split(":").at(-1) ?? "";+ const targetAt = position.get(target);+ if (targetAt !== undefined && targetAt < at) parent = target;+ }+ }+ }+ parents.set(label, parent);+ }+ if (thread !== undefined) latest.set(thread, label);+ });+ return parents;+}++/** A branch summary within the schema's limits, or undefined when the model left it thin. */+function summaryOf(thread: Thread): BranchSummary | undefined {+ const parsed = BranchSummary.safeParse({+ title: clip(thread.name ?? "", 80),+ asked: clip(thread.asked ?? "", 300),+ outcome: clip(thread.outcome ?? "", 600),+ open: clip(thread.open ?? "", 300),+ });+ return parsed.success ? parsed.data : undefined;+}++function candidatePart(sessions: CandidateSession[]): string[] {+ if (sessions.length === 0) return [];+ const lines = sessions.map((s) => {+ const branches = s.branches+ .map(+ (b) =>+ ` · ${b.title}${b.open ? ` (open: ${clip(b.open, 120)})` : ""} → ${s.sessionId}:${b.last.id}`,+ )+ .join("\n");+ const last = s.messages.at(-1);+ return [+ `- ${s.sessionId} "${s.title}" (${s.updatedAt})${s.leftOff ? `: ${s.leftOff}` : ""}`,+ branches,+ last ? ` · last message: ${last.title} → ${s.sessionId}:${last.id}` : "",+ ]+ .filter(Boolean)+ .join("\n");+ });+ return [+ "Earlier sessions of this project, newest first, with where each left off and its threads:",+ ...lines,+ 'If the first message continues one of them, set "continues" to the reference after → of the thread it picks up; otherwise null. Only when the first message clearly continues that work.',+ "",+ ];+}++/** The prompt of the session-end pass. */+export function closePrompt(+ turns: ChatTurn[],+ record: Session,+ opts: { language: string; candidates: CandidateSession[]; status: boolean },+): string {+ const writing = opts.language === "auto" ? "the conversation's language" : opts.language;+ const nodes = new Map(record.nodes.map((node) => [node.id, node]));+ const labelOf = new Map(turns.map((turn) => [turn.hash ?? turn.id, turn.label ?? turn.id]));+ let previousAt: string | undefined;+ const blocks = turns.map((turn) => {+ const node = nodes.get(turn.hash ?? turn.id);+ const gap =+ previousAt === undefined+ ? 0+ : Math.round((Date.parse(turn.at) - Date.parse(previousAt)) / 60_000);+ previousAt = turn.at;+ const parent = node?.parent ? (labelOf.get(node.parent) ?? node.parent) : "null";+ return [+ `### ${turn.label ?? turn.id} · ${turn.at}${gap >= 30 ? ` · gap ${gap} min` : ""} · current parent=${parent}`,+ ...(node ? [`title: ${node.title}`] : []),+ `USER: ${clip(turn.text, USER_LIMIT)}`,+ `AGENT: ${clip(turn.replies.join(" "), REPLY_LIMIT) || "(no written reply)"}`,+ ...actionLines(turn).map((line) => line.slice(0, 260)),+ ].join("\n");+ });+ const status = opts.status+ ? ', "status": {"goal": "one sentence", "done": ["..."], "pending": [{"text": "...", "needsUser": true}], "next": "a concrete step"}'+ : "";+ return [+ "You close a cogit lineage record at the end of a coding session. Each user message below is listed with what the agent did.",+ "Split the session into threads. A thread is one line of work with one goal: a feature, a bug, a release, a discussion, an idea.",+ "",+ "Rules:",+ '- Every message belongs to exactly one thread. List a thread\'s messages as ranges, e.g. "m7-m15, m19-m33": a thread can pause for a detour and resume later.',+ "- A detour is a thread the user opens in the middle of another one and then leaves (a side question, an idea, an unrelated check). When the user goes back to the earlier work, those messages belong to the earlier thread again.",+ "- Short approvals and follow-ups ('do it', 'yap hadi', 'commit at', 'ne durumdayız?') belong to the thread of the message before them.",+ "- Similar subject is not enough to join threads; the goal must be the same.",+ "- For each thread give `from`: the message whose outcome it starts from. Usually the message just before the thread's first message; for a detour the message it interrupts (the same); for a new task after a finished one, the last message of the finished thread; null only if the first message would work as the first message of a brand-new chat.",+ "",+ "Then write a branch summary for every thread (asked: what the user wanted; outcome: what it meant and what came of it; open: what is still open, or empty), and leftOff: one line saying where the session left off, so a later session can decide whether to continue it.",+ `Write text in ${writing}; JSON keys stay English. Never invent what is not in the record. Never write secrets, credentials or personal data.`,+ "",+ ...candidatePart(opts.candidates),+ `Return only one JSON object, no code fences: {"threads": [{"name": "a few words", "messages": "m1-m6, m55-m66", "from": null, "asked": "...", "outcome": "...", "open": ""}], "leftOff": "..."${+ opts.candidates.length > 0 ? ', "continues": null' : ""+ }${status}}`,+ "",+ ...blocks,+ ].join("\n");+}++/**+ * Turns the pass's answer into a `session write` payload: derived parents for+ * the messages whose parent changes, a branch summary on each thread's first+ * message, `leftOff`, and the first message's earlier-session parent. The side+ * write keeps every parent and note the main agent wrote.+ */+export function closePayload(+ answer: Record<string, unknown>,+ turns: ChatTurn[],+ record: Session,+ opts: { status: boolean },+): Record<string, unknown> {+ const nodes = new Map(record.nodes.map((node) => [node.id, node]));+ const recorded = turns.filter((turn) => nodes.has(turn.hash ?? turn.id));+ const order = recorded.map((turn) => turn.label ?? turn.id);+ const idOf = new Map(recorded.map((turn) => [turn.label ?? turn.id, turn.hash ?? turn.id]));+ const threads = (Array.isArray(answer.threads) ? answer.threads : []).filter(+ (t): t is Thread => typeof t === "object" && t !== null && typeof t.messages === "string",+ );+ const parents = threads.length > 0 ? deriveParents(order, threads) : new Map();+ const branches = new Map<string, BranchSummary>();+ const known = new Set(order);+ for (const thread of threads) {+ const first = threadMembers(thread.messages, known).sort(+ (a, b) => order.indexOf(a) - order.indexOf(b),+ )[0];+ const summary = summaryOf(thread);+ if (first !== undefined && summary && !branches.has(first)) branches.set(first, summary);+ }++ const out: Record<string, unknown>[] = [];+ order.forEach((label, at) => {+ const id = idOf.get(label) as string;+ const node = nodes.get(id);+ if (!node) return;+ const entry: Record<string, unknown> = { id: label, kind: "message", title: node.title };+ let changed = false;+ if (at === 0) {+ const continues = answer.continues;+ if (+ node.parent === null &&+ typeof continues === "string" &&+ parseMessageRef(continues).sessionId !== null+ ) {+ entry.parent = continues;+ changed = true;+ }+ } else if (parents.has(label)) {+ const parent = parents.get(label) as string | null;+ const parentId = parent === null ? null : (idOf.get(parent) ?? parent);+ if (parentId !== (node.parent ?? null)) {+ entry.parent = parent;+ changed = true;+ }+ }+ const branch = branches.get(label);+ if (branch) {+ entry.branch = branch;+ changed = true;+ }+ if (changed) out.push(entry);+ });++ const payload: Record<string, unknown> = { sessionId: record.sessionId, nodes: out };+ if (typeof answer.leftOff === "string" && answer.leftOff.trim() !== "")+ payload.leftOff = clip(answer.leftOff, 400);+ // A malformed status would fail the whole write; it is left out instead.+ const status = opts.status ? Status.safeParse(answer.status) : undefined;+ if (status?.success) payload.status = status.data;+ return payload;+}++/**+ * `cogit backfill <session-id> --close`: runs the session-end pass over a+ * recorded session and writes its answer as the side model. Nothing recorded+ * yet means nothing to close.+ */+export async function closeSession(root: string, sessionId: string, io: Io): Promise<void> {+ const agent = defaultAgent();+ const file = await agent.findTranscript(sessionId, io.env);+ const loaded = await loadSession(root, sessionId);+ if (!file || !loaded.found || !loaded.ok) {+ io.out(`session ${sessionId} has no record to close`);+ return;+ }+ const turns = hashTurns(sessionId, await agent.readConversation(file));+ const upgraded = upgradeSessionIds(loaded.data, turns);+ const record: Session = {+ ...upgraded,+ nodes: applyEvents(upgraded.nodes, await readEvents(root, sessionId)),+ };+ const recorded = new Set(record.nodes.map((node) => node.id));+ const closing = turns.filter((turn) => recorded.has(turn.hash ?? turn.id));+ if (closing.length === 0) {+ io.out(`session ${sessionId} has no recorded message to close`);+ return;+ }+ const config = await loadConfig(io.env);+ const firstNode = record.nodes.find((node) => node.id === (closing[0]?.hash ?? ""));+ // Only a first message that still hangs from nothing looks at earlier sessions.+ const candidates =+ firstNode && firstNode.parent === null ? await candidateSessions(root, sessionId, io.env) : [];+ // The status belongs to the main agent unless only the side model records.+ const status = config.recorder === "side";+ const prompt = closePrompt(closing, record, {+ language: config.language,+ candidates,+ status,+ });+ const answer = agentRecord(resultText(await runClaude(prompt, config.sideModel, io.env)));+ const payload = closePayload(answer, closing, record, { status });+ await sessionWrite({ dir: root, by: "side" }, io, async () => JSON.stringify(payload));+}diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex d827446..b54584e 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -140,7 +140,7 @@ export async function sessionWrite(labels: hashesToLabels(messages),crossTargets,by,- sideOwnsParent: sideOwnedParents(events),+ sideOwnsParent: sideOwnedParents(events, base?.nodes),});warnings = merged.warnings;const changes = structureChanges(merged.session, base, io.now(), by);@@ -452,27 +452,81 @@ async function newMessages(return out;}-/** How many earlier sessions and messages `session show` offers for a parent. */-const CANDIDATE_SESSIONS = 3;+/**+ * How many earlier sessions `session show` offers for a parent, and how many of+ * their last messages. Each session comes with its one-line `leftOff` (L0) and+ * its branches (L1), so the pick reaches past a session's last messages.+ */+const CANDIDATE_SESSIONS = 8;const CANDIDATE_MESSAGES = 3;+const CANDIDATE_BRANCHES = 8;/** A first message that says, in the user's words, that it continues earlier work. */const CONTINUES = /\b(devam|kaldığımız yerden|continue)\b/i;+/** One earlier session as the parent pick sees it: L0, its branches (L1) and its last messages. */+export interface CandidateSession {+ sessionId: string;+ title: string;+ updatedAt: string;+ leftOff?: string;+ /** Each branch with the message it ends at, the usual target for "continue this thread". */+ branches: { title: string; open?: string; first: string; last: { id: string; title: string } }[];+ messages: { id: string; title: string; at?: string }[];+}+/**- * The candidates for hanging a session's first message from an earlier session- * (8.6): the last messages of the most recently updated other sessions, with a- * hint when the transcript shows a handoff file being read or the message itself- * says it continues. Cheap hints from records and the transcript, no model call.+ * The branches of a record, oldest first: every message that carries a branch+ * summary, with the newest message that grew from it before another branch began.*/-async function parentCandidates(+function branchesOf(nodes: Session["nodes"]): CandidateSession["branches"] {+ const messages = nodes+ .filter((node) => node.kind === "message")+ .sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));+ const byId = new Map(messages.map((node) => [node.id, node]));+ /** The nearest message at or above this one that starts a branch. */+ const startOf = (id: string): string | null => {+ const seen = new Set<string>();+ let cur: string | null = id;+ while (cur !== null && !seen.has(cur)) {+ seen.add(cur);+ const node = byId.get(cur);+ if (!node) return null;+ if (node.branch) return node.id;+ cur = node.parent ?? null;+ }+ return null;+ };+ const last = new Map<string, Session["nodes"][number]>();+ for (const node of messages) {+ const start = startOf(node.id);+ if (start !== null) last.set(start, node);+ }+ return messages+ .filter((node) => node.branch)+ .slice(-CANDIDATE_BRANCHES)+ .map((node) => {+ const end = last.get(node.id) ?? node;+ return {+ title: node.branch?.title ?? node.title,+ ...(node.branch?.open ? { open: node.branch.open } : {}),+ first: node.id,+ last: { id: end.id, title: end.title },+ };+ });+}++/**+ * The most recently updated other sessions of the project, newest first, as+ * the parent pick of a first message sees them (Story 8.6, widened in 0.21).+ * Cheap: records only, plus a transcript read for a legacy record's ids.+ */+export async function candidateSessions(root: string,sessionId: string,- first: SessionMessage,- io: Io,-): Promise<Record<string, unknown>> {- // Newest records first, and only the three that keep a message need their- // transcript read (old ids become stable ones there).+ env: NodeJS.ProcessEnv,+ limit = CANDIDATE_SESSIONS,+): Promise<CandidateSession[]> {const recent: Session[] = [];for (const id of await listSessionIds(projectPaths(root).sessions)) {if (id === sessionId) continue;@@ -480,47 +534,58 @@ async function parentCandidates(if (loaded.found && loaded.ok) recent.push(loaded.data);}recent.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));- const others: {- sessionId: string;- title: string;- updatedAt: string;- messages: { id: string; title: string; at?: string }[];- }[] = [];+ const out: CandidateSession[] = [];for (const candidate of recent) {- const nodes = [...candidate.nodes]- .filter((node) => node.kind === "message")- .sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));- if (nodes.length === 0) continue;+ if (!candidate.nodes.some((node) => node.kind === "message")) continue;// Only a legacy record needs its transcript (for stable ids); the rest are// already keyed by them, so most sessions cost one file read.- const messages = await readSessionMessages(root, candidate.sessionId, io.env);+ const messages = await readSessionMessages(root, candidate.sessionId, env);const record = await effectiveRecord(root,candidate.sessionId,{ found: true, ok: true, data: candidate, warnings: [] },messages,);- const effective = (record?.nodes ?? nodes)+ const nodes = record?.nodes ?? candidate.nodes;+ const effective = nodes.filter((node) => node.kind === "message").sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));- others.push({+ out.push({sessionId: candidate.sessionId,title: candidate.title,updatedAt: candidate.updatedAt,+ ...(candidate.leftOff ? { leftOff: candidate.leftOff } : {}),+ branches: branchesOf(nodes),messages: effective.slice(-CANDIDATE_MESSAGES).map(({ id: messageId, title, at }) => ({id: messageId,title,...(at === undefined ? {} : { at }),})),});- if (others.length === CANDIDATE_SESSIONS) break;+ if (out.length === limit) break;}+ return out;+}++/**+ * The candidates for hanging a session's first message from an earlier session+ * (8.6), with a hint when the transcript shows a handoff file being read or the+ * message itself says it continues. Cheap hints from records and the transcript,+ * no model call.+ */+async function parentCandidates(+ root: string,+ sessionId: string,+ first: SessionMessage,+ io: Io,+): Promise<Record<string, unknown>> {+ const sessions = await candidateSessions(root, sessionId, io.env);const file = await agent.findTranscript(sessionId, io.env);const handoff = file ? await agent.readsHandoff(file).catch(() => false) : false;return {forMessage: { id: first.hash, label: first.label },...(handoff || CONTINUES.test(first.text) ? { continuesHint: true } : {}),- sessions: others,+ sessions,};}diff --git a/packages/cli/src/hooks/sessionend.ts b/packages/cli/src/hooks/sessionend.tsindex 350488f..592dc30 100644--- a/packages/cli/src/hooks/sessionend.ts+++ b/packages/cli/src/hooks/sessionend.ts@@ -1,6 +1,5 @@-import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";-import { applyEvents, readEvents } from "../store/events.js";-import { loadConfig, loadSession } from "../store/stores.js";+import { readSessionMessages } from "../messages.js";+import { loadConfig } from "../store/stores.js";import type { HookContext } from "./run.js";/**@@ -9,6 +8,10 @@ import type { HookContext } from "./run.js";* is not stored: the catch-up reads whatever messages still have no node, so a* child that dies is retried when the session is opened next.*+ * The catch-up then runs the closing pass (threads, parents, branch summaries,+ * where the session left off) over the whole session, so it starts even when+ * every message already has a node.+ ** With `recordCommit: auto` (Story 9.3) the last record is committed detached as* well; the catch-up does that itself once it has written, so this only starts a* commit when there is nothing to catch up (or the catch-up is off).@@ -16,9 +19,9 @@ import type { HookContext } from "./run.js";export async function onSessionEnd(ctx: HookContext): Promise<undefined> {if (!ctx.initialized) return undefined;const config = await loadConfig(ctx.env);- const autoCommit = config.recordCommit === "auto";const commitOnly = (): void => {- if (autoCommit) ctx.spawnDetached(["record-commit", ctx.sessionId, "-C", ctx.root]);+ if (config.recordCommit === "auto")+ ctx.spawnDetached(["record-commit", ctx.sessionId, "-C", ctx.root]);};if (!config.sessionEndCatchUp) {commitOnly();@@ -29,17 +32,6 @@ export async function onSessionEnd(ctx: HookContext): Promise<undefined> {commitOnly();return undefined;}- const record = await loadSession(ctx.root, ctx.sessionId);- let recorded = new Set<string>();- if (record.found && record.ok) {- const upgraded = upgradeSessionIds(record.data, messages);- const events = await readEvents(ctx.root, ctx.sessionId);- recorded = new Set(applyEvents(upgraded.nodes, events).map((node) => node.id));- }- if (messages.every((message) => isRecorded(recorded, message))) {- commitOnly();- return undefined;- }- ctx.spawnDetached(["backfill", ctx.sessionId, "--tail", "-C", ctx.root]);+ ctx.spawnDetached(["backfill", ctx.sessionId, "--tail", "--close", "-C", ctx.root]);return undefined;}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 3a9899e..70782b7 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -387,14 +387,21 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =.argument("<session-id>", "session id").option("-C, --dir <dir>", "project directory", ".").option("--tail", "only this session's messages that have no node yet")- .addHelpText("after", examples("cogit backfill 9c32ab18 --tail"))+ .option(+ "--close",+ "then run the session-end pass: threads, parents, branch summaries and where it left off",+ )+ .addHelpText(+ "after",+ examples("cogit backfill 9c32ab18 --tail", "cogit backfill 9c32ab18 --tail --close"),+ ).action(- run(async (sessionId: string, opts: { dir: string; tail?: boolean }) => {+ run(async (sessionId: string, opts: { dir: string; tail?: boolean; close?: boolean }) => {if (opts.tail !== true)throw new CliError("backfill of past sessions is not available yet; run `cogit backfill <session-id> --tail`",);- await backfillTail(opts.dir, sessionId, makeIo(false));+ await backfillTail(opts.dir, sessionId, makeIo(false), { close: opts.close === true });}),);diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.tsindex 81a5911..77c59eb 100644--- a/packages/cli/src/schema/merge.ts+++ b/packages/cli/src/schema/merge.ts@@ -193,6 +193,9 @@ export function mergeSession(title: input.title ?? base.title,epoch: input.epoch === undefined ? base.epoch : input.epoch,status: input.status ?? base.status,+ ...(input.leftOff === undefined && base.leftOff === undefined+ ? {}+ : { leftOff: input.leftOff ?? base.leftOff }),nodes: [...nodes.values()],updatedAt: now,};diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.tsindex bec7332..76545ba 100644--- a/packages/cli/src/schema/session.ts+++ b/packages/cli/src/schema/session.ts@@ -119,6 +119,12 @@ export const Session = z.object({startedAt: IsoDate,updatedAt: IsoDate,status: Status.default({ goal: "", done: [], pending: [], next: "" }),+ /**+ * One line on where the session left off (L0), so a later session can tell+ * whether it continues this one without reading the branches. Written by the+ * session-end pass; old records have none.+ */+ leftOff: z.string().max(400).optional(),nodes: z.array(LineageNode).default([]),/** The linked git worktree the session ran in; set by the CLI, never by the agent. */worktree: z.object({ path: z.string().min(1), branch: z.string().min(1).nullable() }).optional(),@@ -154,6 +160,7 @@ export const SessionInput = z.object({title: z.string().max(200).optional(),epoch: Slug.nullable().optional(),status: Status.optional(),+ leftOff: z.string().max(400).optional(),nodes: z.array(LineageNodeInput).optional(),});diff --git a/packages/cli/src/store/events.ts b/packages/cli/src/store/events.tsindex b484c3f..6fcd5a2 100644--- a/packages/cli/src/store/events.ts+++ b/packages/cli/src/store/events.ts@@ -50,15 +50,23 @@ export async function appendEvents(/*** Messages whose latest parent event was written by the side model (Story* 12.1). A side run may correct those parents, and only those: a parent the- * main agent wrote stays put.+ * main agent wrote stays put. A root leaves no event, so a message the side+ * model added (its title is the side model's) with no parent event is the side+ * model's too; otherwise the session-end pass could never move a side root.*/-export function sideOwnedParents(events: readonly SessionEvent[]): Set<string> {+export function sideOwnedParents(+ events: readonly SessionEvent[],+ nodes: readonly LineageNode[] = [],+): Set<string> {const owners = new Map<string, SessionEvent["by"]>();for (const event of events) {if (event.type === "parent") owners.set(event.msg, event.by);}const owned = new Set<string>();for (const [msg, by] of owners) if (by === "side") owned.add(msg);+ for (const node of nodes)+ if (node.kind === "message" && !owners.has(node.id) && node.by?.title === "side")+ owned.add(node.id);return owned;}diff --git a/packages/cli/test/close.test.ts b/packages/cli/test/close.test.tsnew file mode 100644index 0000000..dc0b5a6--- /dev/null+++ b/packages/cli/test/close.test.ts@@ -0,0 +1,301 @@+import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { beforeEach, describe, expect, it } from "vitest";+import type { ChatTurn } from "../src/agents/types.js";+import { backfillTail } from "../src/commands/backfill.js";+import {+ closePayload,+ closePrompt,+ closeSession,+ deriveParents,+ type Thread,+ threadMembers,+} from "../src/commands/close.js";+import { init } from "../src/commands/init.js";+import { sessionWrite } from "../src/commands/session.js";+import { messageHash } from "../src/messages.js";+import type { Session } from "../src/schema/session.js";+import { readEvents, sideOwnedParents } from "../src/store/events.js";+import { loadSession } from "../src/store/stores.js";+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";++const labels = (n: number) => Array.from({ length: n }, (_, i) => `m${i + 1}`);+const thread = (messages: string, from?: string | null): Thread => ({+ name: messages,+ messages,+ ...(from === undefined ? {} : { from }),+});++describe("threadMembers", () => {+ it("reads ranges and single labels, and drops unknown ones", () => {+ const known = new Set(labels(10));+ expect(threadMembers("m1-m3, m7 m9–m12", known)).toEqual(["m1", "m2", "m3", "m7", "m9", "m10"]);+ expect(threadMembers("nothing here", known)).toEqual([]);+ });+});++describe("deriveParents", () => {+ it("chains a thread, hangs a detour's return from the thread it left", () => {+ // m1-m3 work, m4-m5 a detour, m6-m7 back to the work.+ const parents = deriveParents(labels(7), [thread("m1-m3, m6-m7", null), thread("m4-m5", "m3")]);+ expect(Object.fromEntries(parents)).toEqual({+ m2: "m1",+ m3: "m2",+ m4: "m3",+ m5: "m4",+ m6: "m3",+ m7: "m6",+ });+ });++ it("starts a new thread from its `from`, a root on null, the previous message otherwise", () => {+ const order = labels(5);+ expect(deriveParents(order, [thread("m1-m3"), thread("m4-m5", "m1")]).get("m4")).toBe("m1");+ expect(deriveParents(order, [thread("m1-m3"), thread("m4-m5", null)]).get("m4")).toBeNull();+ // A forward or unknown `from` falls back to the previous message.+ expect(deriveParents(order, [thread("m1-m3"), thread("m4-m5", "m5")]).get("m4")).toBe("m3");+ expect(deriveParents(order, [thread("m1-m3"), thread("m4-m5")]).get("m4")).toBe("m3");+ expect(deriveParents(order, [thread("m1-m3"), thread("m4-m5", "s0:m2")]).get("m4")).toBe("m2");+ });++ it("keeps the previous message for a message no thread names", () => {+ expect(deriveParents(labels(3), [thread("m1")]).get("m3")).toBe("m2");+ });+});++const turn = (n: number, extra: Partial<ChatTurn> = {}): ChatTurn => ({+ id: `m${n}`,+ label: `m${n}`,+ hash: `h${n}`,+ at: `2026-10-23T10:0${n}:00.000Z`,+ text: `message ${n}`,+ replies: [`reply ${n}`],+ tools: { commands: 0, files: [], other: 0 },+ ...extra,+});++function session(nodes: Partial<Session["nodes"][number]>[]): Session {+ return {+ schema: 1,+ sessionId: "s1",+ agent: "claude-code",+ title: "",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: nodes.map((n) => ({ parent: null, kind: "message", title: "t", ...n }) as never),+ };+}++describe("closePrompt", () => {+ it("lists every message with its current parent, actions, gaps and the candidates", () => {+ const turns = [+ turn(1),+ turn(2, {+ at: "2026-10-23T11:00:00.000Z",+ tools: { commands: 1, files: ["a.ts"], other: 0, steps: ["Run the tests"] },+ }),+ ];+ const prompt = closePrompt(+ turns,+ session([+ { id: "h1", title: "First" },+ { id: "h2", title: "Second", parent: "h1" },+ ]),+ {+ language: "auto",+ status: false,+ candidates: [+ {+ sessionId: "s0",+ title: "Before",+ updatedAt: T0,+ leftOff: "Release waits",+ branches: [{ title: "Release", first: "h9", last: { id: "h10", title: "Tag it" } }],+ messages: [{ id: "h10", title: "Tag it" }],+ },+ ],+ },+ );+ expect(prompt).toContain("### m2 · 2026-10-23T11:00:00.000Z · gap 59 min · current parent=m1");+ expect(prompt).toContain("title: Second");+ expect(prompt).toContain("STEPS: Run the tests");+ expect(prompt).toContain("FILES EDITED: a.ts");+ expect(prompt).toContain('- s0 "Before" (' + T0 + "): Release waits");+ expect(prompt).toContain("· Release → s0:h10");+ expect(prompt).toContain('"continues": null');+ expect(prompt).not.toContain('"status"');+ expect(+ closePrompt(turns, session([]), { language: "Turkish", status: true, candidates: [] }),+ ).toContain('"status": {"goal"');+ });+});++describe("closePayload", () => {+ const turns = [turn(1), turn(2), turn(3), turn(4)];+ const record = session([+ { id: "h1", title: "One" },+ { id: "h2", title: "Two", parent: "h1" },+ { id: "h3", title: "Three", parent: "h2" },+ { id: "h4", title: "Four", parent: "h3" },+ ]);+ const summary = { asked: "asked", outcome: "outcome", open: "" };++ it("sends only changed parents, a summary on each thread's first message and leftOff", () => {+ const payload = closePayload(+ {+ threads: [+ { name: "Work", messages: "m1-m2, m4", from: null, ...summary },+ { name: "Detour", messages: "m3", from: "m2", ...summary, asked: "" },+ "not a thread",+ ],+ leftOff: " Work done, detour open ",+ status: { goal: "g" },+ },+ turns,+ record,+ { status: false },+ );+ expect(payload).toEqual({+ sessionId: "s1",+ leftOff: "Work done, detour open",+ nodes: [+ {+ id: "m1",+ kind: "message",+ title: "One",+ branch: { title: "Work", asked: "asked", outcome: "outcome", open: "" },+ },+ // The detour's summary has no "asked", so it is left out.+ { id: "m4", kind: "message", title: "Four", parent: "m2" },+ ],+ });+ });++ it("hangs a root first message from an earlier session and keeps a valid status", () => {+ const payload = closePayload(+ {+ threads: [],+ continues: "s0:h10",+ status: { goal: "g", done: [], pending: [], next: "n" },+ },+ turns,+ record,+ { status: true },+ );+ expect(payload.nodes).toEqual([{ id: "m1", kind: "message", title: "One", parent: "s0:h10" }]);+ expect(payload.status).toEqual({ goal: "g", done: [], pending: [], next: "n" });+ expect(+ closePayload({ continues: "h10", status: { pending: "x" } }, turns, record, { status: true }),+ ).toEqual({ sessionId: "s1", nodes: [] });+ });+});++describe("sideOwnedParents", () => {+ it("counts a side-added root without a parent event as the side model's", () => {+ const nodes = session([+ { id: "a", by: { title: "side" } },+ { id: "b" },+ { id: "c", by: { title: "side" } },+ ]).nodes;+ const owned = sideOwnedParents(+ [{ at: T0, type: "parent", msg: "c", target: "a", by: "agent" }],+ nodes,+ );+ expect([...owned]).toEqual(["a"]);+ });+});++describe("backfill --tail --close", () => {+ let dir: string;+ let root: string;+ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ });++ it("has nothing to close without a record or a recorded message", async () => {+ const env = envFor(dir);+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(env));+ const io = fakeIo(env);+ await closeSession(root, "s1", io);+ expect(io.lines).toContain("session s1 has no record to close");++ const folder = join(env.CLAUDE_CONFIG_DIR ?? "", "projects", "proj");+ await mkdir(folder, { recursive: true });+ await writeFile(+ join(folder, "s1.jsonl"),+ `${JSON.stringify({ type: "user", timestamp: T0, message: { role: "user", content: "hi" } })}\n`,+ );+ await sessionWrite({ dir: root }, fakeIo(env), async () =>+ JSON.stringify({ sessionId: "s1", nodes: [{ id: "topic", kind: "phase", title: "Topic" }] }),+ );+ await closeSession(root, "s1", io);+ expect(io.lines).toContain("session s1 has no recorded message to close");+ });++ it("rewires a side-recorded session from its threads and saves where it left off", async () => {+ const bin = join(dir, "bin");+ await mkdir(bin, { recursive: true });+ const answer = JSON.stringify({+ threads: [+ { name: "Work", messages: "m1-m2, m4", from: null, asked: "a", outcome: "o", open: "" },+ { name: "Detour", messages: "m3", from: "m2", asked: "a", outcome: "o", open: "x" },+ ],+ leftOff: "Work done; the detour is open",+ });+ await writeFile(+ join(bin, "claude"),+ `#!/usr/bin/env node+let input = "";+process.stdin.on("data", (c) => { input += c; });+process.stdin.on("end", async () => {+ (await import("node:fs")).writeFileSync(${JSON.stringify(join(dir, "prompt.txt"))}, input);+ process.stdout.write(JSON.stringify({ result: ${JSON.stringify(answer)} }));+});+`,+ );+ await chmod(join(bin, "claude"), 0o755);+ const env = { ...envFor(dir), PATH: `${bin}:${process.env.PATH ?? ""}` };+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(env));+ const folder = join(envFor(dir).CLAUDE_CONFIG_DIR ?? "", "projects", "proj");+ await mkdir(folder, { recursive: true });+ const at = (m: number) => `2026-10-23T10:0${m}:00.000Z`;+ const typed = (m: number) => ({+ type: "user",+ timestamp: at(m),+ message: { role: "user", content: `message ${m}` },+ });+ await writeFile(+ join(folder, "s1.jsonl"),+ `${[1, 2, 3, 4].map((m) => JSON.stringify(typed(m))).join("\n")}\n`,+ );+ // The periodic side run chained everything to the previous message.+ await sessionWrite({ dir: root, by: "side" }, fakeIo(env), async () =>+ JSON.stringify({+ sessionId: "s1",+ nodes: [1, 2, 3, 4].map((m) => ({+ id: `m${m}`,+ kind: "message",+ title: `T${m}`,+ parent: m === 1 ? null : `m${m - 1}`,+ })),+ }),+ );++ await backfillTail(root, "s1", fakeIo(env), { close: true });+ const loaded = await loadSession(root, "s1");+ const saved = loaded.found && loaded.ok ? loaded.data : undefined;+ const h = (m: number) => messageHash("s1", { at: at(m), text: `message ${m}` });+ expect(saved?.leftOff).toBe("Work done; the detour is open");+ expect(saved?.nodes.find((n) => n.id === h(1))?.branch?.title).toBe("Work");+ expect(saved?.nodes.find((n) => n.id === h(3))?.branch?.open).toBe("x");+ const events = await readEvents(root, "s1");+ expect(events.at(-1)).toMatchObject({ type: "parent", msg: h(4), target: h(2), by: "side" });+ expect(await readFile(join(dir, "prompt.txt"), "utf8")).toContain(+ "Split the session into threads",+ );+ });+});diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.tsindex 5acaf30..fea859f 100644--- a/packages/cli/test/hooks.test.ts+++ b/packages/cli/test/hooks.test.ts@@ -507,18 +507,25 @@ describe("runHook", () => {await initialized(2);await transcript([typed("first", 1)]);expect(await sessionEnd()).toBeUndefined();- expect(spawned).toEqual([["/plugin/dist/cli.js", "backfill", "s1", "--tail", "-C", root]]);+ expect(spawned).toEqual([+ ["/plugin/dist/cli.js", "backfill", "s1", "--tail", "--close", "-C", root],+ ]);});- it("does not spawn at session end when everything is recorded or catch-up is off", async () => {+ it("still starts the closing pass at session end when everything is recorded", async () => {await initialized(2);await transcript([typed("first", 1)]);await sessionWrite({ dir: root }, fakeIo(env), async () =>JSON.stringify({ sessionId: "s1", nodes: [{ id: "m1", kind: "message", title: "First" }] }),);expect(await sessionEnd()).toBeUndefined();- expect(spawned).toEqual([]);+ expect(spawned).toEqual([+ ["/plugin/dist/cli.js", "backfill", "s1", "--tail", "--close", "-C", root],+ ]);+ });+ it("does not spawn at session end when the catch-up is off", async () => {+ await initialized(2);await transcript([typed("second", 2)]);await configSet("sessionEndCatchUp", "false", fakeIo(env));expect(await sessionEnd()).toBeUndefined();diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.tsindex 586e8cc..a55ce42 100644--- a/packages/cli/test/session.test.ts+++ b/packages/cli/test/session.test.ts@@ -627,27 +627,36 @@ ${line("second", 2)}});});- it("offers the last messages of recent sessions when the first message may continue one", async () => {+ it("offers recent sessions with where they left off, their branches and last messages", async () => {await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));+ const branch = (title: string) => ({ title, asked: "a", outcome: "o", open: "" });await sessionWrite({ dir: root }, fakeIo(envFor(dir)), async () =>JSON.stringify({sessionId: "first",title: "Epic 8 work",+ leftOff: "Epic 8 half done; the release waits",nodes: [- { id: "m1", kind: "message", title: "One", at: "2026-10-22T09:00:00.000Z" },+ {+ id: "m1",+ kind: "message",+ title: "One",+ at: "2026-10-22T09:00:00.000Z",+ branch: branch("Epic 8"),+ },{ id: "m2", kind: "message", title: "Two", parent: "m1", at: "2026-10-22T09:10:00.000Z" },{id: "m3",kind: "message",title: "Three",- parent: "m2",+ parent: "m1",at: "2026-10-22T09:20:00.000Z",+ branch: { ...branch("Detour"), open: "still open" },},{id: "m4",kind: "message",title: "Four",- parent: "m3",+ parent: "m2",at: "2026-10-22T09:30:00.000Z",},],@@ -671,7 +680,18 @@ ${line("second", 2)}sessionId: "first",title: "Epic 8 work",updatedAt: T0,- // The last three messages, oldest first: enough to pick the parent.+ leftOff: "Epic 8 half done; the release waits",+ // Each branch ends at the newest message that grew from it.+ branches: [+ { title: "Epic 8", first: "m1", last: { id: "m4", title: "Four" } },+ {+ title: "Detour",+ open: "still open",+ first: "m3",+ last: { id: "m3", title: "Three" },+ },+ ],+ // The last three messages, oldest first.messages: [{ id: "m2", title: "Two", at: "2026-10-22T09:10:00.000Z" },{ id: "m3", title: "Three", at: "2026-10-22T09:20:00.000Z" },diff --git a/packages/cli/test/transcript.test.ts b/packages/cli/test/transcript.test.tsindex 775dff6..dc948c0 100644--- a/packages/cli/test/transcript.test.ts+++ b/packages/cli/test/transcript.test.ts@@ -115,6 +115,42 @@ describe("readConversation", () => {expect(turns[0]?.tools).toEqual({ commands: 1, files: ["/p/a.ts"], other: 2 });});+ it("keeps the agent's steps and questions for the recorder, and drops them for the map", async () => {+ const file = join(await tempDir(), "s1.jsonl");+ const agent = (content: unknown[]) => ({ type: "assistant", message: { content } });+ const bash = (description?: string) => ({+ type: "tool_use",+ name: "Bash",+ input: { command: "git status", ...(description ? { description } : {}) },+ });+ const lines = [+ user("first", {}, 1),+ agent([bash("Show working tree status"), bash("Show working tree status"), bash()]),+ agent([+ {+ type: "tool_use",+ name: "AskUserQuestion",+ input: {+ questions: [+ { question: "Which order?", options: [{ label: "A" }, { label: "B" }] },+ { options: [] },+ ],+ },+ },+ ]),+ ];+ await writeFile(file, lines.map((line) => JSON.stringify(line)).join("\n"));+ const [turn] = await readConversation(file);+ expect(turn?.tools).toEqual({+ commands: 3,+ files: [],+ other: 1,+ steps: ["Show working tree status"],+ asks: ["Which order? [A | B]"],+ });+ expect(turn && displayTurn(turn, []).tools).toEqual({ commands: 3, files: [], other: 1 });+ });+it("marks the message after a broken uuid chain as resumed", async () => {const file = join(await tempDir(), "s1.jsonl");const lines = [