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(cli): log and show read the lineage by message hash

Eren63b6d417f0e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f9479b2..9cfbd5a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Added
+- `codelineage log [dir]` prints the recorded lineage like `git log --graph --oneline`, newest first: per message its short hash, `mN`, time, title, `↩` returns and commit tags, a branch's first message with the branch title, and a header line per session (title, epoch, time span). `--session <id|prefix>` narrows to one session, `-n <count>` limits the messages, `--branches` prints only the branch summaries (title, asked, outcome, open) and `--json` prints the model. `codelineage show <ref> [dir]` prints one message — session, time, parent and children as refs, returns, the branch it sits in with that branch's summary, decisions, agent decisions, work, commits with their git subjects, files and its stored conversation turn (`--no-chat` skips it, `--json` prints the model) — and takes a message hash, a unique prefix of at least six hex characters after the `h`, or `<session-id-prefix>:mN`; an ambiguous prefix lists the candidates and exits non-zero. The map's drill-down shows the message's short hash with a copy button ("Ask your agent: codelineage show <hash>").
## [0.8.0] - 2026-10-24
### Added
diff --git a/packages/cli/src/commands/log.ts b/packages/cli/src/commands/log.ts
new file mode 100644
index 0000000..cfed2fe
--- /dev/null
+++ b/packages/cli/src/commands/log.ts
@@ -0,0 +1,634 @@
+import { readCommitSubjects } from "../git.js";
+import { CliError, type Io } from "../io.js";
+import { readSessionMessages, type SessionMessage, upgradeSessionIds } from "../messages.js";
+import type { LineageNode, Session } from "../schema/session.js";
+import { applyEvents, readEvents } from "../store/events.js";
+import { resolveProjectRoot } from "../store/root.js";
+import { loadAllSessions, loadProject } from "../store/stores.js";
+import { buildMessages } from "../view/lineage.js";
+import type { ViewNode } from "../view/model.js";
+
+/**
+ * `codelineage log` and `codelineage show` (Story 8.10): the CLI's read verbs,
+ * modelled on `git log` and `git show`. The agent is the main reader, so the
+ * output is plain text by default and JSON on request; neither command writes.
+ *
+ * A message is addressed by its stable id (`h` plus 12 hex) or any unique prefix
+ * of at least six hex characters after the `h`, or by `<sessionId-prefix>:mN`.
+ */
+
+/** One session as the map sees it: stable ids, replayed structure, message order. */
+export interface EffectiveSession {
+ session: Session;
+ /** buildMessages output: labels, parents and links already normalised. */
+ messages: ViewNode[];
+}
+
+/** Every valid session of the project, with the ids and structure the map draws. */
+export async function loadEffectiveSessions(root: string, io: Io): Promise<EffectiveSession[]> {
+ const sessions = await loadAllSessions(root, io.warn);
+ const out: EffectiveSession[] = [];
+ for (const session of sessions) {
+ // The transcript (or the conversation store) names old `m1` nodes and holds
+ // the hash of each message; a session without either keeps its stored ids.
+ const turns = await readSessionMessages(root, session.sessionId, io.env);
+ const upgraded = turns ? upgradeSessionIds(session, turns) : session;
+ const events = await readEvents(root, session.sessionId);
+ const effective: Session = { ...upgraded, nodes: applyEvents(upgraded.nodes, events) };
+ out.push({ session: effective, messages: buildMessages(effective.nodes) });
+ }
+ return out.sort(
+ (a, b) =>
+ a.session.startedAt.localeCompare(b.session.startedAt) ||
+ a.session.sessionId.localeCompare(b.session.sessionId),
+ );
+}
+
+/** Loads the project record, refusing an uninitialized or broken project. */
+export async function openProject(dir: string): Promise<string> {
+ const { root } = await resolveProjectRoot(dir);
+ const project = await loadProject(root);
+ if (!project.found)
+ throw new CliError(`${root} is not initialized; run \`codelineage init\` first`);
+ if (!project.ok) throw new CliError(project.error);
+ return root;
+}
+
+const pad = (value: number): string => String(value).padStart(2, "0");
+
+/** `2026-10-24 10:44` in local time; an absent or broken time prints `—`. */
+export function stamp(iso: string | undefined): string {
+ if (iso === undefined) return "—";
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return iso;
+ return (
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
+ `${pad(date.getHours())}:${pad(date.getMinutes())}`
+ );
+}
+
+/** `10:44` in local time. */
+function clock(iso: string | undefined): string {
+ if (iso === undefined) return "—";
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return iso;
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
+}
+
+/** `h3f2a1b8` for a stable message id; anything else is already short enough. */
+export function shortHash(id: string): string {
+ return /^h[0-9a-f]{12}$/.test(id) ? id.slice(0, 8) : id;
+}
+
+function oneLine(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+/** A branch summary with the message range it covers. */
+export interface LogBranch {
+ sessionId: string;
+ title: string;
+ asked: string;
+ outcome: string;
+ open: string;
+ start: { id: string; label: string };
+ end: { id: string; label: string };
+ /** Messages in the branch, including the one that starts it. */
+ count: number;
+}
+
+/** One message line in `log` (and the JSON shape). */
+export interface LogMessage {
+ id: string;
+ label: string;
+ at?: string;
+ title: string;
+ summary?: string;
+ parent: string | null;
+ /** The label of the parent when it lives in this session. */
+ parentLabel?: string;
+ links: string[];
+ linkLabels: string[];
+ /** Set on the message that starts a branch. */
+ branch?: LineageNode["branch"];
+ commits: string[];
+}
+
+export interface LogSession {
+ sessionId: string;
+ title: string;
+ epoch: string | null;
+ startedAt: string;
+ updatedAt: string;
+ /** Newest first. */
+ messages: LogMessage[];
+ branches: LogBranch[];
+}
+
+export interface LogModel {
+ sessions: LogSession[];
+}
+
+/**
+ * The branch summaries of a session, in send order. A branch runs from the
+ * message that carries it up to the message before the next branch starts (or
+ * the end of the session), so the compressed view covers every message once a
+ * summary exists.
+ */
+export function branchesOf(sessionId: string, messages: readonly ViewNode[]): LogBranch[] {
+ const starts = messages.flatMap((message, index) =>
+ message.branch === undefined ? [] : [{ index, branch: message.branch }],
+ );
+ return starts.map(({ index, branch }, position) => {
+ const end = (starts[position + 1]?.index ?? messages.length) - 1;
+ const first = messages[index] as ViewNode;
+ const last = messages[end] as ViewNode;
+ return {
+ sessionId,
+ title: branch.title,
+ asked: branch.asked,
+ outcome: branch.outcome,
+ open: branch.open,
+ start: { id: first.id, label: first.label ?? first.id },
+ end: { id: last.id, label: last.label ?? last.id },
+ count: end - index + 1,
+ };
+ });
+}
+
+function toLogSession(effective: EffectiveSession): LogSession {
+ const { session, messages } = effective;
+ const labels = new Map(messages.map((message) => [message.id, message.label ?? message.id]));
+ const logMessages: LogMessage[] = [...messages].reverse().map((message) => {
+ const parentLabel = typeof message.parent === "string" ? labels.get(message.parent) : undefined;
+ return {
+ id: message.id,
+ label: message.label ?? message.id,
+ ...(message.at === undefined ? {} : { at: message.at }),
+ title: message.title,
+ ...(message.summary === undefined ? {} : { summary: message.summary }),
+ parent: message.parent ?? null,
+ ...(parentLabel === undefined ? {} : { parentLabel }),
+ links: message.links ?? [],
+ linkLabels: (message.links ?? []).map((link) => labels.get(link) ?? link),
+ ...(message.branch === undefined ? {} : { branch: message.branch }),
+ commits: message.commits ?? [],
+ };
+ });
+ return {
+ sessionId: session.sessionId,
+ title: session.title,
+ epoch: session.epoch,
+ startedAt: session.startedAt,
+ updatedAt: session.updatedAt,
+ messages: logMessages,
+ branches: branchesOf(session.sessionId, messages),
+ };
+}
+
+export interface LogOptions {
+ /** Only messages recorded here; a session id or any prefix of one. */
+ session?: string | undefined;
+ /** Maximum messages (or branches with `branchesOnly`). */
+ limit?: number | undefined;
+ /** Only the branch summaries: the compressed view. */
+ branchesOnly?: boolean;
+}
+
+/**
+ * The log model: sessions newest first, their messages newest first. `--session`
+ * takes an exact id or an unambiguous prefix.
+ */
+export function buildLog(sessions: EffectiveSession[], opts: LogOptions = {}): LogModel {
+ let selected = sessions;
+ if (opts.session !== undefined) {
+ const prefix = opts.session;
+ const exact = sessions.filter((entry) => entry.session.sessionId === prefix);
+ const matches =
+ exact.length > 0
+ ? exact
+ : sessions.filter((entry) => entry.session.sessionId.startsWith(prefix));
+ if (matches.length === 0) throw new CliError(`no session matches ${prefix}`);
+ if (matches.length > 1) {
+ const ids = matches.map((entry) => entry.session.sessionId).join(", ");
+ throw new CliError(`"${prefix}" matches ${matches.length} sessions: ${ids}`);
+ }
+ selected = matches;
+ }
+
+ const ordered = [...selected].sort(
+ (a, b) =>
+ b.session.startedAt.localeCompare(a.session.startedAt) ||
+ a.session.sessionId.localeCompare(b.session.sessionId),
+ );
+ const model: LogModel = { sessions: ordered.map(toLogSession) };
+
+ if (opts.limit !== undefined && opts.limit > 0) {
+ let left = opts.limit;
+ model.sessions = model.sessions.flatMap((session) => {
+ if (left === 0) return [];
+ if (opts.branchesOnly === true) {
+ const branches = session.branches.slice(0, left);
+ left -= branches.length;
+ return branches.length === 0 ? [] : [{ ...session, messages: [], branches }];
+ }
+ const messages = session.messages.slice(0, left);
+ left -= messages.length;
+ return messages.length === 0 ? [] : [{ ...session, messages }];
+ });
+ }
+ if (opts.branchesOnly === true) {
+ model.sessions = model.sessions.map((session) => ({ ...session, messages: [] }));
+ }
+ return model;
+}
+
+function sessionHeading(session: LogSession): string {
+ const title = session.title.trim() === "" ? session.sessionId : oneLine(session.title);
+ return (
+ `## ${title} (${session.sessionId}) · ${session.epoch ?? "unassigned"} · ` +
+ `${stamp(session.startedAt)} → ${stamp(session.updatedAt)}`
+ );
+}
+
+function branchLines(branch: LogBranch): string[] {
+ const count = `${branch.count} message${branch.count === 1 ? "" : "s"}`;
+ return [
+ ` ╭ ${branch.title} ${branch.start.label}–${branch.end.label}, ${count}`,
+ ` asked: ${branch.asked}`,
+ ` outcome: ${branch.outcome}`,
+ ` open: ${branch.open === "" ? "—" : branch.open}`,
+ ];
+}
+
+function messageLine(message: LogMessage): string {
+ const parts = [
+ ` ${shortHash(message.id)} ${message.label} ${clock(message.at)} ` +
+ `${message.branch === undefined ? "" : `╭ ${message.branch.title} · `}${oneLine(message.title)}`,
+ ];
+ if (message.linkLabels.length > 0) parts.push(` ↩ ${message.linkLabels.join(", ")}`);
+ if (message.commits.length > 0)
+ parts.push(` [${message.commits.map((hash) => hash.slice(0, 7)).join(" ")}]`);
+ return parts.join("");
+}
+
+/** The plain-text `log`, one line per array entry, newest first. */
+export function formatLog(model: LogModel, branchesOnly = false): string[] {
+ if (model.sessions.length === 0) return ["No recorded sessions yet."];
+ const lines: string[] = [];
+ for (const session of model.sessions) {
+ lines.push(sessionHeading(session));
+ if (branchesOnly) {
+ if (session.branches.length === 0) lines.push(" (no branch summaries)");
+ for (const branch of session.branches) lines.push(...branchLines(branch));
+ } else if (session.messages.length === 0) {
+ lines.push(" (no recorded messages)");
+ } else {
+ for (const message of session.messages) lines.push(messageLine(message));
+ }
+ lines.push("");
+ }
+ lines.pop();
+ return lines;
+}
+
+/** A message reference as `show` prints and serializes it. */
+export interface ShowRef {
+ sessionId: string;
+ id: string;
+ label?: string;
+ title?: string;
+}
+
+export interface RefHit {
+ session: Session;
+ messages: ViewNode[];
+ message: ViewNode;
+}
+
+export type RefResult =
+ | { kind: "ok"; hit: RefHit }
+ | { kind: "ambiguous"; candidates: ShowRef[] }
+ | { kind: "unknown"; reason: string }
+ | { kind: "invalid"; reason: string };
+
+const HASH_REF = /^h[0-9a-f]{6,12}$/;
+const SESSION_LABEL_REF = /^([A-Za-z0-9][A-Za-z0-9_.-]{0,127}):m([1-9][0-9]*)$/;
+
+/**
+ * Resolves a `<ref>` against every session. Errors stay data, so the command can
+ * print the candidates before it exits non-zero.
+ */
+export function resolveRef(sessions: readonly EffectiveSession[], ref: string): RefResult {
+ if (HASH_REF.test(ref)) {
+ const hits = sessions.flatMap((entry) =>
+ entry.messages
+ .filter((message) => message.id.startsWith(ref))
+ .map((message) => ({ entry, message })),
+ );
+ if (hits.length === 0) return { kind: "unknown", reason: `no recorded message matches ${ref}` };
+ if (hits.length > 1) {
+ return {
+ kind: "ambiguous",
+ candidates: hits.map(({ entry, message }) => ({
+ sessionId: entry.session.sessionId,
+ id: message.id,
+ label: message.label ?? message.id,
+ title: message.title,
+ })),
+ };
+ }
+ const hit = hits[0] as { entry: EffectiveSession; message: ViewNode };
+ return {
+ kind: "ok",
+ hit: { session: hit.entry.session, messages: hit.entry.messages, message: hit.message },
+ };
+ }
+
+ const sessionLabel = SESSION_LABEL_REF.exec(ref);
+ if (sessionLabel === null)
+ return {
+ kind: "invalid",
+ reason: "use a message hash (h + 6..12 hex) or <session-id-prefix>:mN",
+ };
+
+ const prefix = sessionLabel[1] as string;
+ const label = `m${sessionLabel[2] as string}`;
+ const exact = sessions.filter((entry) => entry.session.sessionId === prefix);
+ const matches =
+ exact.length > 0
+ ? exact
+ : sessions.filter((entry) => entry.session.sessionId.startsWith(prefix));
+ if (matches.length === 0) return { kind: "unknown", reason: `no session matches ${prefix}` };
+ if (matches.length > 1) {
+ return {
+ kind: "ambiguous",
+ candidates: matches.map((entry) => ({
+ sessionId: entry.session.sessionId,
+ id: entry.session.sessionId,
+ label: entry.session.sessionId,
+ title: entry.session.title,
+ })),
+ };
+ }
+ const entry = matches[0] as EffectiveSession;
+ const message = entry.messages.find((candidate) => candidate.label === label);
+ if (message === undefined)
+ return {
+ kind: "unknown",
+ reason: `session ${entry.session.sessionId} has no recorded message ${label}`,
+ };
+ return { kind: "ok", hit: { session: entry.session, messages: entry.messages, message } };
+}
+
+/** One message with everything `show` prints, ready for text or JSON. */
+export interface ShowModel {
+ id: string;
+ label: string;
+ title: string;
+ summary?: string;
+ sessionId: string;
+ sessionTitle: string;
+ epoch: string | null;
+ at?: string;
+ parent: ShowRef | null;
+ children: ShowRef[];
+ links: ShowRef[];
+ branch: LogBranch | null;
+ decidedBy?: "user" | "agent" | "agreed";
+ why?: string;
+ alternatives?: LineageNode["alternatives"];
+ agentDecisions?: LineageNode["agentDecisions"];
+ work?: string[];
+ commits: { hash: string; subject?: string }[];
+ files?: string[];
+ /** Null when the transcript is gone; absent when `--no-chat` skipped it. */
+ chat?: {
+ text: string;
+ replies: string[];
+ tools: { commands: number; files: string[]; other: number };
+ } | null;
+}
+
+function refOf(sessions: readonly EffectiveSession[], ref: string, self: string): ShowRef {
+ const colon = ref.indexOf(":");
+ const sessionId = colon === -1 ? self : ref.slice(0, colon);
+ const id = colon === -1 ? ref : ref.slice(colon + 1);
+ const entry = sessions.find((candidate) => candidate.session.sessionId === sessionId);
+ const message = entry?.messages.find((candidate) => candidate.id === id);
+ return {
+ sessionId,
+ id,
+ ...(message?.label === undefined ? {} : { label: message.label }),
+ ...(message?.title === undefined ? {} : { title: message.title }),
+ };
+}
+
+/** The branch a message sits in: the last branch that started at or before it. */
+function branchAround(
+ sessionId: string,
+ messages: readonly ViewNode[],
+ id: string,
+): LogBranch | null {
+ let start: ViewNode | null = null;
+ for (const message of messages) {
+ if (message.branch !== undefined) start = message;
+ if (message.id === id) break;
+ }
+ if (start === null) return null;
+ const branches = branchesOf(sessionId, messages);
+ return branches.find((branch) => branch.start.id === start?.id) ?? null;
+}
+
+function conversationTurn(
+ messages: SessionMessage[] | null,
+ message: ViewNode,
+): NonNullable<ShowModel["chat"]> | null {
+ const turn = messages?.find(
+ (candidate) => candidate.hash === message.id || candidate.label === message.label,
+ );
+ if (turn === undefined) return null;
+ return { text: turn.text, replies: turn.replies, tools: turn.tools };
+}
+
+export interface ShowOptions {
+ dir: string;
+ ref: string;
+ io: Io;
+ /** False with `--no-chat`: skip the conversation section. */
+ chat?: boolean;
+}
+
+/**
+ * Reads one message: its place in the graph, its notes, its commits and the
+ * conversation turn. An ambiguous or unknown ref prints what it can and throws,
+ * so the CLI exits non-zero.
+ */
+export async function show(opts: ShowOptions): Promise<ShowModel> {
+ const root = await openProject(opts.dir);
+ const sessions = await loadEffectiveSessions(root, opts.io);
+ const result = resolveRef(sessions, opts.ref);
+ if (result.kind === "invalid") throw new CliError(`invalid ref "${opts.ref}": ${result.reason}`);
+ if (result.kind === "unknown") throw new CliError(result.reason);
+ if (result.kind === "ambiguous") {
+ for (const candidate of result.candidates) {
+ opts.io.out(
+ ` ${candidate.sessionId} · ${candidate.label}${candidate.id === candidate.label ? "" : ` (${candidate.id})`} ${candidate.title}`,
+ );
+ }
+ throw new CliError(`"${opts.ref}" is ambiguous; use a longer prefix`);
+ }
+
+ const { session, messages, message } = result.hit;
+ const sessionId = session.sessionId;
+
+ const children: ShowRef[] = [];
+ const seen = new Set<string>();
+ for (const entry of sessions) {
+ for (const candidate of entry.messages) {
+ const parent = candidate.parent;
+ const child =
+ (entry.session.sessionId === sessionId && parent === message.id) ||
+ parent === `${sessionId}:${message.id}`;
+ if (!child) continue;
+ const key = `${entry.session.sessionId}:${candidate.id}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const ref = refOf(sessions, key, entry.session.sessionId);
+ children.push(ref);
+ }
+ }
+
+ const subjects =
+ message.commits === undefined || message.commits.length === 0
+ ? new Map<string, string>()
+ : await readCommitSubjects(root, message.commits);
+
+ const branch = branchAround(sessionId, messages, message.id);
+ const turn = opts.chat === false ? null : await readSessionMessages(root, sessionId, opts.io.env);
+
+ return {
+ id: message.id,
+ label: message.label ?? message.id,
+ title: message.title,
+ ...(message.summary === undefined ? {} : { summary: message.summary }),
+ sessionId,
+ sessionTitle: session.title,
+ epoch: session.epoch,
+ ...(message.at === undefined ? {} : { at: message.at }),
+ parent:
+ message.parent === null || message.parent === undefined
+ ? null
+ : refOf(sessions, message.parent, sessionId),
+ children,
+ links: (message.links ?? []).map((link) => refOf(sessions, link, sessionId)),
+ branch: branch === null ? null : { ...branch, sessionId },
+ ...(message.decidedBy === undefined ? {} : { decidedBy: message.decidedBy }),
+ ...(message.why === undefined ? {} : { why: message.why }),
+ ...(message.alternatives === undefined ? {} : { alternatives: message.alternatives }),
+ ...(message.agentDecisions === undefined ? {} : { agentDecisions: message.agentDecisions }),
+ ...(message.work === undefined ? {} : { work: message.work }),
+ commits: (message.commits ?? []).map((hash) => {
+ const subject = subjects.get(hash);
+ return subject === undefined ? { hash } : { hash, subject };
+ }),
+ ...(message.files === undefined ? {} : { files: message.files }),
+ ...(opts.chat === false ? {} : { chat: conversationTurn(turn, message) }),
+ };
+}
+
+/** A ref as text: a bare label inside its own session, prefixed across sessions. */
+function refText(ref: ShowRef, selfSessionId?: string): string {
+ const label = ref.label === undefined ? ref.id : `${ref.label} ${shortHash(ref.id)}`;
+ return selfSessionId !== undefined && ref.sessionId === selfSessionId
+ ? label
+ : `${ref.sessionId}:${label}`;
+}
+
+/** The plain-text `show`: the message, its graph neighbours, notes and turn. */
+export function formatShow(model: ShowModel): string[] {
+ const title = oneLine(model.sessionTitle) || model.sessionId;
+ const lines: string[] = [
+ `${model.id} ${model.label} ${model.title}`,
+ `Session: ${title} (${model.sessionId}) · ${model.epoch ?? "unassigned"} · ${stamp(model.at)}`,
+ ];
+ if (model.parent !== null) lines.push(`Parent: ${refText(model.parent, model.sessionId)}`);
+ if (model.children.length > 0)
+ lines.push(
+ `Children: ${model.children.map((ref) => refText(ref, model.sessionId)).join(", ")}`,
+ );
+ if (model.links.length > 0)
+ lines.push(`Returns to: ${model.links.map((ref) => refText(ref, model.sessionId)).join(", ")}`);
+ if (model.branch !== null) {
+ const count = `${model.branch.count} message${model.branch.count === 1 ? "" : "s"}`;
+ lines.push(
+ `Branch: ${model.branch.title} (${model.branch.start.label}–${model.branch.end.label}, ${count})`,
+ );
+ lines.push(` asked: ${model.branch.asked}`);
+ lines.push(` outcome: ${model.branch.outcome}`);
+ lines.push(` open: ${model.branch.open === "" ? "—" : model.branch.open}`);
+ }
+ if (model.decidedBy !== undefined) lines.push(`Decided by: ${model.decidedBy}`);
+ if (model.why !== undefined) lines.push(`Why: ${model.why}`);
+ if (model.alternatives !== undefined && model.alternatives.length > 0) {
+ lines.push("Considered and rejected:");
+ for (const alt of model.alternatives)
+ lines.push(` - ${alt.option}${alt.why === "" ? "" : ` — ${alt.why}`}`);
+ }
+ if (model.agentDecisions !== undefined && model.agentDecisions.length > 0) {
+ lines.push("Agent decisions:");
+ for (const decision of model.agentDecisions) {
+ lines.push(` - ${decision.title}${decision.why === "" ? "" : ` — ${decision.why}`}`);
+ for (const alt of decision.alternatives ?? [])
+ lines.push(` not: ${alt.option}${alt.why === "" ? "" : ` — ${alt.why}`}`);
+ }
+ }
+ if (model.work !== undefined && model.work.length > 0) {
+ lines.push("What the agent did:");
+ for (const item of model.work) lines.push(` - ${item}`);
+ }
+ if (model.commits.length > 0) {
+ lines.push("Commits:");
+ for (const commit of model.commits)
+ lines.push(
+ ` ${commit.hash}${commit.subject === undefined ? " (not in this repository)" : ` ${commit.subject}`}`,
+ );
+ }
+ if (model.files !== undefined && model.files.length > 0) {
+ lines.push("Files:");
+ for (const file of model.files) lines.push(` ${file}`);
+ }
+ if (model.chat === null) {
+ lines.push("Conversation: not available (the transcript is gone and nothing was stored)");
+ } else if (model.chat !== undefined) {
+ lines.push("Conversation:");
+ lines.push(` User: ${model.chat.text}`);
+ for (const reply of model.chat.replies) lines.push(` Agent: ${reply}`);
+ const { commands, files, other } = model.chat.tools;
+ const fileText =
+ files.length === 0 ? "" : `, ${files.length} file${files.length === 1 ? "" : "s"}`;
+ lines.push(
+ ` Tools: ${commands} command${commands === 1 ? "" : "s"}${fileText}, ${other} other`,
+ );
+ }
+ return lines;
+}
+
+export interface LogCommandOptions extends LogOptions {
+ dir: string;
+ io: Io;
+ json?: boolean;
+}
+
+/** `codelineage log [dir]`. */
+export async function log(opts: LogCommandOptions): Promise<LogModel> {
+ const root = await openProject(opts.dir);
+ const sessions = await loadEffectiveSessions(root, opts.io);
+ const model = buildLog(sessions, opts);
+ if (opts.json === true) {
+ opts.io.out(JSON.stringify(model, null, 2));
+ return model;
+ }
+ for (const line of formatLog(model, opts.branchesOnly === true)) opts.io.out(line);
+ return model;
+}
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index c690482..609a00a 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -12,6 +12,7 @@ import {
} from "./commands/config.js";
import { epochAdd } from "./commands/epoch.js";
import { type InitOptions, init } from "./commands/init.js";
+import { formatShow, log, show } from "./commands/log.js";
import { migrateIds } from "./commands/migrate.js";
import { openPanel, openProject } from "./commands/open.js";
import { readStdin, sessionShow, sessionWrite } from "./commands/session.js";
@@ -38,6 +39,14 @@ function retention(value: string): number | "keep" {
return days;
}
+/** `-n` for `log`: a positive whole number, or Commander's error message. */
+export function positiveCount(value: string): number {
+ const count = Number(value);
+ if (!Number.isInteger(count) || count < 1)
+ throw new InvalidArgumentError("a positive whole number");
+ return count;
+}
+
export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps = {}): Command {
const program = new Command()
.name("codelineage")
@@ -100,6 +109,48 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
}),
);
+ program
+ .command("log")
+ .description("print the recorded lineage, newest first")
+ .argument("[dir]", "project directory", ".")
+ .option("--session <id>", "only this session (id or prefix)")
+ .option("-n, --number <count>", "at most this many messages", positiveCount)
+ .option("--branches", "only the branch summaries (the compressed view)")
+ .option("--json", "print JSON instead of text")
+ .action(
+ run(
+ async (
+ dir: string,
+ opts: { session?: string; number?: number; branches?: boolean; json?: boolean },
+ ) => {
+ await log({
+ dir,
+ io: makeIo(false),
+ session: opts.session,
+ limit: opts.number,
+ branchesOnly: opts.branches === true,
+ json: opts.json === true,
+ });
+ },
+ ),
+ );
+
+ program
+ .command("show")
+ .description("print one recorded message by hash or <session-id>:mN")
+ .argument("<ref>", "message hash or <session-id-prefix>:mN")
+ .argument("[dir]", "project directory", ".")
+ .option("--no-chat", "leave out the conversation turn")
+ .option("--json", "print JSON instead of text")
+ .action(
+ run(async (ref: string, dir: string, opts: { chat?: boolean; json?: boolean }) => {
+ const io = makeIo(false);
+ const model = await show({ dir, ref, io, chat: opts.chat !== false });
+ if (opts.json === true) io.out(JSON.stringify(model, null, 2));
+ else for (const line of formatShow(model)) io.out(line);
+ }),
+ );
+
program
.command("open")
.description("build and open a project map, or the global panel without a directory")
diff --git a/packages/cli/test/log.test.ts b/packages/cli/test/log.test.ts
new file mode 100644
index 0000000..a936620
--- /dev/null
+++ b/packages/cli/test/log.test.ts
@@ -0,0 +1,358 @@
+import { mkdir, 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 {
+ branchesOf,
+ buildLog,
+ formatLog,
+ formatShow,
+ loadEffectiveSessions,
+ log,
+ resolveRef,
+ shortHash,
+ show,
+ stamp,
+} from "../src/commands/log.js";
+import { createProgram, positiveCount } from "../src/program.js";
+import type { Session } from "../src/schema/session.js";
+import { appendConversationTurns } from "../src/store/conversations.js";
+import { projectPaths } from "../src/store/paths.js";
+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";
+
+/** Four stable message ids; the first two share six hex characters on purpose. */
+const A = "h111111111111";
+const B = "h111111222222";
+const C = "h222222222222";
+const D = "h333333333333";
+
+function session(over: Partial<Session> & { sessionId: string }): Session {
+ return {
+ schema: 1,
+ agent: "claude-code",
+ title: "",
+ epoch: null,
+ startedAt: T0,
+ updatedAt: T0,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [],
+ ...over,
+ };
+}
+
+describe("codelineage log and show", () => {
+ let dir: string;
+ let root: string;
+ let io: FakeIo;
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ io = fakeIo(envFor(dir));
+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+
+ const s1 = session({
+ sessionId: "s1",
+ title: "Ship the parser",
+ epoch: "e8",
+ startedAt: "2026-10-20T09:00:00.000Z",
+ updatedAt: "2026-10-20T10:00:00.000Z",
+ nodes: [
+ {
+ id: A,
+ parent: null,
+ kind: "message",
+ title: "Start the parser",
+ at: "2026-10-20T09:00:00.000Z",
+ branch: { title: "Parser", asked: "How to read a file?", outcome: "It reads.", open: "" },
+ },
+ {
+ id: B,
+ parent: A,
+ kind: "message",
+ title: "Fix the loop",
+ at: "2026-10-20T09:30:00.000Z",
+ links: [A],
+ commits: ["abc1234"],
+ files: ["src/app.ts"],
+ decidedBy: "user",
+ why: "The loop ate one line.",
+ alternatives: [{ option: "Keep the loop", why: "It loses data." }],
+ work: ["Rewrote the loop"],
+ agentDecisions: [
+ {
+ title: "Kept the parser",
+ why: "It works.",
+ alternatives: [{ option: "Rewrite", why: "Too slow." }],
+ },
+ ],
+ },
+ {
+ id: C,
+ parent: B,
+ kind: "message",
+ title: "Ship it",
+ summary: "Shipped the parser.",
+ at: "2026-10-20T10:00:00.000Z",
+ },
+ ],
+ });
+ const s2 = session({
+ sessionId: "s2",
+ title: "Later chat",
+ startedAt: "2026-10-21T10:00:00.000Z",
+ updatedAt: "2026-10-21T10:10:00.000Z",
+ nodes: [
+ {
+ id: D,
+ parent: "s1:h111111111111",
+ kind: "message",
+ title: "Continue the parser",
+ at: "2026-10-21T10:00:00.000Z",
+ branch: { title: "Next", asked: "What next?", outcome: "More parsing.", open: "Tests" },
+ },
+ ],
+ });
+ await writeFile(projectPaths(root).session("s1"), JSON.stringify(s1));
+ await writeFile(projectPaths(root).session("s2"), JSON.stringify(s2));
+ // A session with no messages yet: the log still shows its header.
+ await writeFile(
+ projectPaths(root).session("old"),
+ JSON.stringify(
+ session({
+ sessionId: "old",
+ title: "Empty chat",
+ startedAt: "2026-10-19T08:00:00.000Z",
+ updatedAt: "2026-10-19T08:00:00.000Z",
+ }),
+ ),
+ );
+ // The stored conversation outlives the transcript, which no test has.
+ await appendConversationTurns(root, "s1", [
+ {
+ id: "m1",
+ uuid: "u1",
+ hash: A,
+ at: "2026-10-20T09:00:00.000Z",
+ text: "Start the parser",
+ replies: ["On it."],
+ tools: { commands: 2, files: ["src/app.ts"], other: 0 },
+ },
+ {
+ id: "m2",
+ uuid: "u2",
+ hash: B,
+ at: "2026-10-20T09:30:00.000Z",
+ text: "Fix the loop",
+ replies: [],
+ tools: { commands: 0, files: [], other: 0 },
+ },
+ ]);
+ });
+
+ async function effective() {
+ return loadEffectiveSessions(root, io);
+ }
+
+ it("shows a short hash, a prefix and a session:mN ref", () => {
+ expect(shortHash(A)).toBe("h1111111");
+ });
+
+ it("resolves full hashes, unique prefixes and session labels", async () => {
+ const sessions = await effective();
+ const full = resolveRef(sessions, A);
+ expect(full.kind).toBe("ok");
+ if (full.kind !== "ok") return;
+ expect(full.hit.message.label).toBe("m1");
+ expect(full.hit.session.sessionId).toBe("s1");
+
+ const prefix = resolveRef(sessions, "h222222");
+ expect(prefix.kind).toBe("ok");
+ if (prefix.kind === "ok") expect(prefix.hit.message.title).toBe("Ship it");
+
+ const sessionLabel = resolveRef(sessions, "s1:m2");
+ expect(sessionLabel.kind).toBe("ok");
+ if (sessionLabel.kind === "ok") expect(sessionLabel.hit.message.id).toBe(B);
+ });
+
+ it("lists candidates for an ambiguous prefix", async () => {
+ const result = resolveRef(await effective(), "h111111");
+ expect(result.kind).toBe("ambiguous");
+ if (result.kind !== "ambiguous") return;
+ expect(result.candidates.map((candidate) => candidate.id)).toEqual([A, B]);
+ });
+
+ it("says plainly when a ref is unknown or malformed", async () => {
+ const sessions = await effective();
+ expect(resolveRef(sessions, "h999999")).toMatchObject({ kind: "unknown" });
+ expect(resolveRef(sessions, "s1:m9")).toMatchObject({ kind: "unknown" });
+ expect(resolveRef(sessions, "nope:m1")).toMatchObject({ kind: "unknown" });
+ expect(resolveRef(sessions, "m3")).toMatchObject({ kind: "invalid" });
+ });
+
+ it("lists the sessions that match an ambiguous session prefix", async () => {
+ const result = resolveRef(await effective(), "s:m1");
+ expect(result.kind).toBe("ambiguous");
+ if (result.kind !== "ambiguous") return;
+ expect(result.candidates.map((candidate) => candidate.sessionId)).toEqual(["s1", "s2"]);
+ });
+
+ it("validates -n before Commander runs the command", () => {
+ expect(positiveCount("3")).toBe(3);
+ expect(() => positiveCount("0")).toThrow(/positive whole number/);
+ expect(() => positiveCount("1.5")).toThrow(/positive whole number/);
+ });
+
+ it("prints sessions newest first with labels, return marks and commits", async () => {
+ const model = await log({ dir: root, io });
+ const lines = formatLog(model);
+ expect(lines[0]).toContain("## Later chat (s2) · unassigned");
+ expect(lines[0]).toContain(stamp("2026-10-21T10:00:00.000Z"));
+ expect(lines[1]).toContain(shortHash(D));
+ expect(lines[1]).toContain("m1");
+ expect(lines[1]).toContain("╭ Next · Continue the parser");
+ const s1 = model.sessions.find((entry) => entry.sessionId === "s1");
+ expect(s1?.messages.map((message) => message.label)).toEqual(["m3", "m2", "m1"]);
+ const fix = lines.find((line) => line.includes("Fix the loop"));
+ expect(fix).toContain("↩ m1");
+ expect(fix).toContain("[abc1234]");
+ const start = lines.find((line) => line.includes("Start the parser"));
+ expect(start).toContain("╭ Parser · Start the parser");
+ });
+
+ it("filters by session and limits the number of messages", async () => {
+ const only = await log({ dir: root, io, session: "s1" });
+ expect(only.sessions.map((entry) => entry.sessionId)).toEqual(["s1"]);
+
+ const one = await log({ dir: root, io, limit: 1 });
+ expect(one.sessions.map((entry) => entry.sessionId)).toEqual(["s2"]);
+ expect(one.sessions[0]?.messages).toHaveLength(1);
+
+ await expect(log({ dir: root, io, session: "s" })).rejects.toThrow(/matches 2 sessions/);
+ await expect(log({ dir: root, io, session: "nope" })).rejects.toThrow(/no session matches/);
+ });
+
+ it("keeps a header for a session with no messages yet", async () => {
+ const model = await log({ dir: root, io });
+ const lines = formatLog(model);
+ expect(lines.join("\n")).toContain("## Empty chat (old)");
+ expect(lines.join("\n")).toContain("(no recorded messages)");
+ });
+
+ it("limits branch summaries too", async () => {
+ const model = buildLog(await effective(), { limit: 1, branchesOnly: true });
+ expect(model.sessions).toHaveLength(1);
+ expect(model.sessions[0]?.sessionId).toBe("s2");
+ expect(model.sessions[0]?.branches).toHaveLength(1);
+ });
+
+ it("compresses to branch summaries with --branches", async () => {
+ const model = await log({ dir: root, io, branchesOnly: true });
+ const lines = formatLog(model, true);
+ expect(lines.join("\n")).toContain("╭ Parser m1–m3, 3 messages");
+ expect(lines.join("\n")).toContain("asked: How to read a file?");
+ expect(lines.join("\n")).toContain("open: —");
+ expect(lines.join("\n")).toContain("╭ Next m1–m1, 1 message");
+ expect(lines.join("\n")).toContain("open: Tests");
+ expect(model.sessions[0]?.messages).toEqual([]);
+ });
+
+ it("builds branch ranges from the messages that carry them", async () => {
+ const sessions = await effective();
+ const s1 = sessions.find((entry) => entry.session.sessionId === "s1");
+ expect(branchesOf("s1", s1?.messages ?? [])).toMatchObject([
+ { title: "Parser", count: 3, start: { id: A }, end: { id: C } },
+ ]);
+ });
+
+ it("shows one message with its graph neighbours and its stored turn", async () => {
+ const model = await show({ dir: root, ref: B, io });
+ expect(model).toMatchObject({
+ id: B,
+ label: "m2",
+ title: "Fix the loop",
+ sessionId: "s1",
+ decidedBy: "user",
+ why: "The loop ate one line.",
+ });
+ expect(model.parent).toMatchObject({ sessionId: "s1", id: A, label: "m1" });
+ expect(model.children.map((child) => child.id)).toEqual([C]);
+ expect(model.links[0]).toMatchObject({ id: A, label: "m1" });
+ expect(model.branch?.title).toBe("Parser");
+ expect(model.commits).toEqual([{ hash: "abc1234" }]);
+ expect(model.chat).toMatchObject({ text: "Fix the loop", replies: [] });
+
+ const text = formatShow(model).join("\n");
+ expect(text).toContain(`${B} m2 Fix the loop`);
+ expect(text).toContain(`Parent: m1 ${shortHash(A)}`);
+ expect(text).toContain(`Children: m3 ${shortHash(C)}`);
+ expect(text).toContain(`Returns to: m1 ${shortHash(A)}`);
+ expect(text).toContain("Branch: Parser (m1–m3, 3 messages)");
+ expect(text).toContain("Considered and rejected:");
+ expect(text).toContain("Agent decisions:");
+ expect(text).toContain(" - Kept the parser — It works.");
+ expect(text).toContain(" not: Rewrite — Too slow.");
+ expect(text).toContain("abc1234 (not in this repository)");
+ expect(text).toContain("User: Fix the loop");
+ });
+
+ it("says when the transcript and the store are both gone, and can skip the chat", async () => {
+ const gone = await show({ dir: root, ref: C, io });
+ expect(gone.chat).toBeNull();
+ expect(formatShow(gone).join("\n")).toContain("Conversation: not available");
+
+ const skipped = await show({ dir: root, ref: A, io, chat: false });
+ expect(skipped.chat).toBeUndefined();
+ expect(formatShow(skipped).join("\n")).not.toContain("Conversation:");
+ });
+
+ it("prints a cross-session parent as that session's ref", async () => {
+ const model = await show({ dir: root, ref: D, io });
+ expect(model.parent).toMatchObject({ sessionId: "s1", id: A, label: "m1" });
+ expect(formatShow(model).join("\n")).toContain(`Parent: s1:m1 ${shortHash(A)}`);
+ });
+
+ it("exits non-zero for an ambiguous ref after listing the candidates", async () => {
+ await expect(show({ dir: root, ref: "h111111", io })).rejects.toThrow(/ambiguous/);
+ expect(io.lines.join("\n")).toContain("s1 · m1");
+ expect(io.lines.join("\n")).toContain("s1 · m2");
+ });
+
+ it("runs both verbs through the CLI", async () => {
+ const program = createProgram(() => io);
+ await program.parseAsync(["log", root, "--session", "s1", "--json"], { from: "user" });
+ const model = JSON.parse(io.lines.join("\n")) as { sessions: { sessionId: string }[] };
+ expect(model.sessions[0]?.sessionId).toBe("s1");
+
+ io.lines.length = 0;
+ const limited = createProgram(() => io);
+ await limited.parseAsync(["log", root, "-n", "1"], { from: "user" });
+ expect(io.lines[0]).toContain("## Later chat (s2)");
+ expect(io.lines.filter((line) => line.includes(" m1 "))).toHaveLength(1);
+
+ io.lines.length = 0;
+ const showProgram = createProgram(() => io);
+ await showProgram.parseAsync(["show", B, root], { from: "user" });
+ expect(io.lines.join("\n")).toContain("Session: Ship the parser (s1)");
+
+ io.lines.length = 0;
+ const jsonProgram = createProgram(() => io);
+ await jsonProgram.parseAsync(["show", B, root, "--no-chat", "--json"], { from: "user" });
+ const shown = JSON.parse(io.lines.join("\n")) as { id: string; chat?: unknown };
+ expect(shown.id).toBe(B);
+ expect(shown.chat).toBeUndefined();
+ });
+
+ it("refuses an uninitialized project", async () => {
+ const empty = join(dir, "empty");
+ await mkdir(empty);
+ await expect(log({ dir: empty, io })).rejects.toThrow(/not initialized/);
+ await expect(show({ dir: empty, ref: A, io })).rejects.toThrow(/not initialized/);
+ });
+
+ it("keeps the log model through the pure builder", async () => {
+ const model = buildLog(await effective(), { session: "s1" });
+ expect(model.sessions[0]?.branches).toHaveLength(1);
+ });
+});
diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsx
index a1d393a..418fb3e 100644
--- a/packages/template/src/SidePanel.tsx
+++ b/packages/template/src/SidePanel.tsx
@@ -9,10 +9,12 @@ import { resumeCommand } from "../../cli/src/view/resume.js";
import { formatTime, kindLabel } from "./format.js";
import { layoutGitGraph } from "./gitLayout.js";
import {
+ isMessageHash,
nodeId as messageKey,
messageNeighbors,
type NodeDetail,
sessionId as sessionKey,
+ shortHash,
toNodeDetail,
} from "./graph.js";
import type { OutlineTarget } from "./Outline.js";
@@ -73,6 +75,49 @@ export async function copyText(text: string): Promise<boolean> {
type CopyState = "idle" | "copied" | "failed";
+/**
+ * The message's stable hash with a copy button (Story 8.10): the user pastes it
+ * to the agent, which runs `codelineage show <hash>` for the full record.
+ */
+function MessageHash({ value }: { value: string }) {
+ const [state, setState] = useState<CopyState>("idle");
+ const code = useRef<HTMLElement>(null);
+ const title = `Ask your agent: codelineage show ${value}`;
+
+ const copy = (): void => {
+ setState("idle");
+ void copyText(value).then((ok) => {
+ if (ok) {
+ setState("copied");
+ return;
+ }
+ // Last resort, as for the resume command: select the hash for Ctrl+C.
+ const element = code.current;
+ if (element) {
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ const selection = window.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ }
+ setState("failed");
+ });
+ };
+
+ return (
+ <div className="message-hash" title={title}>
+ <code ref={code}>{shortHash(value)}</code>
+ <button type="button" onClick={copy}>
+ Copy hash
+ </button>
+ {state === "copied" ? <span className="muted">Copied.</span> : null}
+ {state === "failed" ? (
+ <span className="muted">Copy failed — press Ctrl+C to copy.</span>
+ ) : null}
+ </div>
+ );
+}
+
function ResumeRow({ model, session }: { model: LineageViewModel; session: ViewSession }) {
const [state, setState] = useState<CopyState>("idle");
const code = useRef<HTMLElement>(null);
@@ -354,6 +399,9 @@ function NodeDetails({
return (
<>
<MessageNav session={session} node={node} onNavigate={onNavigate} />
+ {node.kind === "message" && isMessageHash(node.nodeId) ? (
+ <MessageHash value={node.nodeId} />
+ ) : null}
{session ? <BranchDetails session={session} branchId={branchId} /> : null}
{node.summary ? (
<section>
diff --git a/packages/template/src/graph.ts b/packages/template/src/graph.ts
index 96baa61..96e454a 100644
--- a/packages/template/src/graph.ts
+++ b/packages/template/src/graph.ts
@@ -68,6 +68,16 @@ export function sessionId(id: string): string {
return `session:${id}`;
}
+/** A stable message id (Story 8.5): `h` plus 12 hex. Older records stay `m1`. */
+export function isMessageHash(id: string): boolean {
+ return /^h[0-9a-f]{12}$/.test(id);
+}
+
+/** `h3f2a1b8`: what the panel shows and `codelineage show` accepts. */
+export function shortHash(id: string): string {
+ return isMessageHash(id) ? id.slice(0, 8) : id;
+}
+
/** Outline group key of an epoch; epochs are only tags on the map now. */
export function epochId(id: string): string {
return `epoch:${id}`;
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index ae4269f..36b6d99 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -745,6 +745,34 @@ time {
cursor: default;
}
+/* The message's stable hash, ready to paste to the agent (Story 8.10). */
+.message-hash {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 12px;
+ font-size: 13px;
+}
+
+.message-hash code {
+ font-size: 12px;
+}
+
+.message-hash button {
+ padding: 3px 8px;
+ color: var(--text);
+ background: #243040;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.message-hash button:hover {
+ border-color: var(--accent);
+}
+
.chat-entry {
margin-top: 8px;
padding: 8px 10px;
diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.md
index 45537bd..47d9f44 100644
--- a/specs/codelineage-mvp.md
+++ b/specs/codelineage-mvp.md
@@ -129,6 +129,11 @@ first message of a branch, written when the branch ends rather than every turn.
`decidedBy` is `user | agent | agreed`. `addedAt` (first write) and `touchedAt`
(last change) are stamped by `session write` and never taken from agent input; a
resent node that changed nothing keeps its `touchedAt`. Epochs live in `project.json`.
+A message's stable id is `h` plus the first 12 hex of a SHA-256 over the session
+id, transcript uuid, time and text; `m1`, `m2`, … stay as display labels. A parent
+is not part of the hash, so correcting it never renames a message (unlike git, on
+purpose). `codelineage show` accepts the hash, any unique prefix of at least six
+hex characters after the `h`, or `<session-id-prefix>:mN`.
The agent picks an existing epoch or adds one through the CLI (`codelineage epoch add`),
which does a locked, atomic write.
@@ -242,6 +247,8 @@ Each update costs agent tokens (the user's subscription or API usage).
| `codelineage build [dir]` | Regenerates `lineage.html` and `panel.html` |
| `codelineage open [dir]` | Builds, then opens the map (or the panel if no dir is given) through the local map server, starting it in the background if it is not running. The open page refreshes itself whenever the map is rebuilt, keeping the selected branch, unfolded branches, scroll and zoom. Falls back to opening the file when the server cannot start. |
| `codelineage blame <file>[:<line>]` | Follows git blame (or `git log` for a whole file) back to the messages whose record lists those commits; prints each commit, session, message, summary and the map URL that opens that message. Says so plainly when no record knows the code. |
+| `codelineage log [dir]` | Prints the lineage like `git log --graph --oneline`, newest first: per message its short hash, `mN`, time, title, `↩` returns and commit tags, a branch's first message with the branch title, and a header line per session (title, epoch, time span). `--session <id\|prefix>` narrows to one session, `-n <count>` limits the messages, `--branches` prints only the branch summaries (title, asked, outcome, open — the compressed view), and `--json` prints the model. Plain text; no colour when not a TTY. |
+| `codelineage show <ref> [dir]` | Prints one message: hash, `mN`, session, time, parent and children (as refs), `links`, the branch it belongs to with that branch's summary, decisions (`decidedBy`, `why`, `alternatives`), agent decisions, work, commits with their git subjects, files, then its conversation turn from the store (`--no-chat` skips it; `--json` prints the model). A `<ref>` is a message hash or any unique prefix of at least six hex characters after the `h`, or `<session-id-prefix>:mN`; an ambiguous prefix lists the candidates and exits non-zero, an unknown one says so plainly. |
| `codelineage epoch add <id> <title>` | Adds an epoch (locked write) |
| `codelineage config get/set <key> [value]` | Reads or changes settings |
| `codelineage config hint-off [dir]` | Stops the SessionStart setup offer in that project ("don't ask again") |