Skip to content

armgit / cogit

Public Imported from GitHub
0

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

feat(session): stable message ids and append-only structure facts

Eren07d253320870
diff --git a/CHANGELOG.md b/CHANGELOG.md
index da351e1..550119e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
-- The conversation store: `build` appends what the drill-down needs for turns not stored yet to `.codelineage/conversations/<sessionId>.jsonl.gz` (one gzip member per append, redacted with the same secret net as the page), reads it before the transcript, and keeps showing a session's conversation after Claude Code deletes the transcript. `init` writes `.codelineage/.gitignore` with `conversations/` even when `.codelineage/` is committed, an existing project gets the line on its next build, and the README explains where the raw chat lives.
+- The conversation store: `build` appends what the drill-down needs for turns not stored yet to `.codelineage/conversations/<sessionId>.jsonl.gz` (one gzip member per append, redacted with the same secret net as the page), reads it before the transcript, and keeps showing a session's conversation after Claude Code deletes the transcript. `init` writes `.codelineage/.gitignore` with `conversations/` even when `.codelineage/` is committed, an existing project gets the line on its next build, and the README explains where the raw chat lives. Stored turns keep the message's stable id, so ids survive the transcript.
+- Stable message ids: a message node is now `h` + the first 12 hex of the SHA-256 over `{sessionId, uuid, at, text}`, derived from the user message and not from its parent, so correcting a parent never renames a message (and its notes stay attached). `m1`, `m2`, … stay as display labels; `session show` prints both and `session write` accepts either. Records written before this are renamed on load and persisted on their next write.
+- Structure as append-only facts: each session gets `sessions/<sessionId>.events.jsonl` (`{ at, type: parent|link|unlink, msg, target, by }`), replayed to build the graph (last parent wins). Notes stay in the session JSON keyed by the stable id and may be updated freely. A changed parent or link appends an event instead of overwriting; unchanged input writes nothing, and an old record's existing structure is seeded before its first change. The hidden `codelineage migrate [dir]` upgrades a project's old records in one go (idempotent, backup in `.codelineage/backup-pre-8.5/`).
### Fixed
- Map: long message titles and branch labels in the git graph wrap onto more lines (the row grows) instead of being cut with an ellipsis; a not-yet-summarized message shows up to 200 characters of its text instead of 80.
diff --git a/packages/cli/skills/lineage/SKILL.md b/packages/cli/skills/lineage/SKILL.md
index 458e113..fed4277 100644
--- a/packages/cli/skills/lineage/SKILL.md
+++ b/packages/cli/skills/lineage/SKILL.md
@@ -42,15 +42,17 @@ Build one JSON object:
## 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`.
+lists the user's messages that have no node yet, in order, each with a stable
+`id` (`h…`), the `label` the user reads (`m1`, `m2`, …), its time and the start
+of its text. Send one `message` node for every one of them; skip none, even a
+short "ok" or "go on".
+
+- `id`: the message's `id` from `newMessages`. The `label` (`m1`) is accepted
+ too, and so is either form for a parent or link: the CLI maps it to the stable
+ id. The stable id never changes when a parent is corrected.
- `kind`: `"message"`.
-- `parent`: the id of the earlier message it reacts to (see below), or `null`
- for a new root.
+- `parent`: the id (or label) 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 a
long paste; name what it is.
@@ -90,10 +92,14 @@ earlier one, and a thread that starts something new is a root.
- `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.
+- Correcting a parent or a link later is safe and is recorded as a new fact: the
+ message keeps its id and its notes. Send the node again with the new `parent`
+ or `links`; resending an unchanged node writes nothing.
- `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.
+ decides. `lastMessages` lists the last recorded messages with their stable
+ `id`, `label` and parent.
## Summarize each branch
diff --git a/packages/cli/src/commands/backfill.ts b/packages/cli/src/commands/backfill.ts
index ddcc67d..a2e1234 100644
--- a/packages/cli/src/commands/backfill.ts
+++ b/packages/cli/src/commands/backfill.ts
@@ -1,6 +1,8 @@
import { spawn } from "node:child_process";
import { CliError, type Io } from "../io.js";
+import { hashTurns, isRecorded, type SessionMessage, upgradeSessionIds } from "../messages.js";
import type { Session } from "../schema/session.js";
+import { applyEvents, readEvents } from "../store/events.js";
import { LockBusyError, withLock } from "../store/lock.js";
import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
@@ -23,7 +25,7 @@ function turnBlock(turn: ChatTurn): string {
const { commands, other } = turn.tools;
const tools = `${commands} command(s), ${turn.tools.files.length} file(s) edited, ${other} other tool call(s)`;
return [
- `### ${turn.id} · ${turn.at}`,
+ `### ${turn.label ?? turn.id} · ${turn.at}`,
`USER: ${cut(turn.text)}`,
`AGENT: ${agent}`,
`TOOLS: ${tools}`,
@@ -165,13 +167,18 @@ async function missingTurns(
root: string,
sessionId: string,
env: NodeJS.ProcessEnv,
-): Promise<ChatTurn[]> {
+): Promise<SessionMessage[]> {
const file = await findTranscript(sessionId, env);
if (!file) return [];
- const turns = await readConversation(file);
+ const turns = hashTurns(sessionId, await readConversation(file));
const loaded = await loadSession(root, sessionId);
- const recorded = new Set(loaded.found && loaded.ok ? loaded.data.nodes.map((n) => n.id) : []);
- return turns.filter((turn) => !recorded.has(turn.id));
+ let recorded = new Set<string>();
+ if (loaded.found && loaded.ok) {
+ const upgraded = upgradeSessionIds(loaded.data, turns);
+ const events = await readEvents(root, sessionId);
+ recorded = new Set(applyEvents(upgraded.nodes, events).map((node) => node.id));
+ }
+ return turns.filter((turn) => !isRecorded(recorded, turn));
}
/**
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 9600411..bb492f8 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -1,20 +1,26 @@
import { ensureConversationGitignore } from "../git.js";
import { CliError, type Io } from "../io.js";
+import {
+ hashTurns,
+ isRecorded,
+ type SessionMessage,
+ storedMessages,
+ upgradeSessionIds,
+} from "../messages.js";
import { redactDeep } from "../redact.js";
import type { Session } from "../schema/session.js";
-import { appendConversationTurns, readConversationStore } from "../store/conversations.js";
+import {
+ appendConversationHashes,
+ appendConversationTurns,
+ readConversationStore,
+} from "../store/conversations.js";
+import { applyEvents, readEvents } from "../store/events.js";
import { atomicWrite } from "../store/fs.js";
import { withLock } from "../store/lock.js";
import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";
-import {
- type ChatTurn,
- displayTurn,
- excerpt,
- readConversation,
- readUserMessages,
-} from "../transcript.js";
+import { type ChatTurn, displayTurn, excerpt, readConversation } from "../transcript.js";
import { buildViewModel, embedViewModel } from "../view/lineage.js";
import type { LineageViewModel, ViewChatTurn, ViewPendingMessage } from "../view/model.js";
import { buildPanel } from "../view/panel.js";
@@ -41,12 +47,17 @@ export interface TranscriptViews {
chats: Map<string, ViewChatTurn[]>;
/** User messages with no node yet, per session, titled for the map. */
pending: Map<string, ViewPendingMessage[]>;
+ /** The record as the map sees it: stable ids and the replayed structure. */
+ sessions: Session[];
+ /** User messages with no node yet, per session, counted from the transcripts. */
+ unrecorded: Map<string, number>;
}
/** Drops the fields only the drill-down needs (uuid, hints) and keeps the contract. */
-function toViewTurn(turn: ChatTurn, id = turn.id): ViewChatTurn {
+function toViewTurn(turn: ChatTurn): ViewChatTurn {
return {
- id,
+ id: turn.hash ?? turn.id,
+ ...(turn.label === undefined ? {} : { label: turn.label }),
at: turn.at,
text: turn.text,
replies: turn.replies,
@@ -69,6 +80,8 @@ async function readTranscriptViews(
): Promise<TranscriptViews> {
const chats = new Map<string, ViewChatTurn[]>();
const pending = new Map<string, ViewPendingMessage[]>();
+ const prepared: Session[] = [];
+ const unrecorded = new Map<string, number>();
for (const session of sessions) {
const file = transcripts.get(session.sessionId);
const recordsMessages = session.nodes.some((node) => node.kind === "message");
@@ -86,75 +99,90 @@ async function readTranscriptViews(
);
}
}
- let turns: ViewChatTurn[];
- if (transcript && transcript.length > 0) {
- const fresh = transcript.filter(
+ const fromTranscript =
+ transcript && transcript.length > 0 ? hashTurns(session.sessionId, transcript) : null;
+ if (fromTranscript) {
+ const fresh = fromTranscript.filter(
(turn) => turn.uuid !== undefined && !storedByUuid.has(turn.uuid),
);
- if (fresh.length > 0) {
- const displayed = fresh.map((turn) => displayTurn(turn, roots));
- try {
- await appendConversationTurns(root, session.sessionId, displayed);
- } catch (err) {
- // Losing the transcript is a real risk, but a failed append must never
- // fail the map: the page still shows this build's conversation.
- io.warn(
- `could not store the conversation of ${session.sessionId}: ${(err as Error).message}`,
+ const hashes = new Map(
+ fromTranscript.flatMap((turn) =>
+ turn.uuid === undefined ? [] : [[turn.uuid, turn.hash] as [string, string]],
+ ),
+ );
+ try {
+ if (fresh.length > 0)
+ await appendConversationTurns(
+ root,
+ session.sessionId,
+ fresh.map((turn) => displayTurn(turn, roots)),
);
- }
+ // Turns stored before ids were stable get theirs now, before Claude Code
+ // deletes the transcript this hash comes from.
+ await appendConversationHashes(root, session.sessionId, hashes);
+ } catch (err) {
+ // Losing the transcript is a real risk, but a failed append must never
+ // fail the map: the page still shows this build's conversation.
+ io.warn(
+ `could not store the conversation of ${session.sessionId}: ${(err as Error).message}`,
+ );
}
- turns = transcript.map((turn) => {
+ }
+ const messages: SessionMessage[] | null = fromTranscript
+ ? fromTranscript
+ : stored.length > 0
+ ? storedMessages(session.sessionId, stored)
+ : transcript
+ ? []
+ : null;
+
+ // Stable ids for old `m1` nodes, then the structure from the facts file.
+ const upgraded = messages ? upgradeSessionIds(session, messages) : session;
+ const events = await readEvents(root, session.sessionId);
+ const effective: Session = {
+ ...upgraded,
+ nodes: applyEvents(upgraded.nodes, events),
+ };
+ prepared.push(effective);
+
+ let turns: ViewChatTurn[];
+ if (fromTranscript) {
+ turns = fromTranscript.map((turn) => {
const kept = turn.uuid === undefined ? undefined : storedByUuid.get(turn.uuid);
return kept
- ? { id: turn.id, at: kept.at, text: kept.text, replies: kept.replies, tools: kept.tools }
+ ? toViewTurn({
+ ...turn,
+ at: kept.at,
+ text: kept.text,
+ replies: kept.replies,
+ tools: kept.tools,
+ })
: toViewTurn(displayTurn(turn, roots));
});
- } else {
+ } else if (stored.length > 0) {
// No readable transcript: the store is all that is left. Its append-only
- // order is the transcript order, so `m1`, `m2`, … still line up.
- turns = stored.map((turn, index) => toViewTurn({ ...turn, id: `m${index + 1}` }));
+ // order is the transcript order, so labels still line up.
+ turns = (messages ?? []).map((message) => toViewTurn(message));
+ } else {
+ turns = [];
}
- const recorded = new Set(session.nodes.map((node) => node.id));
- const missing = turns.filter((turn) => !recorded.has(turn.id));
+ const recorded = new Set(effective.nodes.map((node) => node.id));
+ const missing = (messages ?? []).filter((message) => !isRecorded(recorded, message));
if (missing.length > 0) {
pending.set(
session.sessionId,
- missing.map((turn) => ({
- id: turn.id,
- at: turn.at,
- title: excerpt(turn.text, PENDING_TITLE_LENGTH) || "(blank message)",
+ missing.map((message) => ({
+ id: message.hash,
+ label: message.label,
+ at: message.at,
+ title: excerpt(message.text, PENDING_TITLE_LENGTH) || "(blank message)",
})),
);
+ unrecorded.set(session.sessionId, missing.length);
}
if (recordsMessages || missing.length > 0) chats.set(session.sessionId, turns);
}
- return { chats, pending };
-}
-
-/**
- * User messages with no node, per session, counted from the transcripts. The
- * SessionEnd hook normally records them; while the catch-up is off this count is
- * the only sign. An unreadable transcript is skipped, never failing the build.
- */
-export async function countUnrecorded(
- sessions: Session[],
- transcripts: ReadonlyMap<string, string>,
-): Promise<Map<string, number>> {
- const counts = new Map<string, number>();
- for (const session of sessions) {
- const file = transcripts.get(session.sessionId);
- if (!file) continue;
- let messages;
- try {
- messages = await readUserMessages(file);
- } catch {
- continue;
- }
- const recorded = new Set(session.nodes.map((node) => node.id));
- const missing = messages.filter((message) => !recorded.has(message.id)).length;
- if (missing > 0) counts.set(session.sessionId, missing);
- }
- return counts;
+ return { chats, pending, sessions: prepared, unrecorded };
}
/**
@@ -190,7 +218,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
const views = await readTranscriptViews(sessions, transcripts, root, io);
const built = buildViewModel({
project: project.data,
- sessions,
+ sessions: views.sessions,
path: root,
generatedAt: io.now(),
transcripts: new Set(transcripts.keys()),
@@ -198,9 +226,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
pending: views.pending,
// With the catch-up on, the hook records the tail at session end, so the
// count would only be a stale warning about work already scheduled.
- unrecorded: config.sessionEndCatchUp
- ? undefined
- : await countUnrecorded(sessions, transcripts),
+ unrecorded: config.sessionEndCatchUp ? undefined : views.unrecorded,
});
// The skill already avoids secrets; this is the safety net before rendering.
const redacted = redactDeep(built);
diff --git a/packages/cli/src/commands/migrate.ts b/packages/cli/src/commands/migrate.ts
new file mode 100644
index 0000000..775afdb
--- /dev/null
+++ b/packages/cli/src/commands/migrate.ts
@@ -0,0 +1,89 @@
+import { copyFile, mkdir, readdir } from "node:fs/promises";
+import { join } from "node:path";
+import type { Io } from "../io.js";
+import { MESSAGE_HASH, readSessionMessages, upgradeSessionIds } from "../messages.js";
+import { appendEvents, readEvents, seedEvents } from "../store/events.js";
+import { projectPaths } from "../store/paths.js";
+import { resolveProjectRoot } from "../store/root.js";
+import { listSessionIds, loadSession, updateSession } from "../store/stores.js";
+
+/** Where the pre-migration copy of every record is kept. */
+export const BACKUP_DIR = "backup-pre-8.5";
+
+export interface MigrateResult {
+ /** Sessions whose records now carry stable ids and an events file. */
+ migrated: number;
+ /** Sessions an earlier run already migrated, or that have no messages to map. */
+ skipped: number;
+}
+
+/**
+ * Story 8.5 migration for records written before it: every message node's `m1`
+ * label becomes its stable `h…` id and the record's structure moves into the
+ * append-only events file. Runs once per project; a second run finds the events
+ * and changes nothing. A session whose transcript and stored conversation are
+ * both gone cannot be hashed and is left exactly as it is.
+ */
+export async function migrateIds(dir: string, io: Io): Promise<MigrateResult> {
+ const { root } = await resolveProjectRoot(dir);
+ const paths = projectPaths(root);
+ const ids = await listSessionIds(paths.sessions);
+ let backedUp = false;
+ let migrated = 0;
+ let skipped = 0;
+
+ for (const id of ids) {
+ const loaded = await loadSession(root, id);
+ if (!loaded.found) continue;
+ if (!loaded.ok) {
+ io.warn(`session ${id}: skipped, ${loaded.error}`);
+ skipped += 1;
+ continue;
+ }
+ if (!loaded.data.nodes.some((node) => node.kind === "message")) continue;
+ const events = await readEvents(root, id);
+ if (events.length > 0) {
+ skipped += 1;
+ continue;
+ }
+ const messages = await readSessionMessages(root, id, io.env);
+ if (!messages) {
+ io.warn(`session ${id}: no transcript or stored conversation, ids left as they are`);
+ skipped += 1;
+ continue;
+ }
+ const upgraded = upgradeSessionIds(loaded.data, messages);
+ const unmapped = upgraded.nodes.filter(
+ (node) => node.kind === "message" && !MESSAGE_HASH.test(node.id),
+ );
+ if (unmapped.length > 0) {
+ io.warn(
+ `session ${id}: ${unmapped.length} message(s) have no transcript line, left as they are`,
+ );
+ skipped += 1;
+ continue;
+ }
+ if (!backedUp) {
+ await backupRecords(paths.sessions, paths.backup(BACKUP_DIR));
+ backedUp = true;
+ }
+ await updateSession(root, id, async (cur) => {
+ const next = upgradeSessionIds(cur ?? loaded.data, messages);
+ // Re-checked under the session lock: a concurrent write may have seeded it.
+ if ((await readEvents(root, id)).length === 0)
+ await appendEvents(root, id, seedEvents(next.nodes, io.now()));
+ return next;
+ });
+ migrated += 1;
+ }
+ return { migrated, skipped };
+}
+
+/** Copies every record (and any events file) once, before anything changes. */
+async function backupRecords(sessions: string, backup: string): Promise<void> {
+ await mkdir(backup, { recursive: true });
+ for (const entry of await readdir(sessions)) {
+ if (!entry.endsWith(".json") && !entry.endsWith(".events.jsonl")) continue;
+ await copyFile(join(sessions, entry), join(backup, entry));
+ }
+}
diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.ts
index ad232af..4bf73cc 100644
--- a/packages/cli/src/commands/session.ts
+++ b/packages/cli/src/commands/session.ts
@@ -1,10 +1,21 @@
import { readFile, rm } from "node:fs/promises";
import { resolve } from "node:path";
import { CliError, type Io } from "../io.js";
+import {
+ hashesToLabels,
+ isRecorded,
+ labelsToHashes,
+ messageOrder,
+ readSessionMessages,
+ type SessionMessage,
+ upgradeSessionIds,
+} from "../messages.js";
import { redactDeep } from "../redact.js";
import { Slug } from "../schema/common.js";
+import type { SessionEvent } from "../schema/events.js";
import { mergeSession } from "../schema/merge.js";
import { MESSAGE_ID, type Session, SessionInput } from "../schema/session.js";
+import { appendEvents, applyEvents, readEvents, seedEvents } from "../store/events.js";
import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import {
@@ -14,13 +25,7 @@ import {
loadSession,
updateSession,
} from "../store/stores.js";
-import {
- countUserLines,
- excerpt,
- findTranscript,
- readUserMessages,
- type UserMessage,
-} from "../transcript.js";
+import { countUserLines, excerpt, findTranscript } from "../transcript.js";
import { buildProject } from "./build.js";
export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {
@@ -68,7 +73,10 @@ export async function sessionWrite(
}
const { value: redacted, count } = redactDeep(parsed.data);
- const input = await stampMessageTimes(redacted, io);
+ // Both ids work: the agent may send the stable `h…` id, or the `m1` label it
+ // reads in `session show`; the CLI maps the label to the stable id.
+ const messages = await readSessionMessages(root, redacted.sessionId, io.env);
+ const input = nameMessages(redacted, messages, 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(
@@ -77,9 +85,25 @@ export async function sessionWrite(
}
let warnings: string[] = [];
- const saved = await updateSession(root, input.sessionId, (cur) => {
- const merged = mergeSession(cur, input, io.now());
+ const saved = await updateSession(root, input.sessionId, async (cur) => {
+ // A record written before 8.5 still names messages `m1`, `m2`, …; the file is
+ // rewritten with stable ids and the structure seeds the events file below.
+ const upgraded = cur && messages ? upgradeSessionIds(cur, messages) : cur;
+ const events = await readEvents(root, input.sessionId);
+ const base = upgraded ? { ...upgraded, nodes: applyEvents(upgraded.nodes, events) } : undefined;
+ const merged = mergeSession(base, input, io.now(), {
+ ...(messages ? { order: messageOrder(messages) } : {}),
+ labels: hashesToLabels(messages),
+ });
warnings = merged.warnings;
+ const changes = structureChanges(merged.session, base, io.now());
+ // The first structural change on an old record seeds the facts it already
+ // holds, so replaying the file from then on gives the same graph.
+ const seed =
+ events.length === 0 && changes.length > 0 && base?.nodes.some((n) => n.kind === "message")
+ ? seedEvents(base.nodes, io.now())
+ : [];
+ await appendEvents(root, input.sessionId, [...seed, ...changes]);
// A write from the main checkout (e.g. after a resume) keeps the stored worktree.
return worktree ? { ...merged.session, worktree } : merged.session;
});
@@ -95,56 +119,82 @@ export async function sessionWrite(
}
}
-/** The session's transcript file and user messages, or null when it cannot be read. */
-async function transcriptMessages(
- sessionId: string,
- env: NodeJS.ProcessEnv,
-): Promise<{ file: string; messages: UserMessage[] } | null> {
- const file = await findTranscript(sessionId, env);
- if (!file) return null;
- try {
- return { file, messages: await readUserMessages(file) };
- } catch {
- return null;
- }
-}
-
-/** The session's user messages, or null when its transcript cannot be read. */
-async function userMessages(
- sessionId: string,
- env: NodeJS.ProcessEnv,
-): Promise<UserMessage[] | null> {
- return (await transcriptMessages(sessionId, env))?.messages ?? 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.
+ * Turns the agent's message ids into stable ids and takes each message's time
+ * from the transcript, so the map's order is the order the user wrote them,
+ * whatever the agent sent. A label (`m3`) and a stable id (`h…`) are both
+ * accepted; a node the session does not know keeps its id with a warning.
+ * Without a transcript (or a stored conversation) the agent's fields stay.
*/
-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`);
- }
+function nameMessages(
+ input: SessionInput,
+ messages: SessionMessage[] | null,
+ io: Io,
+): SessionInput {
+ const nodes = input.nodes ?? [];
+ if (!nodes.some((n) => n.kind === "message")) return input;
+ const byLabel = labelsToHashes(messages);
+ const byHash = new Map((messages ?? []).map((message) => [message.hash, message]));
+ const rename = (id: string): string => byLabel.get(id) ?? id;
return {
...input,
- nodes: input.nodes?.map((n) => {
- const at = n.kind === "message" ? times.get(n.id) : undefined;
- return at ? { ...n, at } : n;
+ nodes: nodes.map((node) => {
+ if (node.kind !== "message") return node;
+ const at = byHash.get(rename(node.id))?.at;
+ if (!messages) {
+ if (!MESSAGE_ID.test(node.id))
+ io.warn(`message node ${node.id}: expected an id like m1 from \`session show\``);
+ } else if (at === undefined) {
+ io.warn(`message node ${node.id}: no such message in the transcript`);
+ }
+ return {
+ ...node,
+ id: rename(node.id),
+ ...(at === undefined ? {} : { at }),
+ ...(node.parent === undefined || node.parent === null
+ ? {}
+ : { parent: rename(node.parent) }),
+ ...(node.links === undefined ? {} : { links: node.links.map(rename) }),
+ };
}),
};
}
+/**
+ * The parent/link events a merged record needs on top of the structure it had:
+ * a changed parent (including a correction back to root) and added or removed
+ * links. Unchanged input writes no event.
+ */
+function structureChanges(
+ merged: Session,
+ before: Session | undefined,
+ at: string,
+): SessionEvent[] {
+ const previous = new Map(
+ (before?.nodes ?? [])
+ .filter((node) => node.kind === "message")
+ .map((node) => [node.id, { parent: node.parent ?? null, links: node.links ?? [] }]),
+ );
+ const events: SessionEvent[] = [];
+ for (const node of merged.nodes) {
+ if (node.kind !== "message") continue;
+ const old = previous.get(node.id) ?? { parent: null, links: [] };
+ const parent = node.parent ?? null;
+ if (parent !== old.parent)
+ events.push({ at, type: "parent", msg: node.id, target: parent, by: "agent" });
+ const links = node.links ?? [];
+ for (const link of links) {
+ if (!old.links.includes(link))
+ events.push({ at, type: "link", msg: node.id, target: link, by: "agent" });
+ }
+ for (const link of old.links) {
+ if (!links.includes(link))
+ events.push({ at, type: "unlink", msg: node.id, target: link, by: "agent" });
+ }
+ }
+ return events;
+}
+
/**
* What the skill injects before the agent updates its record: the project's
* epochs, the summary language, a compact view of this session (node ids,
@@ -184,31 +234,35 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi
epochs: project.data.epochs.map(({ id, title }) => ({ id, title })),
session: null,
};
- if (loaded.found && loaded.ok) {
- const { title, epoch, status, nodes } = loaded.data;
+ const messages = await readSessionMessages(root, sessionId, io.env);
+ const labels = hashesToLabels(messages);
+ const effective = await effectiveRecord(root, sessionId, loaded, messages);
+ if (effective) {
+ const { title, epoch, status, nodes } = effective;
view.session = {
sessionId,
title,
epoch,
status,
- nodes: nodes.map(({ id, parent, kind, title }) => ({ id, parent, kind, title })),
+ nodes: nodes.map(({ id, parent, kind, title }) => {
+ const label = labels.get(id);
+ return { id, ...(label === undefined ? {} : { label }), parent, kind, title };
+ }),
};
- } else if (loaded.found) {
+ } else if (loaded.found && !loaded.ok) {
view.sessionError = loaded.error;
}
- const transcript = await transcriptMessages(sessionId, io.env);
- const messages = transcript?.messages ?? null;
if (messages) {
- const recorded = new Set(loaded.found && loaded.ok ? loaded.data.nodes.map((n) => n.id) : []);
view.messageCount = messages.length;
- view.newMessages = newMessages(messages, recorded);
+ view.newMessages = newMessages(messages, recordedIdsOf(effective), labels);
} else {
view.newMessages = null;
}
- view.lastMessages = lastMessages(loaded);
+ view.lastMessages = lastMessages(effective, labels);
// 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);
+ if (messages && messages.length === 0) {
+ const file = await findTranscript(sessionId, io.env);
+ const userLines = file ? await countUserLines(file).catch(() => 0) : 0;
if (userLines > 0)
view.transcriptWarning =
`the transcript has ${userLines} user line(s) but none read as a message; ` +
@@ -218,15 +272,40 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi
io.out(JSON.stringify(view, null, 2));
}
+/**
+ * The record as the map sees it: old `m1` ids renamed to stable ids when the
+ * messages are known, then the structure from the events file (Story 8.5).
+ */
+async function effectiveRecord(
+ root: string,
+ sessionId: string,
+ loaded: Loaded<Session>,
+ messages: SessionMessage[] | null,
+): Promise<Session | null> {
+ if (!loaded.found || !loaded.ok) return null;
+ const upgraded = messages ? upgradeSessionIds(loaded.data, messages) : loaded.data;
+ const events = await readEvents(root, sessionId);
+ return { ...upgraded, nodes: applyEvents(upgraded.nodes, events) };
+}
+
+function recordedIdsOf(session: Session | null): Set<string> {
+ return new Set(session?.nodes.map((node) => node.id) ?? []);
+}
+
/** 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.
+ * between, and a commit this session made between them. Hints, not rules. `id`
+ * is the stable id the record keeps; `label` is the `m1` the user reads.
*/
-function newMessages(messages: UserMessage[], recorded: Set<string>): Record<string, unknown>[] {
+function newMessages(
+ messages: SessionMessage[],
+ recorded: ReadonlySet<string>,
+ labels: ReadonlyMap<string, string>,
+): Record<string, unknown>[] {
return messages
.map((message, i) => {
const previous = i > 0 ? messages[i - 1] : undefined;
@@ -235,9 +314,10 @@ function newMessages(messages: UserMessage[], recorded: Set<string>): Record<str
: undefined;
return { message, gapMinutes };
})
- .filter(({ message }) => !recorded.has(message.id))
+ .filter(({ message }) => !isRecorded(recorded, message))
.map(({ message, gapMinutes }) => ({
- id: message.id,
+ id: message.hash,
+ label: labels.get(message.hash) ?? message.label,
at: message.at,
text: excerpt(message.text),
...(gapMinutes === undefined ? {} : { gapMinutes }),
@@ -246,14 +326,23 @@ function newMessages(messages: UserMessage[], recorded: Set<string>): Record<str
}));
}
-/** The last few recorded messages (id, title, parent) so the agent can pick a parent. */
+/** The last few recorded messages (stable id, label, title, parent) for a parent pick. */
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 }));
+ session: Session | null,
+ labels: ReadonlyMap<string, string>,
+): { id: string; label?: string; title: string; parent: string | null }[] {
+ if (!session) return [];
+ /** Send-order position from the label; a node without one keeps its stored place. */
+ const position = (id: string): number => {
+ const match = /^m([1-9][0-9]*)$/.exec(labels.get(id) ?? "");
+ return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;
+ };
+ const messages = session.nodes
+ .filter((n) => n.kind === "message")
+ .sort((a, b) => position(a.id) - position(b.id))
+ .slice(-LAST_MESSAGES);
+ return messages.map(({ id, title, parent }) => {
+ const label = labels.get(id);
+ return { id, ...(label === undefined ? {} : { label }), title, parent };
+ });
}
diff --git a/packages/cli/src/hooks/sessionend.ts b/packages/cli/src/hooks/sessionend.ts
index dd8f7ad..93f521a 100644
--- a/packages/cli/src/hooks/sessionend.ts
+++ b/packages/cli/src/hooks/sessionend.ts
@@ -1,5 +1,6 @@
+import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";
+import { applyEvents, readEvents } from "../store/events.js";
import { loadConfig, loadSession } from "../store/stores.js";
-import { findTranscript, readConversation } from "../transcript.js";
import type { HookContext } from "./run.js";
/**
@@ -12,17 +13,16 @@ export async function onSessionEnd(ctx: HookContext): Promise<undefined> {
if (!ctx.initialized) return undefined;
const config = await loadConfig(ctx.env);
if (!config.sessionEndCatchUp) return undefined;
- const file = await findTranscript(ctx.sessionId, ctx.env);
- if (!file) return undefined;
- let turns;
- try {
- turns = await readConversation(file);
- } catch {
- return undefined;
- }
+ const messages = await readSessionMessages(ctx.root, ctx.sessionId, ctx.env);
+ if (!messages || messages.length === 0) return undefined;
const record = await loadSession(ctx.root, ctx.sessionId);
- const recorded = new Set(record.found && record.ok ? record.data.nodes.map((n) => n.id) : []);
- if (turns.every((turn) => recorded.has(turn.id))) return undefined;
+ 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))) return undefined;
ctx.spawnDetached(["backfill", ctx.sessionId, "--tail", "-C", ctx.root]);
return undefined;
}
diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.ts
index 5380c0b..2f48e3a 100644
--- a/packages/cli/src/hooks/sessionstart.ts
+++ b/packages/cli/src/hooks/sessionstart.ts
@@ -1,5 +1,6 @@
+import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";
+import { applyEvents, readEvents } from "../store/events.js";
import { loadConfig, loadSession } from "../store/stores.js";
-import { findTranscript, readUserMessages } from "../transcript.js";
import type { HookContext, HookOutput } from "./run.js";
export const COMPACT_REQUEST =
@@ -54,16 +55,15 @@ function additionalContext(text: string): HookOutput {
async function compactRequest(ctx: HookContext): Promise<HookOutput | undefined> {
if (!ctx.initialized) return undefined;
- const file = await findTranscript(ctx.sessionId, ctx.env);
- if (!file) return undefined;
- let messages;
- try {
- messages = await readUserMessages(file);
- } catch {
- return undefined;
- }
+ const messages = await readSessionMessages(ctx.root, ctx.sessionId, ctx.env);
+ if (!messages) return undefined;
const record = await loadSession(ctx.root, ctx.sessionId);
- const recorded = new Set(record.found && record.ok ? record.data.nodes.map((n) => n.id) : []);
- if (messages.every((m) => recorded.has(m.id))) return undefined;
+ 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))) return undefined;
return additionalContext(COMPACT_REQUEST);
}
diff --git a/packages/cli/src/messages.ts b/packages/cli/src/messages.ts
new file mode 100644
index 0000000..1e6ce2e
--- /dev/null
+++ b/packages/cli/src/messages.ts
@@ -0,0 +1,162 @@
+import { createHash } from "node:crypto";
+import type { LineageNode, Session } from "./schema/session.js";
+import { readConversationStore } from "./store/conversations.js";
+import { type ChatTurn, findTranscript, readConversation } from "./transcript.js";
+
+/**
+ * A user message's stable id: `h` plus the first 12 hex of the SHA-256 over the
+ * canonical JSON of the message. The parent is NOT part of it, so correcting a
+ * parent never changes an id (unlike git, on purpose: the id names the message,
+ * not its place in the graph).
+ */
+export const MESSAGE_HASH = /^h[0-9a-f]{12}$/;
+
+/** The exact bytes hashed; fixed key order and no whitespace, so any machine agrees. */
+export function canonicalMessage(
+ sessionId: string,
+ message: { uuid?: string; at: string; text: string },
+): string {
+ return JSON.stringify({
+ sessionId,
+ uuid: message.uuid ?? "",
+ at: message.at,
+ text: message.text,
+ });
+}
+
+/** The stable id of one user message of a session. */
+export function messageHash(
+ sessionId: string,
+ message: { uuid?: string; at: string; text: string },
+): string {
+ return `h${createHash("sha256").update(canonicalMessage(sessionId, message)).digest("hex").slice(0, 12)}`;
+}
+
+/** The display label of the message at a position: `m1`, `m2`, … */
+export function messageLabel(index: number): string {
+ return `m${index + 1}`;
+}
+
+/** One user message with both its stable id and the label the user reads. */
+export interface SessionMessage extends ChatTurn {
+ hash: string;
+ label: string;
+}
+
+/** Adds the stable id and the display label to transcript turns, in order. */
+export function hashTurns(sessionId: string, turns: ChatTurn[]): SessionMessage[] {
+ return turns.map((turn, index) => ({
+ ...turn,
+ label: messageLabel(index),
+ hash: messageHash(sessionId, turn),
+ }));
+}
+
+/**
+ * The user's messages of a session, in send order, with their stable id and
+ * label. The transcript is authoritative; the project's own conversation store
+ * (8.4) stands in once Claude Code has deleted it. Null when neither is readable,
+ * which means ids cannot be hashed at all and labels stay the only names.
+ */
+export async function readSessionMessages(
+ root: string,
+ sessionId: string,
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<SessionMessage[] | null> {
+ const file = await findTranscript(sessionId, env);
+ if (file) {
+ try {
+ const turns = await readConversation(file);
+ if (turns.length > 0) return hashTurns(sessionId, turns);
+ const stored = await readConversationStore(root, sessionId);
+ if (stored.length > 0) return storedMessages(sessionId, stored);
+ // An empty transcript that parsed is still the truth: the user wrote nothing.
+ return [];
+ } catch {
+ // Fall through to the store.
+ }
+ }
+ const stored = await readConversationStore(root, sessionId);
+ return stored.length > 0 ? storedMessages(sessionId, stored) : null;
+}
+
+/**
+ * Stored turns keep the hash they were written with, so ids survive the
+ * transcript. A turn stored before hashes existed falls back to hashing its own
+ * fields (the text is the displayed one, so it may differ from the transcript
+ * hash; the transcript is gone anyway).
+ */
+export function storedMessages(
+ sessionId: string,
+ stored: Awaited<ReturnType<typeof readConversationStore>>,
+): SessionMessage[] {
+ return stored.map((turn, index) => ({
+ id: messageLabel(index),
+ label: messageLabel(index),
+ hash: turn.hash ?? messageHash(sessionId, turn),
+ uuid: turn.uuid,
+ at: turn.at,
+ text: turn.text,
+ replies: turn.replies,
+ tools: turn.tools,
+ }));
+}
+
+/** A message is recorded when either its stable id or its label names a node. */
+export function isRecorded(recorded: ReadonlySet<string>, message: SessionMessage): boolean {
+ return recorded.has(message.hash) || recorded.has(message.label);
+}
+
+/** Position of each message in send order, keyed by stable id. */
+export function messageOrder(messages: readonly SessionMessage[] | null): Map<string, number> {
+ return new Map((messages ?? []).map((message, index) => [message.hash, index]));
+}
+
+/** `m1` → `h…` for every message of the session. */
+export function labelsToHashes(messages: readonly SessionMessage[] | null): Map<string, string> {
+ return new Map((messages ?? []).map((message) => [message.label, message.hash]));
+}
+
+/** `h…` → `m1` for every message of the session, for warnings and display. */
+export function hashesToLabels(messages: readonly SessionMessage[] | null): Map<string, string> {
+ return new Map((messages ?? []).map((message) => [message.hash, message.label]));
+}
+
+/**
+ * Renames a record's message nodes from their old `m1` labels to stable ids, and
+ * their parents/links with them. Runs on load, so a record written before 8.5
+ * renders with stable ids without touching the file; `session write` persists it.
+ * A node the message table does not know keeps its id.
+ */
+export function upgradeSessionIds(session: Session, messages: readonly SessionMessage[]): Session {
+ const byLabel = labelsToHashes(messages);
+ const rename = (id: string): string => byLabel.get(id) ?? id;
+ const byId = new Map<string, LineageNode>();
+ /** Ids whose current entry came from a node that was already stable. */
+ const stable = new Set<string>();
+ for (const node of session.nodes) {
+ if (node.kind !== "message") {
+ byId.set(node.id, node);
+ continue;
+ }
+ const id = rename(node.id);
+ const next: LineageNode = {
+ ...node,
+ id,
+ ...(node.parent === undefined || node.parent === null ? {} : { parent: rename(node.parent) }),
+ ...(node.links === undefined ? {} : { links: node.links.map(rename) }),
+ };
+ if (!byId.has(id)) {
+ byId.set(id, next);
+ if (node.id === id) stable.add(id);
+ continue;
+ }
+ // A half-upgraded record can hold both the label and the stable id for one
+ // message; the node that already carried the stable id wins.
+ if (node.id === id && !stable.has(id)) {
+ byId.set(id, next);
+ stable.add(id);
+ }
+ }
+ return { ...session, nodes: [...byId.values()] };
+}
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index 24470cf..fdb199c 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -11,6 +11,7 @@ import {
} from "./commands/config.js";
import { epochAdd } from "./commands/epoch.js";
import { type InitOptions, init } from "./commands/init.js";
+import { migrateIds } from "./commands/migrate.js";
import { openPanel, openProject } from "./commands/open.js";
import { readStdin, sessionShow, sessionWrite } from "./commands/session.js";
import { runHook } from "./hooks/run.js";
@@ -175,6 +176,21 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
}),
);
+ // One-time data upgrade for records written before stable message ids (8.5).
+ program
+ .command("migrate", { hidden: true })
+ .description("give old records stable message ids and an events file")
+ .argument("[dir]", "project directory", ".")
+ .action(
+ run(async (dir: string) => {
+ const io = makeIo(false);
+ const result = await migrateIds(dir, io);
+ io.out(
+ `Migrated ${result.migrated} session(s); ${result.skipped} skipped (already migrated or unmappable).`,
+ );
+ }),
+ );
+
const epoch = program.command("epoch").description("manage epochs (features, epics)");
epoch
.command("add")
diff --git a/packages/cli/src/schema/events.ts b/packages/cli/src/schema/events.ts
new file mode 100644
index 0000000..e0f9f60
--- /dev/null
+++ b/packages/cli/src/schema/events.ts
@@ -0,0 +1,22 @@
+import { z } from "zod";
+import { IsoDate, Slug } from "./common.js";
+
+/**
+ * Structure changes of one session, appended and never rewritten (Story 8.5).
+ * The graph is the replay of this file: the last `parent` event for a message
+ * wins, `link` adds a return and `unlink` removes one. Notes stay in the session
+ * JSON; this file holds facts only.
+ */
+export const SessionEvent = z.object({
+ /** When the change was recorded. */
+ at: IsoDate,
+ type: z.enum(["parent", "link", "unlink"]),
+ /** The message the event is about, by its stable id. */
+ msg: Slug,
+ /** The parent for `parent` (null = a new root), the other message for link/unlink. */
+ target: Slug.nullable(),
+ /** Who made the change: the agent's record, or the user correcting it. */
+ by: z.enum(["agent", "user"]).default("agent"),
+});
+
+export type SessionEvent = z.infer<typeof SessionEvent>;
diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.ts
index 3470c93..f9c5fdd 100644
--- a/packages/cli/src/schema/merge.ts
+++ b/packages/cli/src/schema/merge.ts
@@ -11,6 +11,16 @@ export interface MergeResult {
warnings: string[];
}
+export interface MergeOptions {
+ /**
+ * Position in send order of every message the session knows, by its stable id
+ * (`h…`). Without it, `m1`, `m2`, … define the order, as before 8.5.
+ */
+ order?: ReadonlyMap<string, number>;
+ /** Stable id → display label, for warnings the agent reads. */
+ labels?: ReadonlyMap<string, string>;
+}
+
/**
* Merges agent input into the stored session. Nodes are upserted by id and never
* removed; status is replaced when sent; other fields change only when sent.
@@ -19,6 +29,7 @@ export function mergeSession(
existing: Session | undefined,
input: SessionInput,
now: string,
+ opts: MergeOptions = {},
): MergeResult {
if (existing && existing.sessionId !== input.sessionId) {
throw new Error(`session id mismatch: ${existing.sessionId} vs ${input.sessionId}`);
@@ -36,24 +47,33 @@ export function mergeSession(
};
const nodes = new Map<string, LineageNode>(base.nodes.map((n) => [n.id, n]));
- const messageNumbers = new Map<string, number>();
+ /**
+ * Send-order position of every message the record holds or this write adds.
+ * The table (stable ids) decides it; without one, `m1`, `m2`, … still do. A
+ * parent must be one of these, so a message that has no node cannot be one.
+ */
+ const recorded = new Map<string, number>();
for (const n of [...base.nodes, ...(input.nodes ?? [])]) {
+ if (n.kind !== "message") continue;
+ const fromTable = opts.order?.get(n.id);
const number = messageNumber(n);
- if (number !== null) messageNumbers.set(n.id, number);
+ const position = fromTable ?? (number === null ? null : number - 1);
+ if (position !== null) recorded.set(n.id, position);
}
+ const label = (id: string): string => opts.labels?.get(id) ?? id;
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 own = n.kind === "message" ? (recorded.get(n.id) ?? null) : null;
const nextParent =
parent !== undefined && own !== null
- ? checkParent(n.id, parent, own, messageNumbers, messageWarnings)
+ ? checkParent(n.id, parent, own, recorded, messageWarnings, label)
: parent === undefined
? (prev?.parent ?? null)
: parent;
const nextLinks =
links !== undefined && own !== null
- ? checkLinks(n.id, links, own, messageNumbers, messageWarnings)
+ ? checkLinks(n.id, links, own, recorded, messageWarnings, label)
: links;
const next: LineageNode = {
...prev,
@@ -94,10 +114,10 @@ function isEarlierMessage(numbers: Map<string, number>, id: string, own: number)
return number !== undefined && number < own;
}
-/** The recorded message just before `own` by number, or null when there is none. */
+/** The recorded message just before `own` by position, or null when there is none. */
function previousMessage(numbers: Map<string, number>, own: number): string | null {
let best: string | null = null;
- let bestNumber = 0;
+ let bestNumber = -1;
for (const [id, number] of numbers) {
if (number < own && number > bestNumber) {
best = id;
@@ -119,13 +139,14 @@ function checkParent(
own: number,
numbers: Map<string, number>,
warnings: string[],
+ label: (id: string) => 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}`,
+ ? `message ${label(id)}: parent ${label(parent)} is not an earlier message of this session, moved to root`
+ : `message ${label(id)}: parent ${label(parent)} is not an earlier message of this session, using ${label(fallback)}`,
);
return fallback;
}
@@ -137,10 +158,13 @@ function checkLinks(
own: number,
numbers: Map<string, number>,
warnings: string[],
+ label: (id: string) => 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`);
+ warnings.push(
+ `message ${label(id)}: link ${label(link)} is not an earlier message of this session, dropped`,
+ );
return false;
});
}
diff --git a/packages/cli/src/store/conversations.ts b/packages/cli/src/store/conversations.ts
index dcee04e..d19b066 100644
--- a/packages/cli/src/store/conversations.ts
+++ b/packages/cli/src/store/conversations.ts
@@ -13,6 +13,11 @@ import { projectPaths } from "./paths.js";
export interface StoredTurn {
/** The transcript's uuid for the user line; the key that makes appends idempotent. */
uuid: string;
+ /**
+ * The message's stable id (Story 8.5), so ids survive the transcript. Absent
+ * on turns stored before hashes existed; they are hashed from these fields.
+ */
+ hash?: string;
at: string;
text: string;
replies: string[];
@@ -53,15 +58,27 @@ export async function readConversationStore(
} catch {
return [];
}
- const turns: StoredTurn[] = [];
+ /** Later records for one uuid add a stable id without rewriting the turn. */
+ const byUuid = new Map<string, StoredTurn>();
+ const order: string[] = [];
for (const line of text.split("\n")) {
if (line.trim() === "") continue;
+ let value: unknown;
try {
- const value: unknown = JSON.parse(line);
- if (isStoredTurn(value)) turns.push(value);
- } catch {}
+ value = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (!isStoredTurn(value)) continue;
+ const prev = byUuid.get(value.uuid);
+ if (!prev) {
+ byUuid.set(value.uuid, value);
+ order.push(value.uuid);
+ continue;
+ }
+ if (prev.hash === undefined && value.hash !== undefined) byUuid.set(value.uuid, value);
}
- return turns;
+ return order.map((uuid) => byUuid.get(uuid) as StoredTurn);
}
/**
@@ -82,6 +99,7 @@ export async function appendConversationTurns(
known.add(turn.uuid);
fresh.push({
uuid: turn.uuid,
+ ...(turn.hash === undefined ? {} : { hash: turn.hash }),
at: turn.at,
text: turn.text,
replies: turn.replies,
@@ -98,3 +116,27 @@ export async function appendConversationTurns(
await appendFile(file, gzipSync(Buffer.from(chunk, "utf8")));
return fresh.length;
}
+
+/**
+ * Adds the stable id to turns stored before Story 8.5, as a later line for the
+ * same uuid: the file stays append-only and reading prefers the line with a
+ * hash. Without this, deleting the transcript would change every id and show
+ * recorded messages as unrecorded.
+ */
+export async function appendConversationHashes(
+ root: string,
+ sessionId: string,
+ hashes: ReadonlyMap<string, string>,
+): Promise<number> {
+ if (hashes.size === 0) return 0;
+ const stored = await readConversationStore(root, sessionId);
+ const fresh = stored
+ .filter((turn) => turn.hash === undefined && hashes.has(turn.uuid))
+ .map((turn) => ({ ...turn, hash: hashes.get(turn.uuid) as string }));
+ if (fresh.length === 0) return 0;
+ const chunk = `${fresh.map((turn) => JSON.stringify(turn)).join("\n")}\n`;
+ const file = projectPaths(root).conversation(sessionId);
+ await mkdir(dirname(file), { recursive: true });
+ await appendFile(file, gzipSync(Buffer.from(chunk, "utf8")));
+ return fresh.length;
+}
diff --git a/packages/cli/src/store/events.ts b/packages/cli/src/store/events.ts
new file mode 100644
index 0000000..587affe
--- /dev/null
+++ b/packages/cli/src/store/events.ts
@@ -0,0 +1,113 @@
+import { appendFile, mkdir, readFile } from "node:fs/promises";
+import { dirname } from "node:path";
+import { SessionEvent } from "../schema/events.js";
+import type { LineageNode } from "../schema/session.js";
+import { projectPaths } from "./paths.js";
+
+/**
+ * The per-session structure file: one JSON event per line, appended and never
+ * rewritten (Story 8.5). A missing file means the record predates the split and
+ * its JSON parents still describe the graph; a present file is the truth.
+ */
+export async function readEvents(root: string, sessionId: string): Promise<SessionEvent[]> {
+ let text: string;
+ try {
+ text = await readFile(projectPaths(root).events(sessionId), "utf8");
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === "ENOENT" || code === "ENOTDIR") return [];
+ throw err;
+ }
+ const events: SessionEvent[] = [];
+ for (const line of text.split("\n")) {
+ if (line.trim() === "") continue;
+ let value: unknown;
+ try {
+ value = JSON.parse(line);
+ } catch {
+ // A hand-edited or half-written line must not hide the rest of the facts.
+ continue;
+ }
+ const parsed = SessionEvent.safeParse(value);
+ if (parsed.success) events.push(parsed.data);
+ }
+ return events;
+}
+
+/** Appends events as JSON lines; nothing to append writes nothing. */
+export async function appendEvents(
+ root: string,
+ sessionId: string,
+ events: readonly SessionEvent[],
+): Promise<number> {
+ if (events.length === 0) return 0;
+ const file = projectPaths(root).events(sessionId);
+ await mkdir(dirname(file), { recursive: true });
+ await appendFile(file, `${events.map((event) => JSON.stringify(event)).join("\n")}\n`);
+ return events.length;
+}
+
+export interface Structure {
+ parent: string | null;
+ links: string[];
+}
+
+/** The structure the events describe: last parent wins, link adds, unlink removes. */
+export function replayEvents(events: readonly SessionEvent[]): Map<string, Structure> {
+ const structure = new Map<string, Structure>();
+ const get = (id: string): Structure => {
+ const found = structure.get(id);
+ if (found) return found;
+ const fresh: Structure = { parent: null, links: [] };
+ structure.set(id, fresh);
+ return fresh;
+ };
+ for (const event of events) {
+ const entry = get(event.msg);
+ if (event.type === "parent") {
+ entry.parent = event.target;
+ } else if (event.type === "link") {
+ if (event.target !== null && !entry.links.includes(event.target))
+ entry.links.push(event.target);
+ } else if (event.target !== null) {
+ entry.links = entry.links.filter((link) => link !== event.target);
+ }
+ }
+ return structure;
+}
+
+/**
+ * Applies the replayed structure to a record's message nodes. Without events the
+ * nodes are returned untouched, so an old record keeps rendering from its JSON.
+ * With events, a message named by no parent event is a root: the file alone
+ * decides the graph.
+ */
+export function applyEvents(nodes: LineageNode[], events: readonly SessionEvent[]): LineageNode[] {
+ if (events.length === 0) return nodes;
+ const structure = replayEvents(events);
+ return nodes.map((node) => {
+ if (node.kind !== "message") return node;
+ const entry = structure.get(node.id);
+ return {
+ ...node,
+ parent: entry?.parent ?? null,
+ ...(entry && entry.links.length > 0 ? { links: entry.links } : { links: undefined }),
+ };
+ });
+}
+
+/**
+ * One `parent` event per message and one `link` event per link of the record as
+ * stored, used to seed the file before its first change (a record written before
+ * 8.5) and by the migration.
+ */
+export function seedEvents(nodes: readonly LineageNode[], at: string): SessionEvent[] {
+ const events: SessionEvent[] = [];
+ for (const node of nodes) {
+ if (node.kind !== "message") continue;
+ events.push({ at, type: "parent", msg: node.id, target: node.parent ?? null, by: "agent" });
+ for (const link of node.links ?? [])
+ events.push({ at, type: "link", msg: node.id, target: link, by: "agent" });
+ }
+ return events;
+}
diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.ts
index 8bf8022..d8be727 100644
--- a/packages/cli/src/store/paths.ts
+++ b/packages/cli/src/store/paths.ts
@@ -10,6 +10,10 @@ export function projectPaths(root: string) {
project: join(base, "project.json"),
sessions: join(base, "sessions"),
session: (id: string) => join(base, "sessions", `${id}.json`),
+ /** Append-only structure events for a session (Story 8.5). */
+ events: (id: string) => join(base, "sessions", `${id}.events.jsonl`),
+ /** Pre-migration copies of the record files. */
+ backup: (name: string) => join(base, name),
/** The conversation store: what the drill-down needs, outliving the transcript. */
conversations: join(base, "conversations"),
conversation: (id: string) => join(base, "conversations", `${id}.jsonl.gz`),
diff --git a/packages/cli/src/transcript.ts b/packages/cli/src/transcript.ts
index b7c8525..4abdf56 100644
--- a/packages/cli/src/transcript.ts
+++ b/packages/cli/src/transcript.ts
@@ -101,6 +101,10 @@ export interface ToolUse {
export interface ChatTurn extends UserMessage {
/** The transcript's uuid for the user line; the key of the conversation store. */
uuid?: string;
+ /** The message's stable id (`h…`, Story 8.5); set once the session id is known. */
+ hash?: string;
+ /** The display label (`m1`, `m2`, …); set once the session id is known. */
+ label?: string;
/** The agent's written replies, in order; tool output never appears here. */
replies: string[];
tools: ToolUse;
diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.ts
index 6ee08ba..161d06c 100644
--- a/packages/cli/src/view/lineage.ts
+++ b/packages/cli/src/view/lineage.ts
@@ -24,10 +24,28 @@ export function buildMessages(
nodes: LineageNode[],
pending: ViewPendingMessage[] = [],
): ViewNode[] {
- const messages = nodes.filter((node) => node.kind === "message").sort(compareMessages);
- const known = new Set(messages.map((message) => message.id));
+ const recorded = nodes.filter((node) => node.kind === "message");
+ // One row per message in send order; unrecorded messages are part of the same
+ // order, so a session's labels (`m1`, `m2`, …) count both and line up with
+ // `session show` (Story 8.5).
+ type Row =
+ | { kind: "recorded"; node: LineageNode; index: number }
+ | { kind: "pending"; message: ViewPendingMessage; index: number };
+ const combined: Row[] = [
+ ...recorded.map((node, index): Row => ({ kind: "recorded", node, index })),
+ ...pending.map(
+ (message, index): Row => ({ kind: "pending", message, index: recorded.length + index }),
+ ),
+ ].sort(
+ (a, b) =>
+ ((a.kind === "recorded" ? a.node.at : a.message.at) ?? "").localeCompare(
+ (b.kind === "recorded" ? b.node.at : b.message.at) ?? "",
+ ) || a.index - b.index,
+ );
+ const idOf = (row: Row): string => (row.kind === "recorded" ? row.node.id : row.message.id);
+ const known = new Set(combined.map(idOf));
/** Position in send order: a parent or link must come before the message. */
- const order = new Map(messages.map((message, index) => [message.id, index]));
+ const order = new Map(combined.map((row, index) => [idOf(row), index]));
const earlier = (other: string, id: string): boolean => {
const otherAt = order.get(other);
const selfAt = order.get(id);
@@ -38,11 +56,26 @@ export function buildMessages(
const push = (message: ViewNode, parent: string | null): void => {
message.parent = parent;
+ message.label = `m${out.length + 1}`;
out.push(message);
previous = message.id;
};
- for (const node of messages) {
+ for (const row of combined) {
+ if (row.kind === "pending") {
+ push(
+ {
+ id: row.message.id,
+ kind: "message",
+ title: row.message.title,
+ at: row.message.at,
+ unsummarized: true,
+ },
+ previous,
+ );
+ continue;
+ }
+ const node = row.node;
const parent =
node.parent === null
? null
@@ -72,36 +105,9 @@ export function buildMessages(
parent,
);
}
-
- // Messages the record does not hold yet continue the chain where it stopped.
- for (const message of pending) {
- push(
- {
- id: message.id,
- kind: "message",
- title: message.title,
- at: message.at,
- unsummarized: true,
- },
- previous,
- );
- }
return out;
}
-const MESSAGE_NUMBER = /^m([1-9][0-9]*)$/;
-
-function messageNumber(id: string): number {
- const match = MESSAGE_NUMBER.exec(id);
- return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER;
-}
-
-/** Send time first; the message number keeps records written in one go in order. */
-function compareMessages(a: LineageNode, b: LineageNode): number {
- const at = (a.at ?? "").localeCompare(b.at ?? "");
- return at !== 0 ? at : messageNumber(a.id) - messageNumber(b.id);
-}
-
/** A session counts as active while it was updated within this window. */
export const ACTIVE_WINDOW_DAYS = 7;
const ACTIVE_WINDOW_MS = ACTIVE_WINDOW_DAYS * 24 * 60 * 60 * 1000;
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index eceabfd..e260947 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -21,7 +21,10 @@ export const LIVE_META_NAME = "codelineage-live";
export const VIEW_SCHEMA = 1;
export interface ViewNode {
+ /** Stable id (`h…`); the key of the node, never shown to the user. */
id: string;
+ /** Display label (`m1`, `m2`, …) derived from send order (Story 8.5). */
+ label?: string;
kind: NodeKind;
title: string;
summary?: string;
@@ -77,8 +80,10 @@ export interface StatusCard extends ViewStatus {
/** A user message the record does not hold yet, read from the transcript at build time. */
export interface ViewPendingMessage {
- /** Same id the message will get as a node (`m1`, `m2`, …). */
+ /** The stable id the message will get as a node (`h…`). */
id: string;
+ /** The `m1`, `m2`, … label the user reads. */
+ label?: string;
at: string;
/** The first words of the message, used as the card title. */
title: string;
@@ -86,8 +91,10 @@ export interface ViewPendingMessage {
/** 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`, …). */
+ /** Same stable id as the message node it belongs to (`h…`). */
id: string;
+ /** The `m1`, `m2`, … label the user reads. */
+ label?: string;
at: string;
/** The user's message as written, without injected reminders. */
text: string;
diff --git a/packages/cli/test/backfill.test.ts b/packages/cli/test/backfill.test.ts
index c601d8c..43856bb 100644
--- a/packages/cli/test/backfill.test.ts
+++ b/packages/cli/test/backfill.test.ts
@@ -10,6 +10,7 @@ import {
} from "../src/commands/backfill.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 { projectPaths } from "../src/store/paths.js";
import { loadSession } from "../src/store/stores.js";
@@ -154,9 +155,11 @@ describe("backfill --tail", () => {
const io = fakeIo(env);
await backfillTail(root, "s1", io);
const saved = await record();
- expect(saved?.nodes.map((n) => n.id)).toEqual(expect.arrayContaining(["m1", "topic", "m2"]));
+ const first = messageHash("s1", { at: "2026-10-23T10:01:00.000Z", text: "first" });
+ const second = messageHash("s1", { at: "2026-10-23T10:02:00.000Z", text: "second" });
+ expect(saved?.nodes.map((n) => n.id)).toEqual(expect.arrayContaining([first, "topic", second]));
// The time comes from the transcript, not from the agent.
- expect(saved?.nodes.find((n) => n.id === "m2")).toMatchObject({
+ expect(saved?.nodes.find((n) => n.id === second)).toMatchObject({
at: "2026-10-23T10:02:00.000Z",
summary: "Recorded it",
});
@@ -165,7 +168,7 @@ describe("backfill --tail", () => {
const prompt = await readFile(join(dir, "prompt.txt"), "utf8");
expect(prompt).toContain("USER: second");
expect(prompt).toContain('"sessionId": "s1"');
- expect(prompt).toContain("- m1 (message) parent=null: First");
+ expect(prompt).toContain(`- ${first} (message) parent=null: First`);
expect(prompt).toContain("the conversation's language");
});
diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.ts
index 131e66f..43600cf 100644
--- a/packages/cli/test/build.test.ts
+++ b/packages/cli/test/build.test.ts
@@ -1,12 +1,14 @@
import { existsSync } from "node:fs";
import { appendFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
+import { gzipSync } from "node:zlib";
import { beforeEach, describe, expect, it } from "vitest";
-import { buildProject, countUnrecorded } from "../src/commands/build.js";
+import { buildProject } from "../src/commands/build.js";
import { configSet } from "../src/commands/config.js";
import { epochAdd } from "../src/commands/epoch.js";
import { init } from "../src/commands/init.js";
import { sessionWrite } from "../src/commands/session.js";
+import { messageHash } from "../src/messages.js";
import type { LineageNode, Session } from "../src/schema/session.js";
import { readConversationStore } from "../src/store/conversations.js";
import { projectPaths } from "../src/store/paths.js";
@@ -213,6 +215,7 @@ describe("buildViewModel", () => {
expect(messages.map((message) => message.parent)).toEqual([null, "m1", "m2"]);
expect(messages[2]).toEqual({
id: "m3",
+ label: "m3",
kind: "message",
title: "Third message",
at: "2026-10-21T10:03:00.000Z",
@@ -492,8 +495,10 @@ describe("codelineage build", () => {
const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
const [s1, s2] = model.epochs[0]?.sessions ?? [];
+ const raw = "Fix the card <system-reminder>x</system-reminder>";
const turn = {
- id: "m1",
+ id: messageHash("s1", { at: T0, text: raw }),
+ label: "m1",
at: T0,
text: "Fix the card",
replies: ["Done, key [REDACTED]"],
@@ -502,9 +507,9 @@ describe("codelineage build", () => {
expect(s1?.chat).toEqual([turn]);
// s2 records no message, so its unrecorded turn is shown as a pending card
// and needs the same conversation for its drill-down.
- expect(s2?.chat).toEqual([turn]);
+ expect(s2?.chat).toEqual([{ ...turn, id: messageHash("s2", { at: T0, text: raw }) }]);
expect(s2?.messages.at(-1)).toMatchObject({
- id: "m1",
+ id: messageHash("s2", { at: T0, text: raw }),
kind: "message",
title: "Fix the card",
unsummarized: true,
@@ -541,8 +546,14 @@ describe("codelineage build", () => {
session({ sessionId: "s1", epoch: "e1", nodes: [node("m1", "message", "First")] }),
);
+ const hash = (uuid: string, at: string, text: string) => messageHash("s1", { uuid, at, text });
+ const hashes = [
+ hash("u1", T0, "First"),
+ hash("u2", "2026-10-21T11:00:00.000Z", "Second"),
+ hash("u3", T0, "Third"),
+ ];
const first = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
- expect(first.epochs[0]?.sessions[0]?.chat?.map((t) => t.id)).toEqual(["m1", "m2"]);
+ expect(first.epochs[0]?.sessions[0]?.chat?.map((t) => t.id)).toEqual(hashes.slice(0, 2));
expect((await readConversationStore(root, "s1")).map((t) => [t.uuid, t.text])).toEqual([
["u1", "First"],
["u2", "Second"],
@@ -568,9 +579,9 @@ describe("codelineage build", () => {
expect(third.epochs[0]?.sessions[0]).toMatchObject({
transcriptAvailable: false,
chat: [
- { id: "m1", text: "First", replies: ["Answer one"] },
- { id: "m2", text: "Second", replies: ["Answer two"] },
- { id: "m3", text: "Third", replies: [] },
+ { id: hashes[0], text: "First", replies: ["Answer one"] },
+ { id: hashes[1], text: "Second", replies: ["Answer two"] },
+ { id: hashes[2], text: "Third", replies: [] },
],
});
@@ -587,6 +598,49 @@ describe("codelineage build", () => {
);
});
+ it("gives turns stored before stable ids their hash, so ids survive the transcript", async () => {
+ const folder = join(dir, "claude", "projects", "-proj");
+ await mkdir(folder, { recursive: true });
+ const transcript = join(folder, "s1.jsonl");
+ await writeFile(
+ transcript,
+ JSON.stringify({
+ type: "user",
+ uuid: "u1",
+ timestamp: T0,
+ message: { content: "First" },
+ }),
+ );
+ // A turn stored by 8.4, before the store kept ids.
+ const stored = {
+ uuid: "u1",
+ at: T0,
+ text: "First",
+ replies: [],
+ tools: { commands: 0, files: [], other: 0 },
+ };
+ await mkdir(paths().conversations, { recursive: true });
+ await writeFile(
+ paths().conversation("s1"),
+ gzipSync(Buffer.from(`${JSON.stringify(stored)}\n`)),
+ );
+ await saveSession(
+ "s1",
+ session({ sessionId: "s1", epoch: "e1", nodes: [node("m1", "message", "First")] }),
+ );
+ const id = messageHash("s1", { uuid: "u1", at: T0, text: "First" });
+
+ const first = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
+ expect(first.epochs[0]?.sessions[0]?.messages[0]?.id).toBe(id);
+ expect((await readConversationStore(root, "s1"))[0]?.hash).toBe(id);
+
+ // The transcript goes; the stored hash keeps the same id and the record matches.
+ await rm(transcript);
+ const second = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
+ expect(second.epochs[0]?.sessions[0]?.messages.map((m) => m.id)).toEqual([id]);
+ expect(second.epochs[0]?.sessions[0]?.messages[0]?.unsummarized).toBeUndefined();
+ });
+
it("adds the conversation gitignore line once, also in an existing project", async () => {
const ignore = join(paths().base, ".gitignore");
// An older project has no inner .gitignore; the next build writes it.
@@ -669,12 +723,16 @@ describe("codelineage build", () => {
"Second message, with the card",
]);
expect(messages[1]).toMatchObject({
- id: "m2",
+ id: messageHash("s1", {
+ at: "2026-10-21T10:05:00.000Z",
+ text: "Second message, with the card <system-reminder>noise</system-reminder>",
+ }),
+ label: "m2",
kind: "message",
title: "Second message, with the card",
at: "2026-10-21T10:05:00.000Z",
unsummarized: true,
- parent: "m1",
+ parent: messageHash("s1", { at: T0, text: "First message" }),
});
await sessionWrite({ dir: root }, io, async () =>
@@ -727,16 +785,6 @@ describe("codelineage build", () => {
);
});
- it("ignores a transcript that cannot be read while counting", async () => {
- const folder = join(dir, "claude", "projects", "-proj");
- await mkdir(join(folder, "s1.jsonl"), { recursive: true });
- const counts = await countUnrecorded(
- [session({ sessionId: "s1" })],
- new Map([["s1", join(folder, "s1.jsonl")]]),
- );
- expect(counts.size).toBe(0);
- });
-
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/events.test.ts b/packages/cli/test/events.test.ts
new file mode 100644
index 0000000..045c721
--- /dev/null
+++ b/packages/cli/test/events.test.ts
@@ -0,0 +1,431 @@
+import { existsSync } from "node:fs";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { init } from "../src/commands/init.js";
+import { migrateIds } from "../src/commands/migrate.js";
+import { sessionWrite } from "../src/commands/session.js";
+import { canonicalMessage, messageHash, messageLabel, upgradeSessionIds } from "../src/messages.js";
+import type { SessionEvent } from "../src/schema/events.js";
+import type { Session } from "../src/schema/session.js";
+import { readEvents, replayEvents } from "../src/store/events.js";
+import { projectPaths } from "../src/store/paths.js";
+import { loadSession } from "../src/store/stores.js";
+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";
+
+const AT = "2026-10-24T10:00:00.000Z";
+
+describe("message ids", () => {
+ it("is stable across runs and machines for a fixed message", () => {
+ // The expected value is the contract: same JSON bytes, same id everywhere.
+ expect(canonicalMessage("s1", { uuid: "u1", at: AT, text: "hello" })).toBe(
+ '{"sessionId":"s1","uuid":"u1","at":"2026-10-24T10:00:00.000Z","text":"hello"}',
+ );
+ expect(messageHash("s1", { uuid: "u1", at: AT, text: "hello" })).toBe("h577bcd134f01");
+ expect(messageHash("s1", { at: AT, text: "hello" })).toBe("h6868c79664e0");
+ expect(messageHash("s2", { uuid: "u1", at: AT, text: "hello" })).not.toBe(
+ messageHash("s1", { uuid: "u1", at: AT, text: "hello" }),
+ );
+ expect(messageLabel(0)).toBe("m1");
+ expect(messageLabel(41)).toBe("m42");
+ });
+
+ it("does not fold the parent into the id", () => {
+ const message = { uuid: "u1", at: AT, text: "hello" };
+ // Correcting a parent is an event; the message keeps its name.
+ expect(messageHash("s1", message)).toBe(messageHash("s1", { ...message }));
+ });
+
+ it("renames old mN nodes and their parents/links to stable ids", () => {
+ const messages = [{ ...turn("m1", "first", AT) }, { ...turn("m2", "second", AT) }];
+ const hashed = messages.map((message, index) => ({
+ ...message,
+ label: message.id,
+ hash: messageHash("s1", { at: message.at, text: message.text }),
+ }));
+ const session = {
+ schema: 1,
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "",
+ epoch: null,
+ startedAt: AT,
+ updatedAt: AT,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [
+ {
+ id: "m1",
+ parent: null,
+ kind: "message" as const,
+ title: "First",
+ at: AT,
+ },
+ {
+ id: "m2",
+ parent: "m1",
+ kind: "message" as const,
+ title: "Second",
+ at: AT,
+ links: ["m1"],
+ },
+ ],
+ } satisfies Session;
+ const upgraded = upgradeSessionIds(session, hashed);
+ expect(upgraded.nodes.map((node) => node.id)).toEqual([hashed[0]?.hash, hashed[1]?.hash]);
+ expect(upgraded.nodes[1]?.parent).toBe(hashed[0]?.hash);
+ expect(upgraded.nodes[1]?.links).toEqual([hashed[0]?.hash]);
+ });
+
+ it("keeps the node that already carries the stable id when both exist", () => {
+ const message = {
+ ...turn("m1", "first", AT),
+ label: "m1",
+ hash: messageHash("s1", { at: AT, text: "first" }),
+ };
+ const session = {
+ schema: 1,
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "",
+ epoch: null,
+ startedAt: AT,
+ updatedAt: AT,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [
+ { id: "m1", parent: null, kind: "message" as const, title: "Old" },
+ { id: message.hash, parent: null, kind: "message" as const, title: "New" },
+ ],
+ } satisfies Session;
+ const upgraded = upgradeSessionIds(session, [message]);
+ expect(upgraded.nodes).toHaveLength(1);
+ expect(upgraded.nodes[0]?.title).toBe("New");
+ });
+});
+
+function turn(id: string, text: string, at: string) {
+ return {
+ id,
+ at,
+ text,
+ replies: [],
+ tools: { commands: 0, files: [], other: 0 },
+ };
+}
+
+describe("events", () => {
+ const at = AT;
+ const event = (type: SessionEvent["type"], msg: string, target: string | null): SessionEvent => ({
+ at,
+ type,
+ msg,
+ target,
+ by: "agent",
+ });
+
+ it("reads a missing file as no facts and skips a damaged line", async () => {
+ const dir = await tempDir();
+ const root = join(dir, "proj");
+ expect(await readEvents(root, "s1")).toEqual([]);
+ await mkdir(projectPaths(root).sessions, { recursive: true });
+ await writeFile(
+ projectPaths(root).events("s1"),
+ [
+ "not json",
+ JSON.stringify({ at, type: "parent", msg: "h1", target: null, by: "agent" }),
+ ].join("\n"),
+ );
+ expect((await readEvents(root, "s1")).map((event) => event.msg)).toEqual(["h1"]);
+ // Anything but a missing file is a real error, not an empty history.
+ await rm(projectPaths(root).events("s1"));
+ await mkdir(projectPaths(root).events("s1"));
+ await expect(readEvents(root, "s1")).rejects.toThrow();
+ });
+
+ it("replays in order: the last parent wins, link adds, unlink removes", () => {
+ const replay = replayEvents([
+ event("parent", "h1", null),
+ event("parent", "h2", "h1"),
+ event("parent", "h3", "h1"),
+ event("link", "h3", "h1"),
+ event("parent", "h2", "h9"),
+ event("link", "h3", "h2"),
+ event("unlink", "h3", "h1"),
+ ]);
+ expect(replay.get("h1")).toEqual({ parent: null, links: [] });
+ expect(replay.get("h2")?.parent).toBe("h9");
+ expect(replay.get("h3")).toEqual({ parent: "h1", links: ["h2"] });
+ });
+});
+
+describe("session write with stable ids", () => {
+ let dir: string;
+ let root: string;
+ let io: FakeIo;
+ const paths = () => projectPaths(root);
+ const write = (json: unknown) =>
+ sessionWrite({ dir: root }, fakeIo(envFor(dir)), async () => JSON.stringify(json));
+ const record = async (): Promise<Session | undefined> => {
+ const loaded = await loadSession(root, "s1");
+ return loaded.found && loaded.ok ? loaded.data : undefined;
+ };
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ io = fakeIo(envFor(dir));
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ const folder = join(envFor(dir).CLAUDE_CONFIG_DIR ?? "", "projects", "proj");
+ await mkdir(folder, { recursive: true });
+ await writeFile(
+ join(folder, "s1.jsonl"),
+ [user("first", "2026-10-23T10:01:00.000Z"), user("second", "2026-10-23T10:02:00.000Z")].join(
+ "\n",
+ ),
+ );
+ });
+
+ function user(text: string, timestamp: string): string {
+ return JSON.stringify({ type: "user", timestamp, message: { role: "user", content: text } });
+ }
+
+ const first = () => messageHash("s1", { at: "2026-10-23T10:01:00.000Z", text: "first" });
+ const second = () => messageHash("s1", { at: "2026-10-23T10:02:00.000Z", text: "second" });
+
+ it("maps mN to the stable id, keeps the notes, and records the structure", async () => {
+ await write({
+ sessionId: "s1",
+ nodes: [
+ { id: "m1", kind: "message", title: "First", summary: "one" },
+ { id: "m2", kind: "message", parent: "m1", title: "Second" },
+ ],
+ });
+ const saved = await record();
+ expect(saved?.nodes.map((node) => [node.id, node.title])).toEqual([
+ [first(), "First"],
+ [second(), "Second"],
+ ]);
+ expect(saved?.nodes[1]?.parent).toBe(first());
+ const events = await readEvents(root, "s1");
+ // A root needs no event: with a facts file, a message no parent event names
+ // is a root, so only the real structure is written.
+ expect(events.map((event) => [event.type, event.msg, event.target])).toEqual([
+ ["parent", second(), first()],
+ ]);
+ });
+
+ it("keeps ids when a parent is corrected, and writes no event for an unchanged write", async () => {
+ await write({
+ sessionId: "s1",
+ nodes: [
+ { id: "m1", kind: "message", title: "First" },
+ { id: "m2", kind: "message", parent: "m1", title: "Second" },
+ ],
+ });
+ const before = await readFile(paths().events("s1"), "utf8");
+ const ids = (await record())?.nodes.map((node) => node.id);
+ expect(ids).toEqual([first(), second()]);
+
+ // The same input again changes nothing, so no line is appended.
+ await write({
+ sessionId: "s1",
+ nodes: [
+ { id: "m1", kind: "message", title: "First" },
+ { id: "m2", kind: "message", parent: "m1", title: "Second" },
+ ],
+ });
+ expect(await readFile(paths().events("s1"), "utf8")).toBe(before);
+
+ // Correcting the parent to root keeps both ids and appends one fact.
+ await write({
+ sessionId: "s1",
+ nodes: [{ id: second(), kind: "message", parent: null, title: "Second" }],
+ });
+ expect((await record())?.nodes.map((node) => node.id)).toEqual([first(), second()]);
+ const events = await readEvents(root, "s1");
+ expect(events.at(-1)).toMatchObject({ type: "parent", msg: second(), target: null });
+ expect(replayEvents(events).get(second())?.parent).toBeNull();
+ });
+
+ it("appends link and unlink facts when links change", async () => {
+ await write({
+ sessionId: "s1",
+ nodes: [
+ { id: "m1", kind: "message", title: "First" },
+ { id: "m2", kind: "message", parent: "m1", title: "Second" },
+ ],
+ });
+ await write({
+ sessionId: "s1",
+ nodes: [{ id: "m2", kind: "message", links: ["m1"], title: "Second" }],
+ });
+ expect(replayEvents(await readEvents(root, "s1")).get(second())?.links).toEqual([first()]);
+ await write({
+ sessionId: "s1",
+ nodes: [{ id: "m2", kind: "message", links: [], title: "Second" }],
+ });
+ const events = await readEvents(root, "s1");
+ expect(events.slice(-2).map((event) => [event.type, event.target])).toEqual([
+ ["link", first()],
+ ["unlink", first()],
+ ]);
+ expect(replayEvents(events).get(second())?.links).toEqual([]);
+ });
+
+ it("seeds an old record's structure before its first change", async () => {
+ // A record written before 8.5: labels only, no events file.
+ const legacy: Session = {
+ schema: 1,
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "old",
+ epoch: null,
+ startedAt: T0,
+ updatedAt: T0,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [
+ { id: "m1", parent: null, kind: "message", title: "First", at: "2026-10-23T10:01:00.000Z" },
+ {
+ id: "m2",
+ parent: "m1",
+ kind: "message",
+ title: "Second",
+ at: "2026-10-23T10:02:00.000Z",
+ },
+ ],
+ };
+ await writeFile(paths().session("s1"), JSON.stringify(legacy));
+ await write({
+ sessionId: "s1",
+ nodes: [{ id: "m2", kind: "message", parent: null, title: "Second" }],
+ });
+ expect((await record())?.nodes.map((node) => node.id)).toEqual([first(), second()]);
+ const events = await readEvents(root, "s1");
+ // Both existing facts are seeded, then the correction is appended.
+ expect(events.map((event) => [event.type, event.msg, event.target])).toEqual([
+ ["parent", first(), null],
+ ["parent", second(), first()],
+ ["parent", second(), null],
+ ]);
+ expect(replayEvents(events).get(second())?.parent).toBeNull();
+ });
+});
+
+describe("migrate ids", () => {
+ let dir: string;
+ let root: string;
+ let io: FakeIo;
+ const paths = () => projectPaths(root);
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ io = fakeIo(envFor(dir));
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ const folder = join(envFor(dir).CLAUDE_CONFIG_DIR ?? "", "projects", "proj");
+ await mkdir(folder, { recursive: true });
+ await writeFile(
+ join(folder, "s1.jsonl"),
+ [
+ JSON.stringify({
+ type: "user",
+ timestamp: "2026-10-23T10:01:00.000Z",
+ message: { role: "user", content: "first" },
+ }),
+ JSON.stringify({
+ type: "user",
+ timestamp: "2026-10-23T10:02:00.000Z",
+ message: { role: "user", content: "second" },
+ }),
+ ].join("\n"),
+ );
+ const legacy: Session = {
+ schema: 1,
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "old",
+ epoch: null,
+ startedAt: T0,
+ updatedAt: T0,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [
+ { id: "m1", parent: null, kind: "message", title: "First", at: "2026-10-23T10:01:00.000Z" },
+ {
+ id: "m2",
+ parent: "m1",
+ kind: "message",
+ title: "Second",
+ at: "2026-10-23T10:02:00.000Z",
+ links: ["m1"],
+ },
+ ],
+ };
+ await writeFile(paths().session("s1"), JSON.stringify(legacy));
+ });
+
+ it("moves an old record to stable ids and facts, keeping a backup", async () => {
+ const first = messageHash("s1", { at: "2026-10-23T10:01:00.000Z", text: "first" });
+ const second = messageHash("s1", { at: "2026-10-23T10:02:00.000Z", text: "second" });
+ const result = await migrateIds(root, io);
+ expect(result).toEqual({ migrated: 1, skipped: 0 });
+ const loaded = await loadSession(root, "s1");
+ expect(loaded.found && loaded.ok && loaded.data.nodes.map((node) => node.id)).toEqual([
+ first,
+ second,
+ ]);
+ const events = await readEvents(root, "s1");
+ expect(events).toHaveLength(3);
+ expect(replayEvents(events).get(second)).toEqual({ parent: first, links: [first] });
+ expect(existsSync(paths().backup("backup-pre-8.5/s1.json"))).toBe(true);
+ expect(await readFile(paths().backup("backup-pre-8.5/s1.json"), "utf8")).toContain('"m1"');
+ });
+
+ it("is idempotent", async () => {
+ await migrateIds(root, io);
+ const record = await readFile(paths().session("s1"), "utf8");
+ const events = await readFile(paths().events("s1"), "utf8");
+ const again = await migrateIds(root, io);
+ expect(again).toEqual({ migrated: 0, skipped: 1 });
+ expect(await readFile(paths().session("s1"), "utf8")).toBe(record);
+ expect(await readFile(paths().events("s1"), "utf8")).toBe(events);
+ });
+
+ it("leaves unreadable, unmappable and transcript-less records alone", async () => {
+ const one = {
+ schema: 1,
+ sessionId: "s2",
+ agent: "claude-code",
+ title: "",
+ epoch: null,
+ startedAt: T0,
+ updatedAt: T0,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [{ id: "m1", parent: null, kind: "message", title: "One" }],
+ };
+ await writeFile(paths().session("bad"), "{nope");
+ await writeFile(paths().session("s2"), JSON.stringify(one));
+ // s3 has a transcript, but its record names a message that is not in it.
+ const folder = join(envFor(dir).CLAUDE_CONFIG_DIR ?? "", "projects", "proj");
+ await writeFile(
+ join(folder, "s3.jsonl"),
+ JSON.stringify({
+ type: "user",
+ timestamp: "2026-10-23T10:01:00.000Z",
+ message: { role: "user", content: "one" },
+ }),
+ );
+ await writeFile(
+ paths().session("s3"),
+ JSON.stringify({ ...one, sessionId: "s3", nodes: [{ ...one.nodes[0], id: "m5" }] }),
+ );
+ const result = await migrateIds(root, io);
+ expect(result).toEqual({ migrated: 1, skipped: 3 });
+ expect(io.warnings).toEqual([
+ expect.stringMatching(/^session bad: skipped, invalid JSON/),
+ expect.stringMatching(/^session s2: no transcript or stored conversation/),
+ expect.stringMatching(/^session s3: 1 message\(s\) have no transcript line/),
+ ]);
+ expect(existsSync(paths().events("s3"))).toBe(false);
+ });
+});
diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.ts
index 09a224b..d050170 100644
--- a/packages/cli/test/program-commands.test.ts
+++ b/packages/cli/test/program-commands.test.ts
@@ -110,6 +110,14 @@ describe("commands through the CLI", () => {
expect(io.lines.at(-1)).toBe("Saved session s1 (0 nodes)");
});
+ it("runs the hidden migrate command", async () => {
+ await cli("init", root, "--yes", "--retention", "keep");
+ await cli("migrate", root);
+ expect(io.lines.at(-1)).toBe(
+ "Migrated 0 session(s); 0 skipped (already migrated or unmappable).",
+ );
+ });
+
it("runs session show for the skill", async () => {
await cli("init", root, "--yes", "--retention", "keep");
await cli("session", "show", "s1", "-C", root);
diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.ts
index 0d5a696..dcbdfff 100644
--- a/packages/cli/test/session.test.ts
+++ b/packages/cli/test/session.test.ts
@@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it } from "vitest";
import { epochAdd } from "../src/commands/epoch.js";
import { init } from "../src/commands/init.js";
import { readStdin, sessionShow, sessionWrite } from "../src/commands/session.js";
+import { messageHash } from "../src/messages.js";
import { redactDeep, redactText } from "../src/redact.js";
import { loadSession } from "../src/store/stores.js";
import { envFor, type FakeIo, fakeIo, tempDir } from "./helpers.js";
@@ -229,12 +230,20 @@ ${line("second", 2)}
`,
);
+ const first = messageHash("s1", { at: "2026-10-23T10:01:00.000Z", text: "first" });
+ const second = messageHash("s1", { at: "2026-10-23T10:02:00.000Z", text: "second" });
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", gapMinutes: 1 },
+ { id: first, label: "m1", at: "2026-10-23T10:01:00.000Z", text: "first" },
+ {
+ id: second,
+ label: "m2",
+ at: "2026-10-23T10:02:00.000Z",
+ text: "second",
+ gapMinutes: 1,
+ },
],
});
@@ -255,10 +264,16 @@ ${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", gapMinutes: 1 },
+ {
+ id: second,
+ label: "m2",
+ at: "2026-10-23T10:02:00.000Z",
+ text: "second",
+ gapMinutes: 1,
+ },
]);
expect(shown().lastMessages).toEqual([
- { id: "m1", title: "First", parent: null },
+ { id: first, label: "m1", title: "First", parent: null },
{ id: "m9", title: "Made up", parent: null },
]);
});
@@ -292,17 +307,31 @@ ${line("second", 2)}
].join("\n"),
);
+ const hash = (at: string, text: string) => messageHash("s1", { at, text });
await sessionShow(root, "s1", io);
expect(shown().newMessages).toEqual([
- { id: "m1", at: "2026-10-23T10:00:00.000Z", text: "first" },
{
- id: "m2",
+ id: hash("2026-10-23T10:00:00.000Z", "first"),
+ label: "m1",
+ at: "2026-10-23T10:00:00.000Z",
+ text: "first",
+ },
+ {
+ id: hash("2026-10-23T10:30:00.000Z", "second"),
+ label: "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 },
+ {
+ id: hash("2026-10-23T11:00:00.000Z", "third"),
+ label: "m3",
+ at: "2026-10-23T11:00:00.000Z",
+ text: "third",
+ gapMinutes: 30,
+ resumed: true,
+ },
]);
});
diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsx
index e3eb5b2..076d047 100644
--- a/packages/template/src/GitGraph.tsx
+++ b/packages/template/src/GitGraph.tsx
@@ -31,7 +31,7 @@ function returnMark(row: GitMessageRow): ReactElement | null {
<span className="git-returns">
{row.returns.map((back) => (
<span key={back.id} className="git-return" style={{ color: color(back.colorIndex) }}>
- ↩ {back.id}
+ ↩ {back.label}
</span>
))}
</span>
@@ -98,7 +98,7 @@ function Row({
{branchTitle}
</span>
) : null}
- <span className="git-id">{message.id}</span>
+ <span className="git-id">{message.label ?? message.id}</span>
<span className="git-title">{message.title}</span>
{returnMark(row)}
{row.head ? <span className="left-off">left off here</span> : null}
diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsx
index e13af3e..9c80661 100644
--- a/packages/template/src/SidePanel.tsx
+++ b/packages/template/src/SidePanel.tsx
@@ -278,8 +278,8 @@ function BranchDetails({
<section className="branch-detail">
<h3 style={{ color: `var(--l${segment.colorIndex})` }}>{branch.title}</h3>
<p className="branch-range">
- {branch.count > 1 ? `${branch.fromId}–${branch.toId}` : branch.fromId} · {branch.count}{" "}
- message{branch.count === 1 ? "" : "s"}
+ {branch.count > 1 ? `${branch.fromLabel}–${branch.toLabel}` : branch.fromLabel} ·{" "}
+ {branch.count} message{branch.count === 1 ? "" : "s"}
{span}
</p>
{branch.asked ? (
diff --git a/packages/template/src/gitLayout.ts b/packages/template/src/gitLayout.ts
index 1fa7cec..6c9911f 100644
--- a/packages/template/src/gitLayout.ts
+++ b/packages/template/src/gitLayout.ts
@@ -39,6 +39,9 @@ export interface GitBranch {
/** First and last message of the branch, for the "m33–m36" range. */
fromId: string;
toId: string;
+ /** The labels `m33` / `m36` the user reads; the ids are stable keys. */
+ fromLabel: string;
+ toLabel: string;
count: number;
firstAt?: string;
lastAt?: string;
@@ -64,6 +67,8 @@ export interface GitSegment {
export interface GitReturn {
/** The older message this row returns to. */
id: string;
+ /** Its `m22` label, which the row shows instead of the stable id. */
+ label: string;
colorIndex: number;
}
@@ -164,7 +169,7 @@ export function rowHeight(
): number {
const fixed =
ROW_FIXED +
- message.id.length * 7 +
+ (message.label ?? message.id).length * 7 +
(row.first ? BRANCH_MAX + 8 : 0) +
row.returns * 44 +
(row.head ? 92 : 0) +
@@ -196,6 +201,8 @@ function branchOf(ids: string[], byId: Map<string, ViewNode>): GitBranch {
open: first?.branch?.open ?? "",
fromId: ids[0] ?? "",
toId: ids[ids.length - 1] ?? "",
+ fromLabel: first?.label ?? ids[0] ?? "",
+ toLabel: last?.label ?? ids[ids.length - 1] ?? "",
count: ids.length,
...(first?.at === undefined ? {} : { firstAt: first.at }),
...(last?.at === undefined ? {} : { lastAt: last.at }),
@@ -401,7 +408,11 @@ export function layoutGitGraph(messages: ViewNode[], options: GitLayoutOptions =
const returns: GitReturn[] = [];
for (const target of message.links ?? []) {
if (!rowOf.has(target)) continue;
- returns.push({ id: target, colorIndex: segOf.get(target)?.colorIndex ?? 0 });
+ returns.push({
+ id: target,
+ label: byId.get(target)?.label ?? target,
+ colorIndex: segOf.get(target)?.colorIndex ?? 0,
+ });
}
return {
kind: "message",
diff --git a/packages/template/test/gitLayout.test.ts b/packages/template/test/gitLayout.test.ts
index 48a6f1d..9a828e5 100644
--- a/packages/template/test/gitLayout.test.ts
+++ b/packages/template/test/gitLayout.test.ts
@@ -205,6 +205,6 @@ describe("returns", () => {
(candidate): candidate is GitMessageRow =>
candidate.kind === "message" && candidate.message.id === "m4",
);
- expect(row?.returns).toEqual([{ id: "m1", colorIndex: 0 }]);
+ expect(row?.returns).toEqual([{ id: "m1", label: "m1", colorIndex: 0 }]);
});
});