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(map): hang a session's first message from an earlier session

Eren297655fe0bd7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 550119e..01abf4d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 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/`).
+- Cross-session lineage: a session's first message can hang from a message of an earlier session of the same project by writing `parent` as `<sessionId>:<messageId>` (`links` accept the same form). `session write` keeps such a reference only when the other session exists, started no later and holds that message; otherwise it warns and falls back to the previous message, as for any other bad parent. `session show` adds `candidates` (the last three messages of the three most recently updated other sessions) for a session's first unrecorded message, with `continuesHint` when the message says it continues ("devam", "kaldığımız yerden", "continue") or the transcript read a handoff file, and the skill gained the matching parent rule. On the map the message reads as a root of its own session plus a "↑ continues <session> · m67" mark that opens that session at the message.
### 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 fed4277..d675408 100644
--- a/packages/cli/skills/lineage/SKILL.md
+++ b/packages/cli/skills/lineage/SKILL.md
@@ -87,6 +87,12 @@ earlier one, and a thread that starts something new is a root.
a new chat and does not rely on the previous answer.
- An explicit return to an older thread ("back to the representation question"):
set `parent` to that thread's message and put the previous message in `links`.
+- The FIRST message of a session that continues earlier work hangs from the
+ message it continues: write `parent` as `<sessionId>:<stable id>`. `candidates`
+ in the record lists the last messages of the most recent other sessions for
+ this. Usually that is the last message of the previous session, or the one that
+ asked for a prompt for the next chat. A first message that starts something new
+ is a root. The target must be a message of an earlier session of this project.
- When unsure, use the previous message. A wrong "continue" only hides a branch;
a wrong branch breaks the chain.
- `links`: up to 5 earlier messages of this session that this one returns to or
@@ -100,6 +106,10 @@ earlier one, and a thread that starts something new is a root.
between), `commitBetween` (this session committed between them). The wording
decides. `lastMessages` lists the last recorded messages with their stable
`id`, `label` and parent.
+- For a session's first message, `candidates` names the message it may continue
+ (with its session and stable `id`) and `continuesHint` is set when the message
+ says so ("devam", "kaldığımız yerden", "continue") or the transcript read a
+ handoff file. A hint only: an unrelated first message stays a root.
## Summarize each branch
diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.ts
index 4bf73cc..43d65d5 100644
--- a/packages/cli/src/commands/session.ts
+++ b/packages/cli/src/commands/session.ts
@@ -11,7 +11,7 @@ import {
upgradeSessionIds,
} from "../messages.js";
import { redactDeep } from "../redact.js";
-import { Slug } from "../schema/common.js";
+import { parseMessageRef, 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";
@@ -20,12 +20,13 @@ import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import {
type Loaded,
+ listSessionIds,
loadConfig,
loadProject,
loadSession,
updateSession,
} from "../store/stores.js";
-import { countUserLines, excerpt, findTranscript } from "../transcript.js";
+import { countUserLines, excerpt, findTranscript, readsHandoff } from "../transcript.js";
import { buildProject } from "./build.js";
export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {
@@ -84,6 +85,11 @@ export async function sessionWrite(
);
}
+ // Cross-session parents (8.6) are checked against the other records before the
+ // merge; `startedAt` is the current session's own start.
+ const current = await loadSession(root, input.sessionId);
+ const startedAt = current.found && current.ok ? current.data.startedAt : io.now();
+ const crossTargets = await crossSessionTargets(root, input.sessionId, startedAt, input, io.env);
let warnings: string[] = [];
const saved = await updateSession(root, input.sessionId, async (cur) => {
// A record written before 8.5 still names messages `m1`, `m2`, …; the file is
@@ -94,6 +100,7 @@ export async function sessionWrite(
const merged = mergeSession(base, input, io.now(), {
...(messages ? { order: messageOrder(messages) } : {}),
labels: hashesToLabels(messages),
+ crossTargets,
});
warnings = merged.warnings;
const changes = structureChanges(merged.session, base, io.now());
@@ -136,6 +143,11 @@ function nameMessages(
const byLabel = labelsToHashes(messages);
const byHash = new Map((messages ?? []).map((message) => [message.hash, message]));
const rename = (id: string): string => byLabel.get(id) ?? id;
+ /** `thisSession:h…` names this session's own message; store it as a bare id. */
+ const ref = (id: string): string => {
+ const own = parseMessageRef(id);
+ return rename(own.sessionId === input.sessionId ? own.id : id);
+ };
return {
...input,
nodes: nodes.map((node) => {
@@ -151,15 +163,47 @@ function nameMessages(
...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) }),
+ ...(node.parent === undefined || node.parent === null ? {} : { parent: ref(node.parent) }),
+ ...(node.links === undefined ? {} : { links: node.links.map(ref) }),
};
}),
};
}
+/**
+ * The `<sessionId>:<id>` parents and links the input sends, kept only when the
+ * other session belongs to this project, started no later than this one and holds
+ * that message (Story 8.6). The rest reach the merge as unknown references and
+ * are warned about there; nothing is dropped silently.
+ */
+export async function crossSessionTargets(
+ root: string,
+ sessionId: string,
+ startedAt: string,
+ input: SessionInput,
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<Set<string>> {
+ const refs = new Set<string>();
+ for (const node of input.nodes ?? []) {
+ for (const value of [node.parent, ...(node.links ?? [])]) {
+ if (typeof value === "string" && parseMessageRef(value).sessionId !== null) refs.add(value);
+ }
+ }
+ const valid = new Set<string>();
+ for (const value of refs) {
+ const { sessionId: otherId, id } = parseMessageRef(value);
+ if (otherId === null || otherId === sessionId) continue;
+ const loaded = await loadSession(root, otherId);
+ if (!loaded.found || !loaded.ok) continue;
+ const otherStart = Date.parse(loaded.data.startedAt);
+ if (Number.isNaN(otherStart) || otherStart > Date.parse(startedAt)) continue;
+ const messages = await readSessionMessages(root, otherId, env);
+ const record = await effectiveRecord(root, otherId, loaded, messages);
+ if (record?.nodes.some((node) => node.kind === "message" && node.id === id)) valid.add(value);
+ }
+ return valid;
+}
+
/**
* 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
@@ -252,9 +296,16 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi
} else if (loaded.found && !loaded.ok) {
view.sessionError = loaded.error;
}
+ const recorded = recordedIdsOf(effective);
if (messages) {
view.messageCount = messages.length;
- view.newMessages = newMessages(messages, recordedIdsOf(effective), labels);
+ view.newMessages = newMessages(messages, recorded, labels);
+ // Only the session's first message can continue an earlier session (8.6).
+ const candidates =
+ messages.length > 0 && !isRecorded(recorded, messages[0] as SessionMessage)
+ ? await parentCandidates(root, sessionId, messages[0] as SessionMessage, io)
+ : null;
+ if (candidates) view.candidates = candidates;
} else {
view.newMessages = null;
}
@@ -326,6 +377,78 @@ function newMessages(
}));
}
+/** How many earlier sessions and messages `session show` offers for a parent. */
+const CANDIDATE_SESSIONS = 3;
+const CANDIDATE_MESSAGES = 3;
+
+/** A first message that says, in the user's words, that it continues earlier work. */
+const CONTINUES = /\b(devam|kaldığımız yerden|continue)\b/i;
+
+/**
+ * The candidates for hanging a session's first message from an earlier session
+ * (8.6): the last messages of the most recently updated other sessions, with a
+ * hint when the transcript shows a handoff file being read or the message itself
+ * says it continues. Cheap hints from records and the transcript, no model call.
+ */
+async function parentCandidates(
+ root: string,
+ sessionId: string,
+ first: SessionMessage,
+ io: Io,
+): Promise<Record<string, unknown>> {
+ // Newest records first, and only the three that keep a message need their
+ // transcript read (old ids become stable ones there).
+ const recent: Session[] = [];
+ for (const id of await listSessionIds(projectPaths(root).sessions)) {
+ if (id === sessionId) continue;
+ const loaded = await loadSession(root, id);
+ if (loaded.found && loaded.ok) recent.push(loaded.data);
+ }
+ recent.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+ const others: {
+ sessionId: string;
+ title: string;
+ updatedAt: string;
+ messages: { id: string; title: string; at?: string }[];
+ }[] = [];
+ for (const candidate of recent) {
+ const nodes = [...candidate.nodes]
+ .filter((node) => node.kind === "message")
+ .sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));
+ if (nodes.length === 0) continue;
+ // Only a legacy record needs its transcript (for stable ids); the rest are
+ // already keyed by them, so most sessions cost one file read.
+ const messages = await readSessionMessages(root, candidate.sessionId, io.env);
+ const record = await effectiveRecord(
+ root,
+ candidate.sessionId,
+ { found: true, ok: true, data: candidate, warnings: [] },
+ messages,
+ );
+ const effective = (record?.nodes ?? nodes)
+ .filter((node) => node.kind === "message")
+ .sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));
+ others.push({
+ sessionId: candidate.sessionId,
+ title: candidate.title,
+ updatedAt: candidate.updatedAt,
+ messages: effective.slice(-CANDIDATE_MESSAGES).map(({ id: messageId, title, at }) => ({
+ id: messageId,
+ title,
+ ...(at === undefined ? {} : { at }),
+ })),
+ });
+ if (others.length === CANDIDATE_SESSIONS) break;
+ }
+ const file = await findTranscript(sessionId, io.env);
+ const handoff = file ? await readsHandoff(file).catch(() => false) : false;
+ return {
+ forMessage: { id: first.hash, label: first.label },
+ ...(handoff || CONTINUES.test(first.text) ? { continuesHint: true } : {}),
+ sessions: others,
+ };
+}
+
/** The last few recorded messages (stable id, label, title, parent) for a parent pick. */
function lastMessages(
session: Session | null,
diff --git a/packages/cli/src/schema/common.ts b/packages/cli/src/schema/common.ts
index 9cd3587..e4cee98 100644
--- a/packages/cli/src/schema/common.ts
+++ b/packages/cli/src/schema/common.ts
@@ -6,3 +6,29 @@ export const Slug = z
.regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/, "must be a slug: letters, digits, _ . -");
export const IsoDate = z.iso.datetime({ offset: true });
+
+/**
+ * A message reference in a parent or link (Story 8.6): a bare id for a message
+ * of the same session, or `<sessionId>:<messageId>` for a message of an earlier
+ * session of the same project. Both halves follow the slug rule.
+ */
+export const MessageRef = z
+ .string()
+ .regex(
+ /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(:[A-Za-z0-9][A-Za-z0-9_.-]{0,127})?$/,
+ "must be a node id or <sessionId>:<messageId>",
+ );
+
+export interface MessageRefParts {
+ /** The other session, or null when the reference stays inside this one. */
+ sessionId: string | null;
+ id: string;
+}
+
+/** Splits `<sessionId>:<id>`; a bare id has no session. */
+export function parseMessageRef(ref: string): MessageRefParts {
+ const at = ref.indexOf(":");
+ return at === -1
+ ? { sessionId: null, id: ref }
+ : { sessionId: ref.slice(0, at), id: ref.slice(at + 1) };
+}
diff --git a/packages/cli/src/schema/events.ts b/packages/cli/src/schema/events.ts
index e0f9f60..83172b8 100644
--- a/packages/cli/src/schema/events.ts
+++ b/packages/cli/src/schema/events.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { IsoDate, Slug } from "./common.js";
+import { IsoDate, MessageRef, Slug } from "./common.js";
/**
* Structure changes of one session, appended and never rewritten (Story 8.5).
@@ -14,7 +14,7 @@ export const SessionEvent = z.object({
/** 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(),
+ target: MessageRef.nullable(),
/** Who made the change: the agent's record, or the user correcting it. */
by: z.enum(["agent", "user"]).default("agent"),
});
diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.ts
index f9c5fdd..bd9ab13 100644
--- a/packages/cli/src/schema/merge.ts
+++ b/packages/cli/src/schema/merge.ts
@@ -1,3 +1,4 @@
+import { parseMessageRef } from "./common.js";
import {
type LineageNode,
MESSAGE_ID,
@@ -19,6 +20,12 @@ export interface MergeOptions {
order?: ReadonlyMap<string, number>;
/** Stable id → display label, for warnings the agent reads. */
labels?: ReadonlyMap<string, string>;
+ /**
+ * Cross-session references (`<sessionId>:<id>`) that were checked against the
+ * project's records: the other session exists, holds that message, and started
+ * earlier (Story 8.6). Anything else is refused like an unknown parent.
+ */
+ crossTargets?: ReadonlySet<string>;
}
/**
@@ -67,13 +74,13 @@ export function mergeSession(
const own = n.kind === "message" ? (recorded.get(n.id) ?? null) : null;
const nextParent =
parent !== undefined && own !== null
- ? checkParent(n.id, parent, own, recorded, messageWarnings, label)
+ ? checkParent(n.id, parent, own, recorded, messageWarnings, label, opts.crossTargets)
: parent === undefined
? (prev?.parent ?? null)
: parent;
const nextLinks =
links !== undefined && own !== null
- ? checkLinks(n.id, links, own, recorded, messageWarnings, label)
+ ? checkLinks(n.id, links, own, recorded, messageWarnings, label, opts.crossTargets)
: links;
const next: LineageNode = {
...prev,
@@ -140,17 +147,25 @@ function checkParent(
numbers: Map<string, number>,
warnings: string[],
label: (id: string) => string,
+ crossTargets: ReadonlySet<string> | undefined,
): string | null {
if (parent === null || isEarlierMessage(numbers, parent, own)) return parent;
+ if (isCrossTarget(parent, crossTargets)) return parent;
const fallback = previousMessage(numbers, own);
+ const cross = parseMessageRef(parent).sessionId !== null;
warnings.push(
fallback === null
- ? `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)}`,
+ ? `message ${label(id)}: parent ${label(parent)} is not ${cross ? "a message of an earlier session in this project" : "an earlier message of this session"}, moved to root`
+ : `message ${label(id)}: parent ${label(parent)} is not ${cross ? "a message of an earlier session in this project" : "an earlier message of this session"}, using ${label(fallback)}`,
);
return fallback;
}
+/** A `<sessionId>:<id>` reference that was checked against the other record. */
+function isCrossTarget(ref: string, crossTargets: ReadonlySet<string> | undefined): boolean {
+ return parseMessageRef(ref).sessionId !== null && (crossTargets?.has(ref) ?? false);
+}
+
/** Links point at earlier messages too; a forward or unknown one is dropped. */
function checkLinks(
id: string,
@@ -159,11 +174,13 @@ function checkLinks(
numbers: Map<string, number>,
warnings: string[],
label: (id: string) => string,
+ crossTargets: ReadonlySet<string> | undefined,
): string[] {
return links.filter((link) => {
- if (isEarlierMessage(numbers, link, own)) return true;
+ if (isEarlierMessage(numbers, link, own) || isCrossTarget(link, crossTargets)) return true;
+ const cross = parseMessageRef(link).sessionId !== null;
warnings.push(
- `message ${label(id)}: link ${label(link)} is not an earlier message of this session, dropped`,
+ `message ${label(id)}: link ${label(link)} is not ${cross ? "a message of an earlier session in this project" : "an earlier message of this session"}, dropped`,
);
return false;
});
@@ -191,12 +208,16 @@ function sameNode(a: LineageNode, b: LineageNode): boolean {
return NODE_FIELDS.every((field) => JSON.stringify(a[field]) === JSON.stringify(b[field]));
}
-/** Re-roots nodes whose parent is missing or that sit on a cycle. Mutates in place. */
+/**
+ * Re-roots nodes whose parent is missing or that sit on a cycle. Mutates in
+ * place. A `<sessionId>:<id>` parent (Story 8.6) belongs to another session's
+ * graph, so it is not looked up here and never re-rooted.
+ */
export function repairTree(nodes: LineageNode[]): string[] {
const warnings: string[] = [];
const byId = new Map(nodes.map((n) => [n.id, n]));
for (const n of nodes) {
- if (n.parent !== null && !byId.has(n.parent)) {
+ if (n.parent !== null && parseMessageRef(n.parent).sessionId === null && !byId.has(n.parent)) {
warnings.push(`node ${n.id}: parent ${n.parent} not found, moved to root`);
n.parent = null;
}
diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.ts
index 1d39b02..cefb255 100644
--- a/packages/cli/src/schema/session.ts
+++ b/packages/cli/src/schema/session.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { IsoDate, Slug } from "./common.js";
+import { IsoDate, MessageRef, Slug } from "./common.js";
export const SESSION_SCHEMA = 1;
@@ -46,9 +46,10 @@ export const LineageNode = z.object({
id: Slug,
/**
* For a message: the id of the earlier message it reacts to (`m3` for `m7`),
- * or null for a new root. For other kinds: the node it belongs to.
+ * `<sessionId>:<id>` for a message of an earlier session (Story 8.6), or null
+ * for a new root. For other kinds: the node it belongs to.
*/
- parent: Slug.nullable().default(null),
+ parent: MessageRef.nullable().default(null),
kind: NodeKind,
title: z.string().min(1).max(200),
summary: z.string().max(2000).optional(),
@@ -65,7 +66,7 @@ export const LineageNode = z.object({
/** Files this work touched, relative to the project. */
files: z.array(z.string().min(1).max(300)).max(30).optional(),
/** For a message: earlier messages it returns to or builds on besides its parent. */
- links: z.array(Slug).max(5).optional(),
+ links: z.array(MessageRef).max(5).optional(),
/** For the first message of a branch: the summary of that thread. */
branch: BranchSummary.optional(),
/** For a message: what the agent did about it, in short items. */
@@ -106,7 +107,7 @@ export const Session = z.object({
/** In input, a missing parent keeps the stored one (null for a new node). */
export const LineageNodeInput = LineageNode.omit({ addedAt: true, touchedAt: true }).extend({
- parent: Slug.nullable().optional(),
+ parent: MessageRef.nullable().optional(),
});
/**
diff --git a/packages/cli/src/transcript.ts b/packages/cli/src/transcript.ts
index 4abdf56..e26da48 100644
--- a/packages/cli/src/transcript.ts
+++ b/packages/cli/src/transcript.ts
@@ -254,6 +254,22 @@ function hasCommit(line: Record<string, unknown>): boolean {
);
}
+/**
+ * Whether the transcript shows the agent reading a handoff file (Story 8.6): a
+ * cheap hint that this session continues earlier work. A tool-use line names the
+ * tool before its input, so `Read` and `file_path` share the line.
+ */
+export async function readsHandoff(file: string): Promise<boolean> {
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
+ for await (const raw of lines) {
+ if (!raw.includes("handoff")) continue;
+ if (/"name":"(?:Read|Bash)"/.test(raw) && /"file_path":"[^"]*handoff[^"]*"/i.test(raw))
+ return true;
+ if (/"name":"Bash"[^}]*"command":"[^"]*handoff/i.test(raw)) return true;
+ }
+ return false;
+}
+
/** Reads the user's messages from a transcript, in order. */
export async function readUserMessages(file: string): Promise<UserMessage[]> {
return (await readConversation(file)).map(({ id, at, text, resumed, commitBetween }) => ({
diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.ts
index 161d06c..98a415b 100644
--- a/packages/cli/src/view/lineage.ts
+++ b/packages/cli/src/view/lineage.ts
@@ -76,12 +76,19 @@ export function buildMessages(
continue;
}
const node = row.node;
+ // A `<sessionId>:<id>` parent points into another session's graph (8.6): it
+ // stays on the node for the map to resolve, and the local layout sees no
+ // parent (the message reads as a root of this session).
+ const parentRef = node.parent ?? null;
+ const cross = parentRef !== null && parentRef.includes(":");
const parent =
- node.parent === null
+ parentRef === null
? null
- : node.parent !== undefined && known.has(node.parent) && earlier(node.parent, node.id)
- ? node.parent
- : previous;
+ : cross
+ ? parentRef
+ : known.has(parentRef) && earlier(parentRef, node.id)
+ ? parentRef
+ : previous;
const links = (node.links ?? []).filter((link) => known.has(link) && earlier(link, node.id));
push(
{
@@ -219,6 +226,35 @@ export interface ViewModelInput {
pending?: ReadonlyMap<string, ViewPendingMessage[]> | undefined;
}
+/**
+ * Turns a `<sessionId>:<id>` parent into the `continues` mark the map draws and
+ * leaves the message a root of its own session, so one session's graph never
+ * leaks into another's (8.6). Runs once every session's labels are known.
+ * A target the map no longer holds still gets the mark, with the raw id.
+ */
+export function resolveContinues(sessions: ViewSession[]): void {
+ const byId = new Map(sessions.map((session) => [session.sessionId, session]));
+ for (const session of sessions) {
+ for (const message of session.messages) {
+ const parent = message.parent;
+ if (typeof parent !== "string") continue;
+ const at = parent.indexOf(":");
+ if (at === -1) continue;
+ const otherId = parent.slice(0, at);
+ const id = parent.slice(at + 1);
+ const other = byId.get(otherId);
+ const target = other?.messages.find((candidate) => candidate.id === id);
+ message.parent = null;
+ message.continues = {
+ sessionId: otherId,
+ sessionTitle: other?.title || otherId,
+ id,
+ ...(target?.label === undefined ? {} : { label: target.label }),
+ };
+ }
+ }
+}
+
/**
* Builds the page model: epochs in project order, sessions by `startedAt`, and
* every session whose epoch is null or unknown in the `unassigned` group.
@@ -229,6 +265,7 @@ export function buildViewModel(input: ViewModelInput): LineageViewModel {
);
const unassigned: ViewSession[] = [];
const sessions = [...input.sessions].sort(byStartedAt);
+ const views: ViewSession[] = [];
for (const session of sessions) {
const view = toViewSession(
@@ -240,7 +277,9 @@ export function buildViewModel(input: ViewModelInput): LineageViewModel {
);
const bucket = session.epoch === null ? undefined : buckets.get(session.epoch);
(bucket ?? unassigned).push(view);
+ views.push(view);
}
+ resolveContinues(views);
const epochs: ViewEpoch[] = input.project.epochs.map((epoch) => ({
id: epoch.id,
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index e260947..3fca781 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -36,6 +36,12 @@ export interface ViewNode {
* message when a record points elsewhere).
*/
parent?: string | null;
+ /**
+ * Set when the message hangs from a message of an earlier session (Story
+ * 8.6): the map then draws a "continues …" mark and a root for the layout,
+ * because the other session has its own graph.
+ */
+ continues?: ViewContinue;
/** Earlier messages this one returns to or builds on besides its parent. */
links?: string[];
/** On a branch's first message: what that thread asked and what came of it. */
@@ -60,6 +66,17 @@ export interface ViewNode {
unsummarized?: true;
}
+/** The earlier session's message a first message continues (Story 8.6). */
+export interface ViewContinue {
+ sessionId: string;
+ /** The other session's title, or its id when the record is gone. */
+ sessionTitle: string;
+ /** The id of the message in the other session. */
+ id: string;
+ /** Its `m67` label from that session, when the message is still there. */
+ label?: string;
+}
+
export interface ViewPendingItem {
text: string;
needsUser: boolean;
diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.ts
index 43600cf..d2beb19 100644
--- a/packages/cli/test/build.test.ts
+++ b/packages/cli/test/build.test.ts
@@ -105,6 +105,15 @@ describe("buildMessages", () => {
expect(forward.map((m) => m.parent)).toEqual([null, null]);
});
+ it("keeps a cross-session parent for the map to resolve", () => {
+ const t = (h: number) => `2026-10-23T${String(h).padStart(2, "0")}:00:00.000Z`;
+ const messages = buildMessages([
+ node("h1", "message", "One", null, { at: t(1) }),
+ node("h2", "message", "Continues the last chat", "first:h9", { at: t(2) }),
+ ]);
+ expect(messages.map((m) => m.parent)).toEqual([null, "first:h9"]);
+ });
+
it("keeps only links to earlier messages and a branch summary where it belongs", () => {
const t = (h: number) => `2026-10-23T${String(h).padStart(2, "0")}:00:00.000Z`;
const branch = { title: "Thread", asked: "What?", outcome: "This.", open: "" };
@@ -224,6 +233,35 @@ describe("buildViewModel", () => {
});
});
+ it("turns a cross-session parent into a continues mark and a root", () => {
+ const model = buildViewModel({
+ project: { schema: 1, name: "p", epochs: [] },
+ sessions: [
+ session({
+ sessionId: "first",
+ title: "Earlier chat",
+ startedAt: "2026-10-21T09:00:00.000Z",
+ nodes: [node("h1", "message", "Ask for the prompt", null, { at: T0 })],
+ }),
+ session({
+ sessionId: "second",
+ title: "Next chat",
+ startedAt: "2026-10-21T10:00:00.000Z",
+ nodes: [node("h2", "message", "Continue", "first:h1", { at: T0 })],
+ }),
+ ],
+ path: "/tmp/p",
+ generatedAt: T0,
+ });
+ const second = model.unassigned.find((s) => s.sessionId === "second");
+ expect(second?.messages[0]).toMatchObject({
+ parent: null,
+ continues: { sessionId: "first", sessionTitle: "Earlier chat", id: "h1", label: "m1" },
+ });
+ // The other session is untouched: its own message stays a root.
+ expect(model.unassigned[0]?.messages[0]?.continues).toBeUndefined();
+ });
+
it("has an empty status card without sessions", () => {
const model = buildViewModel({
project: { schema: 1, name: "p", epochs: [] },
diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.ts
index d9eb1c9..1d803d7 100644
--- a/packages/cli/test/schema.test.ts
+++ b/packages/cli/test/schema.test.ts
@@ -258,6 +258,31 @@ describe("mergeSession", () => {
});
});
+describe("cross-session references (Story 8.6)", () => {
+ it("accepts <sessionId>:<id> in a parent or link and refuses a malformed one", () => {
+ const parsed = input({
+ sessionId: "s1",
+ nodes: [{ id: "h1", kind: "message", title: "M", parent: "other:h0", links: ["other:h2"] }],
+ });
+ expect(parsed.nodes?.[0]?.parent).toBe("other:h0");
+ expect(parsed.nodes?.[0]?.links).toEqual(["other:h2"]);
+ for (const parent of ["a:b:c", ":h1", "a:", "other:h 1"]) {
+ expect(
+ SessionInput.safeParse({
+ sessionId: "s1",
+ nodes: [{ id: "h1", kind: "message", title: "M", parent }],
+ }).success,
+ ).toBe(false);
+ }
+ });
+
+ it("leaves a cross-session parent out of the local tree repair", () => {
+ const nodes = [node("a", "other:h1")];
+ expect(repairTree(nodes)).toEqual([]);
+ expect(nodes[0]?.parent).toBe("other:h1");
+ });
+});
+
describe("repairTree", () => {
it("re-roots nodes with a missing parent", () => {
const nodes = [node("a", "ghost")];
diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.ts
index dcbdfff..75e4efc 100644
--- a/packages/cli/test/session.test.ts
+++ b/packages/cli/test/session.test.ts
@@ -9,7 +9,7 @@ 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";
+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";
describe("redactText", () => {
it.each([
@@ -131,6 +131,68 @@ describe("session write", () => {
]);
});
+ it("hangs a message from an earlier session and refuses an unknown target", async () => {
+ await write({ sessionId: "first", nodes: [{ id: "m1", kind: "message", title: "Ask" }] });
+ const crossIo = fakeIo(envFor(dir));
+ await sessionWrite({ dir: root }, crossIo, async () =>
+ JSON.stringify({
+ sessionId: "second",
+ nodes: [
+ {
+ id: "m1",
+ kind: "message",
+ title: "Continue",
+ parent: "first:m1",
+ links: ["first:m1", "ghost:m1"],
+ },
+ // The session's own prefix is stored as the bare id.
+ { id: "m2", kind: "message", title: "Next", parent: "second:m1" },
+ ],
+ }),
+ );
+ const s = await loadSession(root, "second");
+ const nodes = s.found && s.ok ? s.data.nodes : [];
+ expect(nodes.map((n) => [n.id, n.parent])).toEqual([
+ ["m1", "first:m1"],
+ ["m2", "m1"],
+ ]);
+ expect(nodes[0]?.links).toEqual(["first:m1"]);
+ expect(crossIo.warnings).toEqual([
+ expect.stringMatching(
+ /link ghost:m1 is not a message of an earlier session in this project, dropped/,
+ ),
+ ]);
+ });
+
+ it("refuses a message of a session that started later", async () => {
+ await mkdir(join(root, ".codelineage", "sessions"), { recursive: true });
+ await writeFile(
+ join(root, ".codelineage", "sessions", "late.json"),
+ JSON.stringify({
+ schema: 1,
+ sessionId: "late",
+ agent: "claude-code",
+ title: "",
+ epoch: null,
+ startedAt: "2026-10-22T00:00:00.000Z",
+ updatedAt: "2026-10-22T00:00:00.000Z",
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [{ id: "m1", parent: null, kind: "message", title: "Later" }],
+ }),
+ );
+ await write({
+ sessionId: "second",
+ nodes: [{ id: "m1", kind: "message", title: "C", parent: "late:m1" }],
+ });
+ expect(io.warnings).toContainEqual(
+ expect.stringMatching(
+ /parent late:m1 is not a message of an earlier session in this project, moved to root/,
+ ),
+ );
+ const s = await loadSession(root, "second");
+ expect(s.found && s.ok && s.data.nodes[0]?.parent).toBeNull();
+ });
+
it("rejects invalid JSON and schema mismatches", async () => {
await expect(write("{nope")).rejects.toThrow(/not valid JSON/);
await expect(write({ sessionId: "../x" })).rejects.toThrow(/sessionId:/);
@@ -373,6 +435,95 @@ ${line("second", 2)}
});
});
+ it("offers the last messages of recent sessions when the first message may continue one", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ await sessionWrite({ dir: root }, fakeIo(envFor(dir)), async () =>
+ JSON.stringify({
+ sessionId: "first",
+ title: "Epic 8 work",
+ nodes: [
+ { id: "m1", kind: "message", title: "One", at: "2026-10-22T09:00:00.000Z" },
+ { id: "m2", kind: "message", title: "Two", parent: "m1", at: "2026-10-22T09:10:00.000Z" },
+ {
+ id: "m3",
+ kind: "message",
+ title: "Three",
+ parent: "m2",
+ at: "2026-10-22T09:20:00.000Z",
+ },
+ {
+ id: "m4",
+ kind: "message",
+ title: "Four",
+ parent: "m3",
+ at: "2026-10-22T09:30:00.000Z",
+ },
+ ],
+ }),
+ );
+ const folder = join(dir, "claude", "projects", "-p");
+ await mkdir(folder, { recursive: true });
+ const at = "2026-10-22T10:00:00.000Z";
+ const text = "Kaldığımız yerden devam edelim";
+ await writeFile(
+ join(folder, "second.jsonl"),
+ JSON.stringify({ type: "user", timestamp: at, message: { role: "user", content: text } }),
+ );
+
+ await sessionShow(root, "second", io);
+ expect(shown().candidates).toEqual({
+ forMessage: { id: messageHash("second", { at, text }), label: "m1" },
+ continuesHint: true,
+ sessions: [
+ {
+ sessionId: "first",
+ title: "Epic 8 work",
+ updatedAt: T0,
+ // The last three messages, oldest first: enough to pick the parent.
+ messages: [
+ { id: "m2", title: "Two", at: "2026-10-22T09:10:00.000Z" },
+ { id: "m3", title: "Three", at: "2026-10-22T09:20:00.000Z" },
+ { id: "m4", title: "Four", at: "2026-10-22T09:30:00.000Z" },
+ ],
+ },
+ ],
+ });
+ });
+
+ it("sets the continues hint when the transcript read a handoff file", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ const folder = join(dir, "claude", "projects", "-p");
+ await mkdir(folder, { recursive: true });
+ const at = "2026-10-22T10:00:00.000Z";
+ const user = JSON.stringify({
+ type: "user",
+ timestamp: at,
+ message: { role: "user", content: "Start here" },
+ });
+ const read = JSON.stringify({
+ type: "assistant",
+ timestamp: at,
+ message: {
+ role: "assistant",
+ content: [
+ { type: "tool_use", name: "Read", input: { file_path: "/p/handoff-2026-10-24.md" } },
+ { type: "text", text: "Reading the handoff." },
+ ],
+ },
+ });
+ await writeFile(join(folder, "second.jsonl"), `${user}\n${read}\n`);
+
+ await sessionShow(root, "second", io);
+ expect(shown().candidates).toEqual({
+ forMessage: {
+ id: messageHash("second", { at, text: "Start here" }),
+ label: "m1",
+ },
+ continuesHint: true,
+ sessions: [],
+ });
+ });
+
it("flags an unreadable record instead of hiding it", async () => {
await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
await writeFile(join(root, ".codelineage", "sessions", "s1.json"), "{nope");
diff --git a/packages/cli/test/transcript.test.ts b/packages/cli/test/transcript.test.ts
index 8794e6e..690f398 100644
--- a/packages/cli/test/transcript.test.ts
+++ b/packages/cli/test/transcript.test.ts
@@ -8,6 +8,7 @@ import {
findTranscript,
messageText,
readConversation,
+ readsHandoff,
readUserMessages,
} from "../src/transcript.js";
import { envFor, tempDir } from "./helpers.js";
@@ -176,6 +177,32 @@ describe("findTranscript", () => {
});
});
+describe("readsHandoff", () => {
+ const tool = (name: string, input: Record<string, unknown>) =>
+ JSON.stringify({
+ type: "assistant",
+ message: { role: "assistant", content: [{ type: "tool_use", name, input }] },
+ });
+
+ it("notices a handoff file read with Read or shown with Bash", async () => {
+ const dir = await tempDir();
+ const read = join(dir, "read.jsonl");
+ await writeFile(read, `${tool("Read", { file_path: "/p/handoff-2026-10-24.md" })}\n`);
+ expect(await readsHandoff(read)).toBe(true);
+
+ const bash = join(dir, "bash.jsonl");
+ await writeFile(bash, `${tool("Bash", { command: "sed -n 1,40p handoff-2026-10-24.md" })}\n`);
+ expect(await readsHandoff(bash)).toBe(true);
+ });
+
+ it("ignores a transcript without a handoff read", async () => {
+ const dir = await tempDir();
+ const file = join(dir, "other.jsonl");
+ await writeFile(file, `${tool("Read", { file_path: "/p/README.md" })}\n`);
+ expect(await readsHandoff(file)).toBe(false);
+ });
+});
+
describe("excerpt", () => {
it("collapses whitespace, names pastes and drops reminders", () => {
const text =
diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsx
index 076d047..10b9f1e 100644
--- a/packages/template/src/GitGraph.tsx
+++ b/packages/template/src/GitGraph.tsx
@@ -1,4 +1,5 @@
import { type MouseEvent, type ReactElement, useMemo } from "react";
+import type { ViewNode } from "../../cli/src/view/model.js";
import { formatStamp } from "./format.js";
import {
branchPath,
@@ -45,6 +46,7 @@ function Row({
branchSelected,
onSelect,
onUnfold,
+ onContinue,
}: {
row: GitRow;
branchTitle: string;
@@ -52,6 +54,7 @@ function Row({
branchSelected: boolean;
onSelect: (row: GitMessageRow) => void;
onUnfold: (segmentId: string) => void;
+ onContinue: (continues: NonNullable<ViewNode["continues"]>) => void;
}) {
const style = {
top: row.y - row.height / 2,
@@ -100,6 +103,19 @@ function Row({
) : null}
<span className="git-id">{message.label ?? message.id}</span>
<span className="git-title">{message.title}</span>
+ {message.continues ? (
+ <span
+ className="git-continues"
+ title={`Open ${message.continues.sessionTitle} at ${message.continues.label ?? message.continues.id}`}
+ onClick={(event: MouseEvent) => {
+ event.stopPropagation();
+ onContinue(message.continues as NonNullable<ViewNode["continues"]>);
+ }}
+ >
+ ↑ continues {message.continues.sessionTitle} ·{" "}
+ {message.continues.label ?? message.continues.id}
+ </span>
+ ) : null}
{returnMark(row)}
{row.head ? <span className="left-off">left off here</span> : null}
{message.unsummarized ? <span className="unsummarized">not summarized yet</span> : null}
@@ -113,6 +129,7 @@ export function GitGraph({
activeSegmentId,
onSelect,
onUnfold,
+ onContinue,
}: {
git: GitLayout;
/** Message id of the open drill-down, if it belongs to this session. */
@@ -121,6 +138,8 @@ export function GitGraph({
activeSegmentId: string | null;
onSelect: (row: GitMessageRow) => void;
onUnfold: (segmentId: string) => void;
+ /** Opens the earlier session this message continues, at that message. */
+ onContinue: (continues: NonNullable<ViewNode["continues"]>) => void;
}) {
const branches = useMemo(
() => new Map(git.segments.map((segment) => [segment.id, segment])),
@@ -208,6 +227,7 @@ export function GitGraph({
branchSelected={activeSegmentId !== null && row.segmentId === activeSegmentId}
onSelect={onSelect}
onUnfold={onUnfold}
+ onContinue={onContinue}
/>
);
})}
diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsx
index e299c52..6b1089f 100644
--- a/packages/template/src/Graph.tsx
+++ b/packages/template/src/Graph.tsx
@@ -47,11 +47,14 @@ import { DrillDown, type Selection } from "./SidePanel.js";
const GraphActions = createContext<{
toggle: (id: string) => void;
openRow: (sessionId: string, messageId: string, segmentId: string) => void;
+ /** Opens another session at one of its messages (a "continues" mark, 8.6). */
+ openContinue: (sessionId: string, messageId: string) => void;
unfold: (segmentId: string) => void;
selection: Selection | null;
}>({
toggle: () => {},
openRow: () => {},
+ openContinue: () => {},
unfold: () => {},
selection: null,
});
@@ -112,7 +115,7 @@ function EpochNode({ id, data }: NodeProps<EpochFlowNode>) {
}
function SessionNode({ id, data }: NodeProps<SessionFlowNode>) {
- const { selection, openRow, unfold } = useContext(GraphActions);
+ const { selection, openRow, openContinue, unfold } = useContext(GraphActions);
const selectedId =
selection?.type === "node" && selection.sessionId === data.sessionId ? selection.nodeId : null;
const activeSegmentId =
@@ -142,6 +145,7 @@ function SessionNode({ id, data }: NodeProps<SessionFlowNode>) {
activeSegmentId={activeSegmentId}
onSelect={(row: GitMessageRow) => openRow(data.sessionId, row.message.id, row.segmentId)}
onUnfold={unfold}
+ onContinue={(target) => openContinue(target.sessionId, target.id)}
/>
) : null}
</div>
@@ -365,10 +369,6 @@ function Flow({ model }: { model: LineageViewModel }) {
setOpenAll((value) => !value);
setUnfolded(new Set());
}, []);
- const actions = useMemo(
- () => ({ toggle, openRow, unfold, selection }),
- [toggle, openRow, unfold, selection],
- );
const closePanel = useCallback(() => setSelection(null), []);
const toggleOutline = useCallback(() => setShowOutline((value) => !value), []);
const onNodeClick = useCallback<NodeMouseHandler<GraphNode>>((_event, node) => {
@@ -421,6 +421,24 @@ function Flow({ model }: { model: LineageViewModel }) {
[centerRow, expanded, layout, model, scheduleFocus],
);
+ /** A "↑ continues …" mark opens the earlier session, revealed and centred. */
+ const openContinue = useCallback(
+ (targetSessionId: string, messageId: string) => {
+ const focus = nodeId(sessionKey(targetSessionId), messageId);
+ selectFromOutline({
+ focusId: focus,
+ expand: outlinePath(model, focus) ?? [sessionKey(targetSessionId)],
+ selection: { type: "node", sessionId: targetSessionId, nodeId: messageId },
+ });
+ },
+ [model, selectFromOutline],
+ );
+
+ const actions = useMemo(
+ () => ({ toggle, openRow, openContinue, unfold, selection }),
+ [toggle, openRow, openContinue, unfold, selection],
+ );
+
let content: ReactNode;
if (error) {
content = <p className="error graph-status">{error}</p>;
diff --git a/packages/template/src/gitLayout.ts b/packages/template/src/gitLayout.ts
index 6c9911f..b9c655c 100644
--- a/packages/template/src/gitLayout.ts
+++ b/packages/template/src/gitLayout.ts
@@ -173,7 +173,9 @@ export function rowHeight(
(row.first ? BRANCH_MAX + 8 : 0) +
row.returns * 44 +
(row.head ? 92 : 0) +
- (message.unsummarized ? 116 : 0);
+ (message.unsummarized ? 116 : 0) +
+ // The "↑ continues <session> · m67" mark sits in the row, next to the title.
+ (message.continues ? 150 + message.continues.sessionTitle.length * 6.4 : 0);
const room = Math.max(120, ROW_WIDTH - fixed);
const titleLines = Math.max(1, Math.ceil((message.title.length * TITLE_CHAR) / room));
const branchLines = row.first
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index 6ec2af5..8c1525f 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -903,6 +903,24 @@ time {
font-size: 11px;
}
+/* "↑ continues <session> · m67": a jump to the earlier session's message. */
+.git-continues {
+ flex: none;
+ max-width: 220px;
+ overflow: hidden;
+ padding: 1px 6px;
+ color: var(--accent);
+ font-size: 11px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ border: 1px solid rgba(122, 162, 247, 0.45);
+ border-radius: 4px;
+}
+
+.git-continues:hover {
+ background: rgba(122, 162, 247, 0.14);
+}
+
.git-row .left-off,
.git-row .unsummarized {
flex: none;
diff --git a/packages/template/test/gitLayout.test.ts b/packages/template/test/gitLayout.test.ts
index 9a828e5..9bc30ba 100644
--- a/packages/template/test/gitLayout.test.ts
+++ b/packages/template/test/gitLayout.test.ts
@@ -51,6 +51,13 @@ describe("segments", () => {
expect(segments.map((segment) => segment.ids)).toEqual([["m1"], ["m2"]]);
expect(segments.every((segment) => segment.parentId === null)).toBe(true);
});
+
+ it("draws a cross-session parent as a root of this session (Story 8.6)", () => {
+ const messages = [message("m1", null), message("m2", "first:h9")];
+ const { segments } = layoutGitGraph(messages);
+ expect(segments.map((segment) => segment.ids)).toEqual([["m1"], ["m2"]]);
+ expect(segments[1]?.parentId).toBeNull();
+ });
});
describe("lanes", () => {