Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
fix(record): record a forked session from where it was forked, not as a copy
Eren44f1f6bda5ce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 018c5d9..38a3620 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- A forked session (`claude --resume <id> --fork-session`, the map's **Fork** button) is no longer recorded as a copy of the session it came from: the messages it copied are left out, and its first own message hangs from the last message it shares with the original.- Sessions the map search opened no longer stay open after a reload: they close again when the search is cleared or stops matching them, unless you clicked into one.### Changeddiff --git a/docs/guide/map.md b/docs/guide/map.mdindex ebc2ec1..653ed08 100644--- a/docs/guide/map.md+++ b/docs/guide/map.md@@ -54,7 +54,8 @@ Click a row to open its details on the right:- previous and next message buttons, and two small buttons that copy a command for thewhole session: **Resume** (`cd '<project>' && claude --resume <session-id>`) reopens thechat where it left off, and **Fork** adds `--fork-session`, so the chat goes on as a new- session with the same history and the original stays as it was.+ session with the same history and the original stays as it was. On the map the fork starts from+ the message it was forked at, like a session that continues another.## "Your turn"diff --git a/packages/cli/skills/record/SKILL.md b/packages/cli/skills/record/SKILL.mdindex 6527679..464b5d7 100644--- a/packages/cli/skills/record/SKILL.md+++ b/packages/cli/skills/record/SKILL.md@@ -68,6 +68,8 @@ Every message grows from an earlier one; a thread that starts something new is abranches with the message each ends at (`last`), and its last messages. Read `leftOff`first, then the branches; the usual target is a branch's `last`. The target must be amessage of an earlier session of this project.+- `forkedFrom` (a forked session): the first message's parent is that value; no candidates+ are listed, and the CLI sets it when you send none.- Unsure: use the previous message. A wrong "continue" hides a branch; a wrong branch breaksthe chain.- `links`: up to 5 earlier messages it builds on besides the parent.diff --git a/packages/cli/src/agents/claude/fork.ts b/packages/cli/src/agents/claude/fork.tsnew file mode 100644index 0000000..d16f9c2--- /dev/null+++ b/packages/cli/src/agents/claude/fork.ts@@ -0,0 +1,128 @@+import { createReadStream } from "node:fs";+import { readdir, stat } from "node:fs/promises";+import { basename, dirname, join } from "node:path";+import { createInterface } from "node:readline";+import type { ChatTurn, ForkOrigin } from "../types.js";++/**+ * Forked sessions (`claude --resume <id> --fork-session`). Claude Code copies the+ * original's lines into the new transcript with their uuids and times, changes+ * only the session id and marks nothing. A copied message read as the fork's own+ * would be recorded a second time under a new id, so the fork's messages start+ * after the part it shares with the session it came from.+ */+/** A copy of a fork of a fork can name the session the copy came from; this bounds the walk. */+const MAX_DEPTH = 8;++const USER_LINE = /"type":"user"/;+const LINE_UUID = /"uuid":"([^"]+)"/;++/**+ * Per process: a transcript only grows at its end, so its first message never+ * changes. Reading every transcript of the folder only as far as its first+ * message is the one scan a fork check costs (a fraction of a second for hundreds).+ */+const firstUuids = new Map<string, string | null>();++/** The uuid of the first user line that is a message, read only as far as that line. */+async function firstMessageUuid(+ file: string,+ isMessage: (line: Record<string, unknown>) => boolean,+): Promise<string | null> {+ const known = firstUuids.get(file);+ if (known !== undefined) return known;+ const input = createReadStream(file, "utf8");+ const lines = createInterface({ input, crlfDelay: Infinity });+ let found: string | null = null;+ try {+ for await (const raw of lines) {+ if (!USER_LINE.test(raw)) continue;+ const line = parseLine(raw);+ if (line === null || !isMessage(line)) continue;+ found = LINE_UUID.exec(raw)?.[1] ?? null;+ break;+ }+ } finally {+ lines.close();+ input.destroy();+ }+ // Only a found uuid is final; an empty file may still get its first message.+ if (found !== null) firstUuids.set(file, found);+ return found;+}++function parseLine(raw: string): Record<string, unknown> | null {+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++/** When the file was created; null where the file system does not say or the file is gone. */+async function bornAt(file: string): Promise<number | null> {+ const birth = (await stat(file).catch(() => null))?.birthtimeMs ?? 0;+ return birth > 0 ? birth : null;+}++/** How many leading messages two transcripts share, by uuid. */+function sharedPrefix(a: readonly ChatTurn[], b: readonly ChatTurn[]): number {+ let count = 0;+ while (count < a.length && count < b.length) {+ const uuid = a[count]?.uuid;+ if (uuid === undefined || uuid !== b[count]?.uuid) break;+ count++;+ }+ return count;+}++/**+ * Where a transcript was forked from, or null for a session of its own. The+ * origin is the earlier-born transcript in the same folder that shares the+ * longest run of first messages; when that one is itself a fork and the shared+ * run lies inside its own copies, the walk goes on to the session that wrote them.+ */+export async function forkOrigin(+ file: string,+ turns: readonly ChatTurn[],+ readTurns: (file: string) => Promise<ChatTurn[]>,+ isMessage: (line: Record<string, unknown>) => boolean,+ depth = 0,+): Promise<ForkOrigin | null> {+ const first = turns[0];+ if (first?.uuid === undefined || depth > MAX_DEPTH) return null;+ const born = await bornAt(file);++ const dir = dirname(file);+ const names = (await readdir(dir).catch(() => [] as string[])).filter((name) =>+ name.endsWith(".jsonl"),+ );+ let best: { file: string; shared: number; born: number } | null = null;+ for (const name of names) {+ const other = join(dir, name);+ if (other === file) continue;+ // A transcript that cannot be read (removed meanwhile) is no origin.+ if ((await firstMessageUuid(other, isMessage).catch(() => null)) !== first.uuid) continue;+ const otherBorn = (await bornAt(other)) ?? 0;+ // A fork is always born after the session it copies.+ if (born !== null && otherBorn >= born) continue;+ const shared = sharedPrefix(turns, await readTurns(other).catch(() => []));+ // The longest shared run is the direct origin; on a tie, the later-born one.+ if (+ shared > 0 &&+ (best === null || shared > best.shared || (shared === best.shared && otherBorn > best.born))+ )+ best = { file: other, shared, born: otherBorn };+ }+ if (best === null) return null;+ const last = turns[best.shared - 1];+ if (last?.uuid === undefined) return null;+ const copy = { uuid: last.uuid, at: last.at, text: last.text };+ const parentTurns = await readTurns(best.file).catch(() => null);+ const deeper = parentTurns+ ? await forkOrigin(best.file, parentTurns, readTurns, isMessage, depth + 1)+ : null;+ if (deeper && best.shared <= deeper.copied)+ return { sessionId: deeper.sessionId, copied: best.shared, last: copy };+ return { sessionId: basename(best.file, ".jsonl"), copied: best.shared, last: copy };+}diff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.tsindex d92e7d8..e610540 100644--- a/packages/cli/src/agents/claude/index.ts+++ b/packages/cli/src/agents/claude/index.ts@@ -23,6 +23,7 @@ import {excerpt,findTranscript,readConversation,+ readForkOrigin,readLastTurn,readsHandoff,} from "./transcripts.js";@@ -48,6 +49,7 @@ export const claude: AgentAdapter = {collectTranscripts,collectTranscriptIds,readConversation,+ readForkOrigin,readsHandoff,readLastTurn,countUserLines,diff --git a/packages/cli/src/agents/claude/transcripts.ts b/packages/cli/src/agents/claude/transcripts.tsindex 1bb2d86..06a90e1 100644--- a/packages/cli/src/agents/claude/transcripts.ts+++ b/packages/cli/src/agents/claude/transcripts.ts@@ -1,9 +1,10 @@import { createReadStream } from "node:fs";-import { access, type FileHandle, open, readdir } from "node:fs/promises";+import { access, type FileHandle, open, readdir, stat } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";import { createInterface } from "node:readline";-import type { ChatTurn, LastTurn, ToolUse, UserMessage } from "../types.js";+import type { ChatTurn, ForkOrigin, LastTurn, ToolUse, UserMessage } from "../types.js";+import { forkOrigin } from "./fork.js";/*** Reading Claude Code's transcripts. A session is one JSONL file under@@ -222,9 +223,44 @@ function addAssistant(turn: ChatTurn, line: Record<string, unknown>): void {/*** Reads the conversation from a transcript: each message the user typed, in* order, with the agent's written replies and a count of its tool calls up to- * the next message. Unparseable lines are skipped.+ * the next message. Unparseable lines are skipped. A fork's copied messages+ * belong to the session it came from and are left out (see `fork.ts`).*/export async function readConversation(file: string): Promise<ChatTurn[]> {+ // Read fresh: callers own the turns they get; only other transcripts are cached.+ const turns = await readAllTurns(file);+ const origin = await forkOrigin(file, turns, readTranscriptTurns, isMessageLine);+ if (origin === null) return turns;+ return turns.slice(origin.copied).map((turn, index) => {+ const { resumed: _, ...rest } = turn;+ // The fork's first own message starts its session; a later one keeps its flag.+ return { ...(index === 0 ? rest : turn), id: `m${index + 1}` };+ });+}++/** Where a forked transcript came from; null for a session of its own. */+export async function readForkOrigin(file: string): Promise<ForkOrigin | null> {+ return forkOrigin(file, await readAllTurns(file), readTranscriptTurns, isMessageLine);+}++function isMessageLine(line: Record<string, unknown>): boolean {+ return messageText(line) !== null && typeof line.timestamp === "string";+}++/** Other transcripts' messages, copies included, while a fork is matched; per process, by size. */+const turnCache = new Map<string, { size: number; turns: Promise<ChatTurn[]> }>();++async function readTranscriptTurns(file: string): Promise<ChatTurn[]> {+ const size = (await stat(file)).size;+ const cached = turnCache.get(file);+ if (cached && cached.size === size) return cached.turns;+ const turns = readAllTurns(file);+ turnCache.set(file, { size, turns });+ turns.catch(() => turnCache.delete(file));+ return turns;+}++async function readAllTurns(file: string): Promise<ChatTurn[]> {const turns: ChatTurn[] = [];/** Uuids already read, to notice a chain that starts again (a resumed process). */const seen = new Set<string>();diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.tsindex 033c53b..a81afb6 100644--- a/packages/cli/src/agents/types.ts+++ b/packages/cli/src/agents/types.ts@@ -51,6 +51,20 @@ export interface ChatTurn extends UserMessage {tools: ToolUse;}+/**+ * Where a forked session came from (`claude --resume <id> --fork-session`): the+ * fork's transcript starts with copies of the original's messages, which belong+ * to the original, so its own messages begin after them.+ */+export interface ForkOrigin {+ /** The session the shared messages were first written in. */+ sessionId: string;+ /** How many of the fork's first messages are copies. */+ copied: number;+ /** The last copied message as the origin has it; the fork's first own message grows from it. */+ last: { uuid: string; at: string; text: string };+}+/*** How a transcript ends (Story 11.1): the deterministic "your turn" signal.* The agent wrote after the newest user message, or that message is still@@ -128,6 +142,8 @@ export interface AgentAdapter {collectTranscriptIds(env: NodeJS.ProcessEnv): Promise<Set<string>>;/** Each message the user typed, in order, with the agent's replies and tool counts. */readConversation(file: string): Promise<ChatTurn[]>;+ /** Where a forked session came from; null for a session of its own. */+ readForkOrigin(file: string): Promise<ForkOrigin | null>;/** Whether the transcript shows the agent reading a handoff file (Story 8.6). */readsHandoff(file: string): Promise<boolean>;/**diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex 071d579..fdb7626 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -8,6 +8,7 @@ import {hashesToLabels,isRecorded,labelsToHashes,+ messageHash,messageOrder,readSessionMessages,type SessionMessage,@@ -112,7 +113,11 @@ export async function sessionWrite(const messages = await readSessionMessages(root, redacted.sessionId, io.env);// The side model runs on this same transcript, so a message id it does not// know is made up; its node is dropped instead of stored beside the real one.- const input = nameMessages(redacted, messages, io, opts.by === "side");+ const input = withForkParent(+ nameMessages(redacted, messages, io, opts.by === "side"),+ messages,+ await forkParent(redacted.sessionId, io.env),+ );if (count > 0) io.warn(`redacted ${count} secret-looking value(s)`);// Cross-session parents (8.6) are checked against the other records before the@@ -218,6 +223,41 @@ function nameMessages(};}+/**+ * A forked session's first own message grows from the last message it copied,+ * as `<origin session>:<id>`; null for a session of its own.+ */+export async function forkParent(+ sessionId: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<string | null> {+ const agent = defaultAgent();+ const file = await agent.findTranscript(sessionId, env);+ if (!file) return null;+ const origin = await agent.readForkOrigin(file).catch(() => null);+ return origin ? `${origin.sessionId}:${messageHash(origin.sessionId, origin.last)}` : null;+}++/**+ * Hangs a fork's first message from where it was forked, when the input sends+ * that message without a parent: a fork is a fact of the transcript, not a guess,+ * so no recorder has to find it among the candidates.+ */+export function withForkParent(+ input: SessionInput,+ messages: readonly SessionMessage[] | null,+ parent: string | null,+): SessionInput {+ const first = messages?.[0];+ if (parent === null || first === undefined || !input.nodes) return input;+ return {+ ...input,+ nodes: input.nodes.map((node) =>+ node.id === first.hash && typeof node.parent !== "string" ? { ...node, parent } : node,+ ),+ };+}+/*** 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@@ -362,8 +402,12 @@ export async function sessionShow(// the expensive other-session scan only runs while that message is unrecorded// (`--full` asks for it every time, for debugging and backfill).const first = messages[0];+ const unrecorded = first !== undefined && (opts.full === true || !isRecorded(recorded, first));+ // A fork names its own parent; the candidates are for guessing one.+ const forkedFrom = unrecorded ? await forkParent(sessionId, io.env) : null;+ if (forkedFrom !== null) view.forkedFrom = forkedFrom;const candidates =- first !== undefined && (opts.full === true || !isRecorded(recorded, first))+ unrecorded && first !== undefined && forkedFrom === null? await parentCandidates(root, sessionId, first, io): null;if (candidates) view.candidates = candidates;diff --git a/packages/cli/test/fork.test.ts b/packages/cli/test/fork.test.tsnew file mode 100644index 0000000..c5a2159--- /dev/null+++ b/packages/cli/test/fork.test.ts@@ -0,0 +1,113 @@+import { writeFile } from "node:fs/promises";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { readConversation, readForkOrigin } from "../src/agents/claude/transcripts.js";+import { withForkParent } from "../src/commands/session.js";+import { messageHash } from "../src/messages.js";+import { tempDir } from "./helpers.js";++/** Messages sent long before the files are written, as a fork's copies are. */+const at = (m: number) => `2026-01-01T10:${String(m).padStart(2, "0")}:00.000Z`;++function user(uuid: string, text: string, m: number, parentUuid: string | null) {+ return JSON.stringify({+ type: "user",+ uuid,+ parentUuid,+ timestamp: at(m),+ message: { role: "user", content: text },+ });+}++function reply(uuid: string, text: string, m: number, parentUuid: string) {+ return JSON.stringify({+ type: "assistant",+ uuid,+ parentUuid,+ timestamp: at(m),+ message: { role: "assistant", content: [{ type: "text", text }] },+ });+}++/** Writes one transcript; a pause first so each file is born after the one before. */+async function transcript(dir: string, id: string, lines: string[]): Promise<string> {+ await new Promise((done) => setTimeout(done, 20));+ const file = join(dir, `${id}.jsonl`);+ await writeFile(file, `${lines.join("\n")}\n`);+ return file;+}++const ONE = [user("u1", "bir", 0, null), reply("a1", "bir", 1, "u1")];+const TWO = [user("u2", "iki", 2, "a1"), reply("a2", "iki", 3, "u2")];+const THREE = [user("u3", "üç", 4, "a2"), reply("a3", "üç", 5, "u3")];++describe("forked transcripts", () => {+ it("leaves a session of its own as it is", async () => {+ const dir = await tempDir();+ // Another session, with a broken user line before its first message.+ await transcript(dir, "other", ['{"type":"user",', user("x1", "başka", 0, null)]);+ const file = await transcript(dir, "orig", [...ONE, ...TWO]);+ expect((await readConversation(file)).map((t) => t.text)).toEqual(["bir", "iki"]);+ expect(await readForkOrigin(file)).toBeNull();+ });++ it("reads only a fork's own messages and names where it was forked", async () => {+ const dir = await tempDir();+ await transcript(dir, "orig", [...ONE, ...TWO]);+ const fork = await transcript(dir, "fork", [...ONE, ...TWO, ...THREE]);+ const turns = await readConversation(fork);+ expect(turns.map((t) => [t.id, t.text])).toEqual([["m1", "üç"]]);+ expect(turns[0]?.resumed).toBeUndefined();+ expect(await readForkOrigin(fork)).toEqual({+ sessionId: "orig",+ copied: 2,+ last: { uuid: "u2", at: at(2), text: "iki" },+ });+ });++ it("names the session that wrote the copies when a fork is forked again", async () => {+ const dir = await tempDir();+ await transcript(dir, "orig", [...ONE]);+ // Forked and not written in yet, then forked again.+ await transcript(dir, "fork1", [...ONE]);+ const fork2 = await transcript(dir, "fork2", [...ONE, ...TWO]);+ expect((await readForkOrigin(fork2))?.sessionId).toBe("orig");+ });++ it("hangs from the fork's own session when the copies end in its messages", async () => {+ const dir = await tempDir();+ await transcript(dir, "orig", [...ONE]);+ await transcript(dir, "fork1", [...ONE, ...TWO]);+ const fork2 = await transcript(dir, "fork2", [...ONE, ...TWO, ...THREE]);+ expect(await readForkOrigin(fork2)).toMatchObject({ sessionId: "fork1", copied: 2 });+ });+});++describe("withForkParent", () => {+ const first = {+ id: "m1",+ label: "m1",+ hash: "h000000000001",+ at: at(4),+ text: "üç",+ replies: [],+ };+ const messages = [{ ...first, tools: { commands: 0, files: [], other: 0 } }];+ const parent = `orig:${messageHash("orig", { uuid: "u2", at: at(2), text: "iki" })}`;+ const node = { id: "h000000000001", kind: "message" as const, title: "üç" };++ it("gives the fork's first message its origin as parent", () => {+ const input = withForkParent({ sessionId: "fork", nodes: [node] }, messages, parent);+ expect(input.nodes?.[0]?.parent).toBe(parent);+ });++ it("keeps a parent the recorder chose and leaves a session of its own alone", () => {+ const chosen = { ...node, parent: "other:h000000000002" };+ expect(+ withForkParent({ sessionId: "fork", nodes: [chosen] }, messages, parent).nodes?.[0]?.parent,+ ).toBe("other:h000000000002");+ expect(+ withForkParent({ sessionId: "s", nodes: [node] }, messages, null).nodes?.[0]?.parent,+ ).toBeUndefined();+ });+});diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.tsindex 22b207d..99c776c 100644--- a/packages/cli/test/thought.test.ts+++ b/packages/cli/test/thought.test.ts@@ -98,8 +98,9 @@ describe("the thought behind a commit (Story 9.4)", () => {await writeFile(file,[- { type: "user", uuid: "u1", timestamp: T0, message: { content: "first" } },- { type: "user", uuid: "u2", timestamp: NEWEST_AT, message: { content: text } },+ // Uuids are unique per session; only a fork shares them (see fork.test.ts).+ { type: "user", uuid: `${id}-u1`, timestamp: T0, message: { content: "first" } },+ { type: "user", uuid: `${id}-u2`, timestamp: NEWEST_AT, message: { content: text } },].map((line) => JSON.stringify(line)).join("\n") + "\n",@@ -108,7 +109,7 @@ describe("the thought behind a commit (Story 9.4)", () => {};const thoughtOf = (text = "second", id = "s1"): string =>- messageHash(id, { uuid: "u2", at: NEWEST_AT, text });+ messageHash(id, { uuid: `${id}-u2`, at: NEWEST_AT, text });const writeHead = async (at = T0, path: string | undefined = transcript): Promise<void> => {await writeFile(