Skip to content

A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.

fix(claude): keep ids and history through compaction and resume

chipfighter7dfe237d1c0e
diff --git a/plugin/src/claude-index.ts b/plugin/src/claude-index.ts
index 8795bd0..4ca58b5 100644
--- a/plugin/src/claude-index.ts
+++ b/plugin/src/claude-index.ts
@@ -9,12 +9,19 @@
// records it continues from, with their uuids, so keys built on them stay the same in the new session.
// Keys: "<record uuid>#<n>" for a pasted image, "tool:<tool_use_id>#<n>" for one in a tool result. A request carries
// tool_use_id but not record uuids: claude-rewrite.ts matches pasted images to records by their content.
+// v0.10 (docs/v0.10/plan.md) — since 2.1.304 a compaction keeps the last messages verbatim (compactMetadata
+// preservedSegment / preservedMessages). Claude Code reads such a transcript by putting them after the summary and
+// dropping what came before the boundary; the file keeps them where they were, so the chain is relinked the same way
+// here, keeping the history before the boundary. Claude Desktop resumes a session as a new one, whose transcript
+// starts at the latest compaction: the history is followed back into the transcript where that compaction happened,
+// so ids stay what they were and the images from before it can be put back. Record lines and fetch labels written
+// while the plugin numbered such a transcript from its own start are translated back.
// Input: the session id (and optionally the Claude config dir). Output: ClaudeIndex (in memory; files are parsed
// incrementally).
-import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
+import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { basename, dirname, join, resolve, sep } from "node:path";
import { baseName, FETCHED_STATE, imageDigest, type ImageKind, type ImageRef } from "./images.ts";
import { addNotes, type Notes } from "./notes.ts";
import { pixelHashOfData, type FetchedCopy, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
@@ -27,6 +34,9 @@ export type ClaudeImage = IndexedImage & { recordUuid: string; toolUseId: string
// The records with pasted images, in conversation order, with the digests of their images: what a request's user
// messages are matched against. compacted: before the latest compaction, so no longer in requests.
export type UploadRecord = { uuid: string; contentIds: string[]; compacted: boolean };
+// v0.10: the session's transcripts (this one, the ones it was resumed or forked from), each with the record it starts
+// at and when it was started, oldest first.
+export type FamilyFile = { sessionId: string; start: string; created: string; forkedFrom: string | null };
export type ClaudeIndex = ThreadIndex & {
images: ClaudeImage[];
byKey: Map<string, ClaudeImage>;
@@ -39,6 +49,8 @@ export type ClaudeIndex = ThreadIndex & {
transcript: string | null;
// v0.5: the latest compaction summary's text: Claude Code starts each request after the compaction with it.
summary: string | null;
+ // v0.10: the sessions this one continues, most recent first (for its selection, selection.ts).
+ previous: Array<{ sessionId: string; at: string | null }>;
};
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -100,18 +112,87 @@ const isBoundary = (record: ClaudeRecord) => record.type === "system" && (record
const blocksOf = (record: ClaudeRecord): Json[] => (Array.isArray(record.message?.content) ? record.message.content : []);
-// The conversation as it stands: from the newest message (not a subagent's sidechain) back to the start.
-export function activeChain(records: ClaudeRecord[]): ClaudeRecord[] {
+// v0.10: the messages a compaction kept, oldest first, as Claude Code 2.1.309 finds them: the list it wrote
+// (preservedMessages), else the walk from the tail up the parent links to the head (preservedSegment).
+function preservedOf(boundary: ClaudeRecord, byUuid: Map<string, ClaudeRecord>): { anchor: string; uuids: string[] } | null {
+ const meta = boundary.compactMetadata;
+ const list = meta?.preservedMessages;
+ if (list && typeof list.anchorUuid === "string" && Array.isArray(list.uuids)) return { anchor: list.anchorUuid, uuids: list.uuids.map(String) };
+ const segment = meta?.preservedSegment;
+ if (!segment || typeof segment.anchorUuid !== "string") return null;
+ const walk: string[] = [];
+ for (let uuid: string | null | undefined = segment.tailUuid; uuid && !walk.includes(uuid); uuid = byUuid.get(uuid)?.parentUuid) {
+ walk.push(uuid);
+ if (uuid === segment.headUuid) return { anchor: segment.anchorUuid, uuids: walk.reverse() };
+ }
+ return null;
+}
+
+// v0.10: the record a boundary's history goes on from, among `records`: the one the first kept message came after,
+// unless Claude Code already put that message after the summary (a resumed transcript); without kept messages, the
+// last message before the compaction (logicalParentUuid).
+function historyStart(records: ClaudeRecord[], boundary: ClaudeRecord, known?: Map<string, ClaudeRecord>): string | null {
+ const byUuid = known ?? new Map(records.filter((record) => typeof record.uuid === "string").map((record) => [record.uuid!, record]));
+ const preserved = preservedOf(boundary, byUuid);
+ if (preserved?.uuids.length) {
+ const parent = byUuid.get(preserved.uuids[0])?.parentUuid ?? null;
+ return parent && parent !== preserved.anchor && byUuid.has(parent) ? parent : null;
+ }
+ const logical = boundary.logicalParentUuid ?? null;
+ return logical && byUuid.has(logical) ? logical : null;
+}
+
+// v0.10: what Claude Code 2.1.309 does when it reads a transcript (its relink after the latest boundary, when that one
+// kept messages): the kept messages follow the summary; records that followed the summary, or a record it drops (one
+// before the boundary that was not kept), follow the last kept message. It then drops those records; here they stay
+// as the history the boundary leads back to, so the images there count as compacted. Parents to use, by uuid.
+function relinked(records: ClaudeRecord[], byUuid: Map<string, ClaudeRecord>): Map<string, string | null> {
+ const parents = new Map<string, string | null>();
+ let last = -1;
+ records.forEach((record, at) => { if (isBoundary(record)) last = at; });
+ if (last < 0) return parents;
+ const boundary = records[last];
+ const preserved = preservedOf(boundary, byUuid);
+ if (!preserved || !preserved.uuids.length || preserved.uuids.some((uuid) => !byUuid.has(uuid))) return parents;
+ const { anchor, uuids } = preserved;
+ const head = uuids[0];
+ const tail = uuids[uuids.length - 1];
+ const kept = new Set(uuids);
+ const position = new Map<string, number>();
+ records.forEach((record, at) => { if (typeof record.uuid === "string") position.set(record.uuid, at); });
+ const dropped = (uuid: string) => { const at = position.get(uuid); return at !== undefined && at < last && !kept.has(uuid); };
+ const history = historyStart(records, boundary, byUuid);
+ let previous = anchor;
+ for (const uuid of uuids) { parents.set(uuid, previous); previous = uuid; }
+ for (const record of records) {
+ if (typeof record.uuid !== "string" || kept.has(record.uuid) || dropped(record.uuid)) continue;
+ if (record.parentUuid === anchor) parents.set(record.uuid, tail);
+ else if ((record.type === "user" || record.type === "assistant") && record.parentUuid && dropped(record.parentUuid)) parents.set(record.uuid, tail);
+ }
+ if (typeof boundary.uuid === "string" && history && history !== head) parents.set(boundary.uuid, history);
+ return parents;
+}
+
+// The conversation as it stands: from the newest message (not a subagent's sidechain) back to the start. v0.10:
+// `links` are where boundaries whose history sits in an earlier transcript lead (withHistory).
+export function activeChain(records: ClaudeRecord[], links: Map<string, string> = new Map()): ClaudeRecord[] {
const byUuid = new Map<string, ClaudeRecord>();
for (const record of records) if (typeof record.uuid === "string") byUuid.set(record.uuid, record);
+ const parents = relinked(records, byUuid);
+ const parentOf = (record: ClaudeRecord): string | null | undefined => {
+ if (parents.has(record.uuid!)) return parents.get(record.uuid!);
+ return record.parentUuid ?? (isBoundary(record) ? links.get(record.uuid!) ?? record.logicalParentUuid : null);
+ };
let leaf: ClaudeRecord | undefined;
for (let i = records.length - 1; i >= 0; i--) if (isMessage(records[i]) && !records[i].isSidechain) { leaf = records[i]; break; }
+ // A record the newer transcript holds wins over the same one read from an earlier transcript.
+ if (leaf) leaf = byUuid.get(leaf.uuid!) ?? leaf;
const chain: ClaudeRecord[] = [];
const seen = new Set<string>();
for (let record = leaf; record && !seen.has(record.uuid!); ) {
seen.add(record.uuid!);
chain.push(record);
- const parent = record.parentUuid ?? (isBoundary(record) ? record.logicalParentUuid : null);
+ const parent = parentOf(record);
record = parent ? byUuid.get(parent) : undefined;
}
chain.reverse();
@@ -128,7 +209,7 @@ export function activeChain(records: ClaudeRecord[]): ClaudeRecord[] {
}
}
const after = new Map<string, ClaudeRecord[]>();
- for (const record of records) {
+ for (const record of byUuid.values()) {
if (record.type !== "user" || record.isSidechain || seen.has(record.uuid!) || !record.parentUuid || !seen.has(record.parentUuid)) continue;
const results = blocksOf(record).filter((block) => block?.type === "tool_result");
if (results.length === 0 || !results.every((block) => calls.has(String(block.tool_use_id)) && !answered.has(String(block.tool_use_id)))) continue;
@@ -168,8 +249,80 @@ export function imageBlocks(content: unknown): BlockImage[] {
return found;
}
-export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], transcript: string | null = null): ClaudeIndex {
- const chain = activeChain(records);
+// The key each image of a user record gets, in order (what buildClaudeIndex and the old numberings share).
+function keysOf(record: ClaudeRecord): Array<BlockImage & { key: string }> {
+ let n = 0;
+ const perTool = new Map<string, number>();
+ return imageBlocks(record.message?.content).map((found) => {
+ if (found.toolUseId === null) return { ...found, key: `${record.uuid}#${n++}` };
+ const m = perTool.get(found.toolUseId) ?? 0;
+ perTool.set(found.toolUseId, m + 1);
+ return { ...found, key: `tool:${found.toolUseId}#${m}` };
+ });
+}
+
+const mimeOf = (block: Json) => (typeof block.source?.media_type === "string" ? block.source.media_type : null);
+
+// v0.10: when record lines and fetch labels were written under another numbering. `family`: the session's transcripts
+// (FamilyFile); a line written at a time belongs to the newest one started by then. One that starts at a compaction
+// was numbered, until `since` (when this version first ran here), from that compaction on.
+export type Eras = { family: FamilyFile[]; since: string | null };
+// chain: activeChain(records, links), when the caller has it already.
+export type ClaudeIndexOptions = { links?: Map<string, string>; eras?: Eras; chain?: ClaudeRecord[] };
+
+// The ids a transcript started at chain position `from` gave its images, as the plugin numbered it then: one by one
+// from there, a copy our fetch tool returned (its label naming an id of this numbering, same content) taking none.
+// Only up to `until` (nothing written later is translated), so it stays the same as the session goes on: kept.
+const numberings = new Map<string, Map<string, string>>();
+function oldNumbering(chain: ClaudeRecord[], from: number, until: string): Map<string, string> {
+ let end = from;
+ while (end < chain.length && !(typeof chain[end].timestamp === "string" && chain[end].timestamp >= until)) end++;
+ const cacheKey = `${chain[from].uuid}${chain[end - 1]?.uuid}${end - from}`;
+ const known = numberings.get(cacheKey);
+ if (known) return known;
+ const keys = new Map<string, string>();
+ const seen = new Set<string>();
+ const content = new Map<string, { contentId: string; pixels: string | null }>();
+ for (let position = from; position < end; position++) {
+ const record = chain[position];
+ if (record.type !== "user") continue;
+ for (const found of keysOf(record)) {
+ if (seen.has(found.key)) continue;
+ seen.add(found.key);
+ const digest = imageDigest(found.block, found.block.source.data, mimeOf(found.block));
+ const pixels = pixelHashOfData(digest, found.block.source.data);
+ const fetched = found.toolUseId && found.before ? FETCHED_LINE.exec(found.before)?.[1] ?? null : null;
+ const original = fetched ? content.get(keys.get(fetched) ?? "") : undefined;
+ if (original && (original.contentId === digest.contentId || (pixels !== null && original.pixels === pixels))) continue;
+ keys.set(`IMG-${String(keys.size + 1).padStart(3, "0")}`, found.key);
+ content.set(found.key, { contentId: digest.contentId, pixels });
+ }
+ }
+ if (numberings.size > 64) numberings.clear();
+ numberings.set(cacheKey, keys);
+ return keys;
+}
+
+// v0.10: for a record written at `timestamp`, the numbering its ids were in: null when they are this index's own.
+function translator(chain: ClaudeRecord[], eras: Eras | undefined): (timestamp: unknown) => Map<string, string> | null {
+ if (!eras || eras.since === null || !chain.length) return () => null;
+ const positions = new Map<string, number>();
+ chain.forEach((record, at) => { if (typeof record.uuid === "string") positions.set(record.uuid, at); });
+ const family = eras.family.filter((file) => positions.has(file.start)).sort((a, b) => a.created.localeCompare(b.created));
+ if (!family.some((file) => file.start !== chain[0].uuid)) return () => null;
+ const used = new Map<string, Map<string, string>>();
+ return (timestamp) => {
+ if (typeof timestamp !== "string" || timestamp >= eras.since!) return null;
+ let start: string | null = null;
+ for (const file of family) if (file.created <= timestamp) start = file.start;
+ if (start === null || start === chain[0].uuid) return null;
+ if (!used.has(start)) used.set(start, oldNumbering(chain, positions.get(start)!, eras.since!));
+ return used.get(start)!;
+ };
+}
+
+export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], transcript: string | null = null, options: ClaudeIndexOptions = {}): ClaudeIndex {
+ const chain = options.chain ?? activeChain(records, options.links);
let lastBoundary = -1;
chain.forEach((record, position) => { if (isBoundary(record)) lastBoundary = position; });
const tools = new Map<string, { name: string; input: Json }>();
@@ -184,15 +337,19 @@ export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], tra
let previous: string[] = [];
// v0.8: what the model noted in record lines at the end of its replies (notes.ts), by image id.
const notes = new Map<string, Notes>();
+ // v0.10: ids written under another numbering, back to this one's (through the image they named).
+ const numberingAt = translator(chain, options.eras);
+ const ownId = (numbering: Map<string, string> | null) => (id: string) => (numbering ? byKey.get(numbering.get(id) ?? "")?.id ?? null : id);
chain.forEach((record, position) => {
const content = record.message?.content;
if (record.type === "assistant" && Array.isArray(content)) {
+ const idOf = ownId(numberingAt(record.timestamp));
for (const block of content as Json[]) {
if (block?.type === "tool_use" && block.id) tools.set(String(block.id), { name: String(block.name ?? ""), input: block.input ?? {} });
const text = textOf(block);
if (!text) continue;
current.push(text);
- addNotes(notes, text, turn || null);
+ addNotes(notes, text, turn || null, idOf);
}
return;
}
@@ -205,30 +362,26 @@ export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], tra
}
const compacted = position < lastBoundary;
const pasted: string[] = [];
- let n = 0;
- const perTool = new Map<string, number>();
- for (const found of imageBlocks(content)) {
- const mime = typeof found.block.source.media_type === "string" ? found.block.source.media_type : null;
+ const idOf = ownId(numberingAt(record.timestamp));
+ for (const found of keysOf(record)) {
+ const { key } = found;
+ const mime = mimeOf(found.block);
const digest = imageDigest(found.block, found.block.source.data, mime);
const tool = found.toolUseId ? tools.get(found.toolUseId) : undefined;
- let key: string;
let kind: ImageKind;
let name: string | null = null;
if (found.toolUseId === null) {
- key = `${record.uuid}#${n++}`;
kind = "upload";
pasted.push(digest.contentId);
} else {
- const m = perTool.get(found.toolUseId) ?? 0;
- perTool.set(found.toolUseId, m + 1);
- key = `tool:${found.toolUseId}#${m}`;
kind = tool?.name === "Read" ? "view" : "tool";
if (tool?.name === "Read" && typeof tool.input.file_path === "string") name = baseName(tool.input.file_path);
}
if (byKey.has(key) || copies.has(key)) continue;
const pixelSha256 = pixelHashOfData(digest, found.block.source.data);
// What our fetch tool brought back is a copy of an image already listed: no id of its own (thread-index.ts).
- const fetchedId = found.toolUseId && found.before ? FETCHED_LINE.exec(found.before)?.[1] ?? null : null;
+ const labelled = found.toolUseId && found.before ? FETCHED_LINE.exec(found.before)?.[1] ?? null : null;
+ const fetchedId = labelled ? idOf(labelled) : null;
const original = fetchedId ? images.find((image) => image.id === fetchedId) : undefined;
if (original && (original.contentId === digest.contentId || (pixelSha256 !== null && original.pixelSha256 === pixelSha256))) {
copies.set(key, { key, of: original.id, turn: turn || null });
@@ -257,7 +410,17 @@ export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], tra
const twin = images.find((other) => other.name && (other.contentId === entry.contentId || (entry.pixelSha256 !== null && other.pixelSha256 === entry.pixelSha256)));
if (twin) entry.name = twin.name;
}
- return { threadId: sessionId, images, byKey, turns: turn, turnNumbers, copies, notes, uploads, chain, title: titleOf(records, chain), replies, transcript, summary };
+ return { threadId: sessionId, images, byKey, turns: turn, turnNumbers, copies, notes, uploads, chain, title: titleOf(records, chain), replies, transcript, summary, previous: previousOf(sessionId, options.eras?.family ?? []) };
+}
+
+// v0.10: the sessions this one continues, most recent first, each with the time this one took over: the one it was
+// forked from (the copied records keep that session's id), then the transcripts started before it.
+function previousOf(sessionId: string, family: FamilyFile[]): Array<{ sessionId: string; at: string | null }> {
+ const own = family.find((file) => file.sessionId === sessionId);
+ if (!own) return [];
+ const earlier = family.filter((file) => file.sessionId !== sessionId && file.created <= own.created).sort((a, b) => b.created.localeCompare(a.created));
+ const ids = [...(own.forkedFrom ? [own.forkedFrom] : []), ...earlier.map((file) => file.sessionId)];
+ return [...new Set(ids)].map((id) => ({ sessionId: id, at: own.created }));
}
// The session's name as Claude Code shows it: the latest custom title, else the start of the first prompt.
@@ -280,11 +443,28 @@ export function claudeStartedAt(index: ClaudeIndex): string | null {
return first ? first.timestamp : null;
}
+// v0.10: an image read from an earlier transcript keeps its data on disk: where to read it back.
+type OnDisk = { file: string; start: number; end: number; part: number; sub: number | null };
+const onDisk = new WeakMap<object, OnDisk>();
+
+function readImageAt({ file, start, end, part, sub }: OnDisk): string | null {
+ try {
+ const buffer = Buffer.alloc(end - start);
+ const fd = openSync(file, "r");
+ try { readSync(fd, buffer, 0, buffer.length, start); } finally { closeSync(fd); }
+ const block = JSON.parse(buffer.toString("utf8")).message?.content?.[part];
+ const inner = sub === null ? block : block?.content?.[sub];
+ return typeof inner?.source?.data === "string" ? inner.source.data : null;
+ } catch { return null; }
+}
+
// The base64 of one indexed image, from the record it sits in.
export function claudeImageData(index: ClaudeIndex, image: ClaudeImage): string | null {
const block = index.chain[image.item]?.message?.content?.[image.part!];
const inner = image.sub === null ? block : block?.content?.[image.sub];
- return typeof inner?.source?.data === "string" ? inner.source.data : null;
+ if (typeof inner?.source?.data === "string" && inner.source.data) return inner.source.data;
+ const where = inner ? onDisk.get(inner) : undefined;
+ return where ? readImageAt(where) : null;
}
// An empty index for a session without a transcript yet.
@@ -292,8 +472,182 @@ export function emptyClaudeIndex(sessionId: string): ClaudeIndex {
return buildClaudeIndex(sessionId, []);
}
-export function loadClaudeIndex(sessionId: string, home = claudeHome()): ClaudeIndex {
+// v0.10: an earlier transcript, read for its history only: every image's digest and pixel fingerprint are taken while
+// its data is at hand, then the data is left on disk (claudeImageData reads it back), so a long session followed back
+// through several transcripts does not hold all their images in memory. Read again only if the file changes.
+const histories = new Map<string, { size: number; mtimeMs: number; records: ClaudeRecord[] }>();
+export function readHistoryTranscript(file: string): ClaudeRecord[] {
+ const stat = statSync(file);
+ const known = histories.get(file);
+ if (known && known.size === stat.size && known.mtimeMs === stat.mtimeMs) return known.records;
+ const buffer = readFileSync(file);
+ const records: ClaudeRecord[] = [];
+ let start = 0;
+ for (let end = buffer.indexOf(0x0a); end >= 0; end = buffer.indexOf(0x0a, start)) {
+ const text = buffer.toString("utf8", start, end).trim();
+ if (text) {
+ try {
+ const record = JSON.parse(text) as ClaudeRecord;
+ for (const found of imageBlocks(record.message?.content)) {
+ const data = found.block.source.data as string;
+ if (!data) continue;
+ pixelHashOfData(imageDigest(found.block, data, mimeOf(found.block)), data);
+ found.block.source = { ...found.block.source, data: "" };
+ onDisk.set(found.block, { file, start, end, part: found.part, sub: found.sub });
+ }
+ records.push(record);
+ } catch { /* damaged line */ }
+ }
+ start = end + 1;
+ }
+ histories.set(file, { size: stat.size, mtimeMs: stat.mtimeMs, records });
+ return records;
+}
+
+// v0.10: the transcript a compaction happened in. The summary Claude Code wrote names it ("…read the full transcript
+// at: <path>"; the last such line, after the model's own text); failing that, a transcript of the same project that
+// holds the boundary with records before it. Only files under <home>/projects count. Remembered once found.
+const TRANSCRIPT_AT = /read the full transcript at: ([^\n]+?\.jsonl)/g;
+const originals = new Map<string, { file: string | null; at: number }>();
+function underProjects(file: string, home: string): boolean {
+ const root = resolve(home, "projects") + sep;
+ const full = resolve(file);
+ return process.platform === "win32" ? full.toLowerCase().startsWith(root.toLowerCase()) : full.startsWith(root);
+}
+const holdsBefore = (records: ClaudeRecord[], uuid: string) => {
+ const first = records.findIndex((record) => typeof record.uuid === "string");
+ const at = records.findIndex((record) => record.uuid === uuid);
+ return at > first && first >= 0;
+};
+function originalOf(file: string, records: ClaudeRecord[], boundary: ClaudeRecord, home: string): string | null {
+ const key = `${file}\0${boundary.uuid}`;
+ const known = originals.get(key);
+ if (known && (known.file || Date.now() - known.at < 10 * 60_000)) return known.file;
+ const usable = (candidate: string) => {
+ if (resolve(candidate) === resolve(file) || !underProjects(candidate, home) || !existsSync(candidate)) return false;
+ try { return holdsBefore(readHistoryTranscript(candidate), boundary.uuid!); } catch { return false; }
+ };
+ const summary = records.find((record) => record.isCompactSummary && record.parentUuid === boundary.uuid);
+ const content = summary?.message?.content;
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map(textOf).filter(Boolean).join("\n") : "";
+ let found = [...text.matchAll(TRANSCRIPT_AT)].map((match) => match[1].trim()).reverse().find(usable) ?? null;
+ // Else the project's transcripts written to since the compaction, holding its boundary.
+ if (!found) {
+ const since = typeof boundary.timestamp === "string" ? Date.parse(boundary.timestamp) : 0;
+ const needle = Buffer.from(`"uuid":"${boundary.uuid}"`);
+ let names: string[] = [];
+ try { names = readdirSync(dirname(file)).filter((name) => name.endsWith(".jsonl")); } catch { /* none */ }
+ for (const name of names) {
+ const other = join(dirname(file), name);
+ try {
+ if (statSync(other).mtimeMs < since || !readFileSync(other).includes(needle)) continue;
+ } catch { continue; }
+ if (usable(other)) { found = other; break; }
+ }
+ }
+ originals.set(key, { file: found, at: Date.now() });
+ return found;
+}
+
+// v0.10: a transcript's records with the history its first compaction hides prepended: the records of the transcript
+// that compaction happened in, up to its boundary, followed back as far as they go. `links` say where each such
+// boundary leads.
+export type WithHistory = { records: ClaudeRecord[]; links: Map<string, string> };
+// The history read from an earlier transcript, per boundary, while that file is unchanged: only its conversation
+// records before the boundary (the rest of it is in the newer transcript, or not part of this session), so the earlier
+// file itself need not stay parsed.
+const prefixes = new Map<string, { stamp: string; part: { prefix: ClaudeRecord[]; links: Map<string, string> } | null }>();
+const stampOf = (file: string) => { const stat = statSync(file); return `${stat.size}:${stat.mtimeMs}`; };
+export function withHistory(file: string, records: ClaudeRecord[], home = claudeHome(), depth = 0): WithHistory {
+ const first = records.find((record) => typeof record.uuid === "string");
+ if (!first || !isBoundary(first) || depth > 16) return { records, links: new Map() };
+ const original = originalOf(file, records, first, home);
+ if (!original) return { records, links: new Map() };
+ const key = `${original}${first.uuid}`;
+ let stamp: string;
+ try { stamp = stampOf(original); } catch { return { records, links: new Map() }; }
+ let cached = prefixes.get(key);
+ if (!cached || cached.stamp !== stamp) {
+ const older = withHistory(original, readHistoryTranscript(original), home, depth + 1);
+ const at = older.records.findIndex((record) => record.uuid === first.uuid);
+ const start = at < 0 ? null : historyStart(older.records, older.records[at]);
+ const prefix = at < 0 || !start ? null : older.records.slice(0, at).filter((record) => typeof record.uuid === "string");
+ cached = { stamp, part: prefix && start ? { prefix, links: new Map([...older.links, [first.uuid!, start]]) } : null };
+ prefixes.set(key, cached);
+ histories.delete(original);
+ }
+ if (!cached.part) return { records, links: new Map() };
+ return { records: [...cached.part.prefix, ...records], links: cached.part.links };
+}
+
+// v0.10: the transcripts of one session in its project folder: those whose first conversation record is the session's
+// start or one of its compactions, each with when it was started (its first stamped record, before the copied ones)
+// and, for a fork, the session it came from. The head of each file is read once.
+const heads = new Map<string, { start: string; created: string; sessionOf: string | null } | null>();
+const listings = new Map<string, { at: number; names: string[] }>();
+function headOf(file: string): { start: string; created: string; sessionOf: string | null } | null {
+ if (heads.has(file)) return heads.get(file)!;
+ let head: { start: string; created: string; sessionOf: string | null } | null = null;
+ try {
+ const fd = openSync(file, "r");
+ const buffer = Buffer.alloc(1 << 20);
+ let read = 0;
+ try { read = readSync(fd, buffer, 0, buffer.length, 0); } finally { closeSync(fd); }
+ let created: string | null = null;
+ const lines = buffer.toString("utf8", 0, read).split("\n");
+ for (const line of lines.slice(0, -1)) {
+ let record: ClaudeRecord;
+ try { record = JSON.parse(line); } catch { continue; }
+ if (typeof record.uuid !== "string") { if (!created && typeof record.timestamp === "string") created = record.timestamp; continue; }
+ const stamp = created ?? (typeof record.timestamp === "string" ? record.timestamp : null);
+ if (stamp) head = { start: record.uuid, created: stamp, sessionOf: typeof record.sessionId === "string" ? record.sessionId : null };
+ break;
+ }
+ } catch { /* unreadable */ }
+ // Not cached while the file has no conversation record yet.
+ if (head) heads.set(file, head);
+ return head;
+}
+export function familyOf(file: string, starts: Set<string>): FamilyFile[] {
+ const folder = dirname(file);
+ let listing = listings.get(folder);
+ // Listed again every 5 s, and at once when this transcript is new to the listing (a session just resumed).
+ if (!listing || Date.now() - listing.at > 5000 || !listing.names.includes(basename(file))) {
+ let names: string[] = [];
+ try { names = readdirSync(folder).filter((name) => name.endsWith(".jsonl")); } catch { /* none */ }
+ listing = { at: Date.now(), names };
+ listings.set(folder, listing);
+ }
+ const family: FamilyFile[] = [];
+ for (const name of listing.names) {
+ const head = headOf(join(folder, name));
+ if (!head || !starts.has(head.start)) continue;
+ const sessionId = basename(name, ".jsonl");
+ family.push({ sessionId, start: head.start, created: head.created, forkedFrom: head.sessionOf && head.sessionOf !== sessionId ? head.sessionOf : null });
+ }
+ return family.sort((a, b) => a.created.localeCompare(b.created));
+}
+
+// v0.10: `since` is when this version first ran here (selection.ts, stableIdsSince); before it, transcripts resumed
+// after a compaction were numbered from their own start, and what was written then is translated back.
+// The engine reads the index several times per request (whether to rewrite, the rewrite, the sizes): the last one is
+// kept while the transcripts, the project folder and `since` are as they were. Callers only read it.
+const loaded = new WeakMap<ClaudeRecord[], { key: string; index: ClaudeIndex }>();
+export function loadClaudeIndex(sessionId: string, home = claudeHome(), since: string | null = null): ClaudeIndex {
const file = transcriptOf(sessionId, home);
if (!file) return emptyClaudeIndex(sessionId);
- return buildClaudeIndex(sessionId, readTranscript(file), file);
+ const own = readTranscript(file);
+ const { records, links } = withHistory(file, own, home);
+ const key = [own.length, records.length, since, listings.get(dirname(file))?.names.length ?? -1].join("");
+ const known = loaded.get(own);
+ if (known && known.key === key) return known.index;
+ const index = indexFor(sessionId, file, records, links, since);
+ loaded.set(own, { key, index });
+ return index;
+}
+
+function indexFor(sessionId: string, file: string, records: ClaudeRecord[], links: Map<string, string>, since: string | null): ClaudeIndex {
+ const chain = activeChain(records, links);
+ const starts = new Set([chain[0]?.uuid, ...chain.filter(isBoundary).map((record) => record.uuid)].filter((uuid): uuid is string => typeof uuid === "string"));
+ return buildClaudeIndex(sessionId, records, file, { links, chain, eras: { family: familyOf(file, starts), since } });
}
diff --git a/plugin/src/notes.ts b/plugin/src/notes.ts
index 51a39a5..0284e5d 100644
--- a/plugin/src/notes.ts
+++ b/plugin/src/notes.ts
@@ -8,19 +8,29 @@
// rating: the user's words the model noted, with the turn it noted them in.
export type Rating = { turn: number | null; text: string };
-// line: the feature line, written once (the first one stands); ratings: oldest first.
+// line: the feature line, written once (the first one stands, unless corrected); ratings: oldest first.
export type Notes = { line: string | null; ratings: Rating[] };
const RECORD = /^ {0,3}\[\/\/\]:[ \t]*#[ \t]*\(cam[ \t]+(IMG-\d{3,})[ \t]+([^()\n]+?)[ \t]*\)[ \t]*$/gm;
const RATING = /^(?:评价|rated)[ \t]*[::][ \t]*/i;
+// v0.10: a feature line the model found wrong (e.g. the user pointed it out), written again in full.
+const CORRECTION = /^(?:更正|corrected)[ \t]*[::][ \t]*/i;
-export function addNotes(notes: Map<string, Notes>, text: string, turn: number | null): void {
- for (const [, id, body] of text.matchAll(RECORD)) {
+// v0.10: `idOf` turns the id a line names into the image's id now (claude-index.ts: lines written while a resumed
+// transcript was numbered from its own start); null drops the line.
+export function addNotes(notes: Map<string, Notes>, text: string, turn: number | null, idOf: (id: string) => string | null = (id) => id): void {
+ for (const [, named, body] of text.matchAll(RECORD)) {
+ const id = idOf(named);
+ if (!id) continue;
const entry = notes.get(id) ?? { line: null, ratings: [] };
const rating = RATING.exec(body);
+ const correction = CORRECTION.exec(body);
if (rating) {
const said = body.slice(rating[0].length).trim();
if (said) entry.ratings.push({ turn, text: said });
+ } else if (correction) {
+ const line = body.slice(correction[0].length).trim();
+ if (line) entry.line = line;
} else if (entry.line === null) entry.line = body.trim();
notes.set(id, entry);
}
diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.ts
index 58c0c0a..61342bb 100644
--- a/plugin/src/panel-state.ts
+++ b/plugin/src/panel-state.ts
@@ -19,7 +19,7 @@ import type { ImageSource } from "./images.ts";
import { sceneOf, withoutRecords } from "./notes.ts";
import { childrenDirOf, claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "./paths.ts";
import { readRequestStats, type RequestStats } from "./request-stats.ts";
-import { claudeSelection, effectiveSelection, writeSelection, type Mark, type Selection } from "./selection.ts";
+import { claudeSelection, effectiveSelection, stableIdsSince, writeSelection, type Mark, type Selection } from "./selection.ts";
import { buildIndex, imageData, readThreadHistory, sessionMetaOf, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
import { threadTitle } from "./thread-names.ts";
import { pngThumbnail } from "./thumbnail.ts";
@@ -357,8 +357,8 @@ export type ClaudePanelOptions = { dataRoot?: string; home?: string };
function loadClaude(sessionId: string, options: ClaudePanelOptions) {
const root = options.dataRoot ?? dataDir();
- const index = loadClaudeIndex(sessionId, options.home ?? claudeHome());
- const selection = claudeSelection(sessionId, claudeSelectionDirOf(root), claudeStartedAt(index));
+ const index = loadClaudeIndex(sessionId, options.home ?? claudeHome(), stableIdsSince(claudeSelectionDirOf(root)));
+ const selection = claudeSelection(sessionId, claudeSelectionDirOf(root), claudeStartedAt(index), index.previous);
const stats = readRequestStats(sessionId, claudeRequestStatsDirOf(root));
return { root, index, selection, stats };
}
@@ -379,7 +379,7 @@ export function applyClaudeSelection(sessionId: string, change: SelectionChange,
}
export function claudeImageFor(sessionId: string, id: string, maxSide: number, options: ClaudePanelOptions = {}): { id: string; dataUrl: string | null } {
- const index = loadClaudeIndex(sessionId, options.home ?? claudeHome());
+ const index = loadClaudeIndex(sessionId, options.home ?? claudeHome(), stableIdsSince(claudeSelectionDirOf(options.dataRoot ?? dataDir())));
const image = index.images.find((candidate) => candidate.id === id);
if (!image) throw new Error(`${id} is not an image of this session`);
const data = claudeImageData(index, image);
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index fabdedc..b32a01a 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -38,7 +38,7 @@ import { migrateDataOnce } from "./migrate-data.ts";
import { applySelection, claudeImageFor, imageFor, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel-state.ts";
import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./paths.ts";
import { fetchedLabel, fetchWords } from "./rewrite.ts";
-import { claudeSelection, effectiveSelection, ensureAutoDefault } from "./selection.ts";
+import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, stableIdsSince } from "./selection.ts";
import { connectDirectly, useEngine, usesEngine } from "./setup.ts";
import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache, sideChatOrigin } from "./thread-index.ts";
import { threadTitle } from "./thread-names.ts";
@@ -257,8 +257,9 @@ export function callClaudeTool(name: string, args: Json, options: ClaudePanelOpt
if (name === "cam_view_image") {
const words = fetchWords(lang);
const ids: string[] = Array.isArray(args.ids) ? args.ids.map(String) : typeof args.id === "string" ? [args.id] : [];
- const index = loadClaudeIndex(sessionId, options.home);
- if (!claudeSelection(sessionId, claudeSelectionDirOf(options.dataRoot ?? dataDir()), claudeStartedAt(index)).auto) {
+ const selectionDir = claudeSelectionDirOf(options.dataRoot ?? dataDir());
+ const index = loadClaudeIndex(sessionId, options.home, stableIdsSince(selectionDir));
+ if (!claudeSelection(sessionId, selectionDir, claudeStartedAt(index), index.previous).auto) {
log({ event: "fetch", host: "claude", sessionId, ids, refused: "automatic selection is off" });
return { content: [{ type: "text", text: words.off }], isError: true };
}
@@ -285,6 +286,8 @@ function main(): void {
// v0.6: the panel may read a selection before the engine has started: the same start for both (selection.ts).
ensureAutoDefault(selectionDirOf());
ensureAutoDefault(claudeSelectionDirOf());
+ // v0.10: ids of Claude sessions resumed after a compaction stay as they were from now on (claude-index.ts).
+ ensureStableIds(claudeSelectionDirOf());
const send = (message: Json) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
let engineState = "";
const supervise = async () => {
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 757f64d..74d3962 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -44,7 +44,7 @@ import { recordRequest } from "./request-stats.ts";
import { readRoute, registerRoute, routeBaseUrl, routingPort, validateBaseUrl, type Platform } from "./routes.ts";
import { rewriteItems, type Described } from "./rewrite.ts";
import { connectDirectly, pluginGone, usesEngine } from "./setup.ts";
-import { claudeSelection, effectiveSelection, ensureAutoDefault, selectionDir, sideChatSelection } from "./selection.ts";
+import { claudeSelection, effectiveSelection, ensureAutoDefault, ensureStableIds, selectionDir, sideChatSelection, stableIdsSince } from "./selection.ts";
import { loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, writesNotes, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
@@ -378,9 +378,9 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre
export function claudeNeedsRewrite(sessionId: string | null, dir = claudeSelectionDirOf(), home = claudeHome()): boolean {
if (!sessionId) return false;
let index: ClaudeIndex | null = null;
- try { index = loadClaudeIndex(sessionId, home); } catch { /* the selection still decides */ }
+ try { index = loadClaudeIndex(sessionId, home, stableIdsSince(dir)); } catch { /* the selection still decides */ }
try {
- const selection = claudeSelection(sessionId, dir, index ? claudeStartedAt(index) : null);
+ const selection = claudeSelection(sessionId, dir, index ? claudeStartedAt(index) : null, index?.previous ?? []);
if (Object.keys(selection.unchecked).length > 0 || selection.autoSince) return true;
} catch { /* the transcript still decides */ }
return !!index?.images.length;
@@ -420,8 +420,8 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
if (!Array.isArray(json.messages)) return asIs({ skipped: "no messages array" });
if (hasUnsafeInteger(text)) return asIs({ skipped: "integer beyond 2^53 would change when re-serialized" });
let index: ClaudeIndex;
- try { index = loadClaudeIndex(sessionId, home); } catch (error) { return asIs({ skipped: `thread index: ${String(error)}` }); }
- const selection = claudeSelection(sessionId, dir, claudeStartedAt(index));
+ try { index = loadClaudeIndex(sessionId, home, stableIdsSince(dir)); } catch (error) { return asIs({ skipped: `thread index: ${String(error)}` }); }
+ const selection = claudeSelection(sessionId, dir, claudeStartedAt(index), index.previous);
const current = index.turns;
const copies = new Map([...index.copies.values()].filter((copy) => copy.turn === null || copy.turn < current).map((copy) => [copy.key, copy.of]));
let leaveOut = new Set(Object.keys(selection.unchecked));
@@ -564,6 +564,8 @@ async function main(): Promise<void> {
// v0.6: tasks and sessions started from now on have automatic selection on by default (selection.ts).
ensureAutoDefault(selectionDirOf());
ensureAutoDefault(claudeSelectionDirOf());
+ // v0.10: from now on Claude sessions resumed after a compaction keep their ids (claude-index.ts).
+ ensureStableIds(claudeSelectionDirOf());
const portIndex = process.argv.indexOf("--port");
const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : DEFAULT_PORT);
const providerPort = routingPort(port);
@@ -786,7 +788,7 @@ async function main(): Promise<void> {
details = describeBody(path, json);
// Measured on the body as Codex sent it, before any rewrite: the panel's "everything sent" baseline.
if (/\/responses$/.test(path) && Array.isArray(json.input)) imageSizes = imageSizesOf(json.input);
- if (claudeSession && Array.isArray(json.messages)) imageSizes = claudeImageSizes(json.messages, loadClaudeIndex(claudeSession));
+ if (claudeSession && Array.isArray(json.messages)) imageSizes = claudeImageSizes(json.messages, loadClaudeIndex(claudeSession, claudeHome(), stableIdsSince(claudeSelectionDirOf())));
if (dumpDir && (/\/responses$/.test(path) || path === "/v1/messages")) {
mkdirSync(dumpDir, { recursive: true });
const headers = Object.fromEntries(Object.entries(req.headers).filter(([name]) => /^(x-codex|session_id|conversation_id|openai-beta|content-|anthropic-(beta|version)|x-claude-code-|user-agent)/.test(name)));
diff --git a/plugin/src/selection.ts b/plugin/src/selection.ts
index 469727b..e899cc8 100644
--- a/plugin/src/selection.ts
+++ b/plugin/src/selection.ts
@@ -54,28 +54,36 @@ export function writeSelection(selection: Selection, dir = selectionDir): void {
// v0.6: written by the engine and the plugin service when they start; the first one wins.
const AUTO_DEFAULT = "auto-default.json";
+// v0.10: when this version first ran here. Before it, a Claude session resumed after a compaction was numbered from
+// its transcript's own start; claude-index.ts translates what was written then (docs/v0.10/plan.md).
+const STABLE_IDS = "stable-ids.json";
const sinceOf = new Map<string, string>();
-export function ensureAutoDefault(dir = selectionDir, now = new Date()): void {
+function ensureSince(name: string, dir: string, now: Date): void {
mkdirSync(dir, { recursive: true });
try {
- writeFileSync(join(dir, AUTO_DEFAULT), JSON.stringify({ since: now.toISOString() }, null, 2), { flag: "wx" });
+ writeFileSync(join(dir, name), JSON.stringify({ since: now.toISOString() }, null, 2), { flag: "wx" });
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
}
-
-// null until this version has run here: then nothing is on by default.
-export function autoDefaultSince(dir = selectionDir): string | null {
- const known = sinceOf.get(dir);
+function sinceIn(name: string, dir: string): string | null {
+ const key = join(dir, name);
+ const known = sinceOf.get(key);
if (known) return known;
try {
- const since = JSON.parse(readFileSync(join(dir, AUTO_DEFAULT), "utf8")).since;
- if (typeof since === "string") sinceOf.set(dir, since);
+ const since = JSON.parse(readFileSync(key, "utf8")).since;
+ if (typeof since === "string") sinceOf.set(key, since);
return typeof since === "string" ? since : null;
} catch {
return null;
}
}
+export const ensureAutoDefault = (dir = selectionDir, now = new Date()): void => ensureSince(AUTO_DEFAULT, dir, now);
+// null until this version has run here: then nothing is on by default.
+export const autoDefaultSince = (dir = selectionDir): string | null => sinceIn(AUTO_DEFAULT, dir);
+export const ensureStableIds = (dir = selectionDir, now = new Date()): void => ensureSince(STABLE_IDS, dir, now);
+// null until this version has run here: then nothing is translated.
+export const stableIdsSince = (dir = selectionDir): string | null => sinceIn(STABLE_IDS, dir);
// A thread with no switch of its own that started at or after `since` has automatic selection on, from its start;
// one with no history yet (startedAt null) is just starting.
@@ -87,8 +95,29 @@ export function withAutoDefault(selection: Selection, startedAt: string | null,
}
// v0.6: a Claude Code session's selection with the default applied, given when it started (claudeStartedAt).
-export function claudeSelection(sessionId: string, dir: string, startedAt: string | null): Selection {
- return withAutoDefault(readSelection(sessionId, dir), startedAt, autoDefaultSince(dir));
+// v0.10: `previous`, the sessions it continues (ClaudeIndex.previous), for one without a selection of its own.
+export function claudeSelection(sessionId: string, dir: string, startedAt: string | null, previous: Array<{ sessionId: string; at: string | null }> = []): Selection {
+ return withAutoDefault(claudeOwnSelection(sessionId, dir, previous), startedAt, autoDefaultSince(dir));
+}
+
+// v0.10: Claude Desktop resumes a session as a new one, and a fork is one too: without a selection of its own, it
+// starts with that of the latest session it continues that has one — the marks made by the time it took over, and
+// the switch if it was last switched by then — kept as its own file from then on, as a Codex fork (ownSelection).
+function claudeOwnSelection(sessionId: string, dir: string, previous: Array<{ sessionId: string; at: string | null }>): Selection {
+ if (!previous.length || existsSync(fileFor(sessionId, dir))) return readSelection(sessionId, dir);
+ for (const { sessionId: other, at } of previous) {
+ if (!THREAD_ID.test(other) || other === sessionId || !existsSync(fileFor(other, dir))) continue;
+ const from = readSelection(other, dir);
+ const before = (entries: Record<string, Mark> = {}) => Object.fromEntries(Object.entries(entries).filter(([, entry]) => !at || entry.at <= at));
+ const unchecked = before(from.unchecked);
+ const pinned = before(from.pinned);
+ const switched = typeof from.auto === "boolean" && (!at || !from.autoAt || from.autoAt <= at);
+ const switches = switched ? { auto: from.auto, ...(from.autoAt ? { autoAt: from.autoAt } : {}), ...(from.autoSince ? { autoSince: from.autoSince } : {}) } : {};
+ const inherited: Selection = { threadId: sessionId, unchecked, ...switches, ...(Object.keys(pinned).length ? { pinned } : {}), inheritedFrom: other };
+ writeSelection(inherited, dir);
+ return inherited;
+ }
+ return readSelection(sessionId, dir);
}
// The thread's own selection; a fork without one takes the images its parent had unchecked by the time of the fork
diff --git a/spike/src/claude-compaction.test.ts b/spike/src/claude-compaction.test.ts
new file mode 100644
index 0000000..7d42919
--- /dev/null
+++ b/spike/src/claude-compaction.test.ts
@@ -0,0 +1,208 @@
+// Purpose: v0.10 — Claude Code compactions that keep the last messages (2.1.304+), and sessions Claude Desktop
+// resumed after one (claude-index.ts): the chain relinked the way Claude Code reads it, the history followed back into
+// the transcript the compaction happened in, ids kept, images from there read back from disk, record lines and fetch
+// labels written under a renumbered id translated, and a resumed session's selection (selection.ts).
+// Input: synthetic transcripts (claude-fixtures.ts) in a temporary Claude home; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { buildClaudeIndex, claudeImageData, loadClaudeIndex, readHistoryTranscript } from "../../plugin/src/claude-index.ts";
+import { claudeSelection, writeSelection } from "../../plugin/src/selection.ts";
+import { image, pngA, pngB, pngC, text, transcript } from "./claude-fixtures.ts";
+import { png } from "./testkit.ts";
+
+type Json = Record<string, any>;
+const pngD = png(8, 8, () => [30, 200, 60]).toString("base64");
+const ids = { O: "aaaaaaaa-0000-4000-8000-000000000001", R: "aaaaaaaa-0000-4000-8000-000000000002", R2: "aaaaaaaa-0000-4000-8000-000000000003", F: "aaaaaaaa-0000-4000-8000-000000000004" };
+const at = (minute: number) => `2026-10-01T10:${String(minute).padStart(2, "0")}:00.000Z`;
+const record = (line: string) => `[//]: # (cam ${line})`;
+
+function home(): { home: string; project: string; write: (id: string, records: Json[]) => string } {
+ const root = mkdtempSync(join(tmpdir(), "cam-compaction-"));
+ const project = join(root, "projects", "P");
+ mkdirSync(project, { recursive: true });
+ const write = (id: string, records: Json[]) => {
+ const file = join(project, `${id}.jsonl`);
+ writeFileSync(file, `${records.map((entry) => JSON.stringify(entry)).join("\n")}\n`);
+ return file;
+ };
+ return { home: root, project, write };
+}
+
+// What Claude Code writes when it resumes a session after a compaction: a new session whose transcript starts at the
+// boundary, the summary, the kept messages after it, then what followed, relinked as its reader does.
+function resumed(records: Json[], boundary: string, anchor: string, kept: string[], sessionId: string, created: string): Json[] {
+ const start = records.findIndex((entry) => entry.uuid === boundary);
+ const byUuid = new Map(records.map((entry) => [entry.uuid, entry]));
+ const before = new Set(records.slice(0, start).map((entry) => entry.uuid));
+ const keep = new Set(kept);
+ const tail = kept[kept.length - 1];
+ const out: Json[] = [{ type: "custom-title", customTitle: "resumed", sessionId }, { type: "queue-operation", operation: "enqueue", timestamp: created, sessionId }];
+ out.push({ ...records[start], sessionId }, { ...byUuid.get(anchor), sessionId });
+ let previous = anchor;
+ for (const uuid of kept) { out.push({ ...byUuid.get(uuid), parentUuid: previous, sessionId }); previous = uuid; }
+ for (const entry of records.slice(start + 1)) {
+ if (entry.uuid === anchor || keep.has(entry.uuid)) continue;
+ const moved = entry.parentUuid === anchor || (entry.parentUuid && before.has(entry.parentUuid) && !keep.has(entry.parentUuid));
+ out.push({ ...entry, parentUuid: moved ? tail : entry.parentUuid, sessionId });
+ }
+ return out;
+}
+
+const summaryNaming = (file: string) => `Summary of the work.\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: ${file}\nContinue the conversation from where it left off.`;
+
+test("a compaction that kept messages, where it happened: they follow the summary, and the images before it are compacted", () => {
+ for (const after of ["tail", "summary"] as const) {
+ for (const list of [false, true]) {
+ const t = transcript();
+ const p1 = t.prompt([image(pngA), text("one")]);
+ t.assistant(text("A"));
+ const p2 = t.prompt([image(pngB), text("two")]);
+ const kept = t.assistant(text("B"));
+ const { boundary, anchor } = t.compact([kept], after, "summary", {}, list);
+ const p3 = t.prompt([image(pngC), text("three")]);
+ t.assistant(text("C"));
+ const index = buildClaudeIndex("s", t.records);
+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.key, entry.compacted]), [["IMG-001", `${p1}#0`, true], ["IMG-002", `${p2}#0`, true], ["IMG-003", `${p3}#0`, false]], `${after} ${list}`);
+ assert.equal(index.summary, "summary");
+ const order = index.chain.map((entry) => entry.uuid);
+ // boundary, summary, the kept message, what came after: as Claude Code sends it.
+ assert.deepEqual([order.indexOf(boundary) + 1, order.indexOf(anchor) + 1, order.indexOf(kept) + 1], [order.indexOf(anchor), order.indexOf(kept), order.indexOf(p3)], `${after} ${list}`);
+ assert.equal(index.turns, 3);
+ }
+ }
+});
+
+test("a compaction that kept nothing, or a broken kept list, reads as before", () => {
+ const t = transcript();
+ t.prompt([image(pngA), text("one")]);
+ const kept = t.assistant(text("A"));
+ t.compact(["00000000-0000-4000-8000-0000000009ff", kept]);
+ const p2 = t.prompt([image(pngB), text("two")]);
+ const index = buildClaudeIndex("s", t.records);
+ // The kept list names a record that is not there: Claude Code then relinks nothing; the chain still crosses the
+ // boundary through its logical parent.
+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.compacted]), [["IMG-001", true], ["IMG-002", false]]);
+ assert.equal(index.images[1].key, `${p2}#0`);
+});
+
+// The original session: two images, a compaction keeping the last reply, a third image; the plugin noted each.
+function original(write: (id: string, records: Json[]) => string, project: string, named = true) {
+ const t = transcript();
+ const file = join(project, `${ids.O}.jsonl`);
+ const p1 = t.prompt([image(pngA), text("one")], { timestamp: at(0) });
+ t.assistant(text(`${record("IMG-001 书房|红色方块")}\n\nA`), { timestamp: at(1) });
+ const p2 = t.prompt([image(pngB), text("two")], { timestamp: at(2) });
+ const kept = t.assistant(text(`${record("IMG-002 书房|蓝色方块")}\n\nB`), { timestamp: at(3) });
+ const compaction = t.compact([kept], "summary", named ? summaryNaming(file) : "Summary of the work.", { timestamp: at(5) });
+ const p3 = t.prompt([image(pngC), text("three")], { timestamp: at(6) });
+ const a3 = t.assistant(text(`${record("IMG-003 书房|白色长方形")}\n\nC`), { timestamp: at(7) });
+ const records = t.records.map((entry) => ({ ...entry, sessionId: ids.O }));
+ write(ids.O, records);
+ return { records, p1, p2, p3, a3, kept, ...compaction, file };
+}
+
+test("a session resumed after a compaction keeps its ids: the history is read from the transcript the summary names", () => {
+ const { home: root, project, write } = home();
+ const o = original(write, project);
+ const fresh = transcript(1000);
+ fresh.from(o.a3);
+ // Written while the plugin numbered the resumed transcript from its own start: its IMG-002 is the new image, IMG-001
+ // the one after the compaction; a fetch then named IMG-001 too.
+ const p4 = fresh.prompt([image(pngD), text("four")], { timestamp: at(31) });
+ fresh.assistant({ type: "tool_use", id: "toolu_fetch", name: "mcp__plugin_codex-attachment-manager_codex_attachment_manager__cam_view_image", input: { ids: ["IMG-001"] } }, { timestamp: at(32) });
+ fresh.toolResult("toolu_fetch", [text("[图片 IMG-001 取回的原图|未命名|用户上传|第 3 轮]"), image(pngC)], { timestamp: at(32) });
+ fresh.assistant(text(`${record("IMG-002 客厅|绿色方块")}\n${record("IMG-001 评价:太白")}\n\nD`), { timestamp: at(33) });
+ // Written once this version ran (since 10:40): its own ids.
+ fresh.prompt("nice", { timestamp: at(45) });
+ fresh.assistant(text(`${record("IMG-004 评价:好看")}\n\nE`), { timestamp: at(46) });
+ write(ids.R, [...resumed(o.records, o.boundary, o.anchor, [o.kept], ids.R, at(30)), ...fresh.records.map((entry) => ({ ...entry, sessionId: ids.R }))]);
+
+ const index = loadClaudeIndex(ids.R, root, at(40));
+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.key, entry.compacted]), [
+ ["IMG-001", `${o.p1}#0`, true], ["IMG-002", `${o.p2}#0`, true], ["IMG-003", `${o.p3}#0`, false], ["IMG-004", `${p4}#0`, false],
+ ]);
+ // The fetched copy is known as one (its label translated), not a new image.
+ assert.deepEqual([...index.copies.values()].map((copy) => copy.of), ["IMG-003"]);
+ assert.deepEqual(Object.fromEntries([...index.notes].map(([id, notes]) => [id, [notes.line, notes.ratings.map((rating) => rating.text)]])), {
+ "IMG-001": ["书房|红色方块", []], "IMG-002": ["书房|蓝色方块", []], "IMG-003": ["书房|白色长方形", ["太白"]], "IMG-004": ["客厅|绿色方块", ["好看"]],
+ });
+ // Images from the earlier transcript are read back from disk; held without their data.
+ assert.equal(claudeImageData(index, index.images[0]), pngA);
+ assert.equal(claudeImageData(index, index.images[1]), pngB);
+ assert.equal(readHistoryTranscript(o.file).find((entry) => entry.uuid === o.p1)!.message.content[0].source.data, "");
+ assert.equal(index.summary?.startsWith("Summary of the work."), true);
+ assert.deepEqual(index.previous, [{ sessionId: ids.O, at: at(30) }]);
+ // Before this version ran nothing is translated: the lines name the ids they named.
+ assert.equal(loadClaudeIndex(ids.R, root, null).notes.get("IMG-001")?.ratings.map((rating) => rating.text).join(), "太白");
+});
+
+test("a resumed session whose summary names no transcript: the project's transcript holding the boundary is used", () => {
+ const { home: root, project, write } = home();
+ const o = original(write, project, false);
+ write(ids.R, resumed(o.records, o.boundary, o.anchor, [o.kept], ids.R, at(30)));
+ const index = loadClaudeIndex(ids.R, root, at(40));
+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.compacted]), [["IMG-001", true], ["IMG-002", true], ["IMG-003", false]]);
+ assert.equal(index.notes.get("IMG-003")?.line, "书房|白色长方形");
+});
+
+test("without the transcript the compaction happened in, the resumed one is read on its own", () => {
+ const { home: root, project, write } = home();
+ const o = original(write, project);
+ write(ids.R, resumed(o.records, o.boundary, o.anchor, [o.kept], ids.R, at(30)));
+ writeFileSync(o.file, "");
+ const index = loadClaudeIndex(ids.R, root, at(40));
+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.key]), [["IMG-001", `${o.p3}#0`]]);
+});
+
+test("resumed twice across two compactions, and forked: ids and history carry through", () => {
+ const { home: root, project, write } = home();
+ const o = original(write, project);
+ // In the resumed session: a fourth image, then a second compaction keeping its reply, then a fifth image.
+ const r = transcript(1000);
+ r.from(o.a3);
+ const p4 = r.prompt([image(pngD), text("four")], { timestamp: at(41) });
+ const kept2 = r.assistant(text(`${record("IMG-004 客厅|绿色方块")}\n\nD`), { timestamp: at(42) });
+ const second = r.compact([kept2], "tail", summaryNaming(join(project, `${ids.R}.jsonl`)), { timestamp: at(43) });
+ const p5 = r.prompt([image(pngA), text("five")], { timestamp: at(44) });
+ r.assistant(text(`${record("IMG-005 门口|红色方块又一张")}\n\nE`), { timestamp: at(45) });
+ const resumedOnce = [...resumed(o.records, o.boundary, o.anchor, [o.kept], ids.R, at(30)), ...r.records.map((entry) => ({ ...entry, sessionId: ids.R }))];
+ write(ids.R, resumedOnce);
+ const live = loadClaudeIndex(ids.R, root, at(20));
+ assert.deepEqual(live.images.map((entry) => [entry.id, entry.compacted]), [["IMG-001", true], ["IMG-002", true], ["IMG-003", true], ["IMG-004", true], ["IMG-005", false]]);
+ // Resumed again after the second compaction.
+ const twice = resumed(resumedOnce, second.boundary, second.anchor, [kept2], ids.R2, at(50));
+ write(ids.R2, twice);
+ const index = loadClaudeIndex(ids.R2, root, at(20));
+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.key, entry.compacted]), [
+ ["IMG-001", `${o.p1}#0`, true], ["IMG-002", `${o.p2}#0`, true], ["IMG-003", `${o.p3}#0`, true], ["IMG-004", `${p4}#0`, true], ["IMG-005", `${p5}#0`, false],
+ ]);
+ assert.equal(index.notes.get("IMG-004")?.line, "客厅|绿色方块");
+ assert.deepEqual(index.previous.map((entry) => entry.sessionId), [ids.R, ids.O]);
+ assert.equal(claudeImageData(index, index.images[3]), pngD);
+ // A fork copies the records with the session's own id in them, from the same compaction.
+ write(ids.F, [{ type: "queue-operation", operation: "enqueue", timestamp: at(55), sessionId: ids.F }, ...twice.filter((entry) => entry.uuid).map((entry) => ({ ...entry, sessionId: ids.R2 }))]);
+ const fork = loadClaudeIndex(ids.F, root, at(20));
+ assert.deepEqual(fork.images.map((entry) => entry.key), index.images.map((entry) => entry.key));
+ assert.equal(fork.previous[0].sessionId, ids.R2);
+});
+
+test("a resumed or forked Claude session starts with the selection of the session it continues", () => {
+ const dir = mkdtempSync(join(tmpdir(), "cam-claude-selection-"));
+ writeSelection({ threadId: ids.O, unchecked: { "k#0": { id: "IMG-001", at: at(10) }, "k#1": { id: "IMG-002", at: at(35) } }, auto: true, autoAt: at(5), autoSince: at(5), pinned: { "k#2": { id: "IMG-003", at: at(12) } } }, dir);
+ const inherited = claudeSelection(ids.R, dir, at(0), [{ sessionId: ids.R2, at: at(30) }, { sessionId: ids.O, at: at(30) }]);
+ assert.deepEqual(Object.keys(inherited.unchecked), ["k#0"]);
+ assert.deepEqual(Object.keys(inherited.pinned ?? {}), ["k#2"]);
+ assert.equal(inherited.auto, true);
+ assert.equal(inherited.inheritedFrom, ids.O);
+ // Kept as its own from then on.
+ assert.equal(existsSync(join(dir, `${ids.R}.json`)), true);
+ assert.equal(JSON.parse(readFileSync(join(dir, `${ids.R}.json`), "utf8")).inheritedFrom, ids.O);
+ // Its own selection wins; nothing to inherit leaves the default.
+ writeSelection({ threadId: ids.F, unchecked: {} , auto: false }, dir);
+ assert.equal(claudeSelection(ids.F, dir, at(0), [{ sessionId: ids.O, at: at(30) }]).auto, false);
+ assert.deepEqual(claudeSelection(ids.R2, dir, at(0), []).unchecked, {});
+});
diff --git a/spike/src/claude-fixtures.ts b/spike/src/claude-fixtures.ts
index 6b54b0c..6a18e24 100644
--- a/spike/src/claude-fixtures.ts
+++ b/spike/src/claude-fixtures.ts
@@ -13,13 +13,14 @@ export const pngC = png(16, 8, () => [255, 255, 255]).toString("base64");
export const image = (data: string, extra: Json = {}) => ({ type: "image", source: { type: "base64", media_type: "image/png", data }, ...extra });
export const text = (value: string, extra: Json = {}) => ({ type: "text", text: value, ...extra });
-// A transcript builder: each record links to the one before unless told otherwise.
-export function transcript() {
+// A transcript builder: each record links to the one before unless told otherwise. v0.10: `base` offsets its uuids,
+// for a second builder whose records join the first one (a resumed session).
+export function transcript(base = 0) {
const records: Json[] = [];
let last: string | null = null;
let n = 0;
const add = (record: Json, parent: string | null | undefined = last) => {
- const uuid = record.uuid ?? `00000000-0000-4000-8000-${String(++n).padStart(12, "0")}`;
+ const uuid = record.uuid ?? `00000000-0000-4000-8000-${String(++n + base).padStart(12, "0")}`;
const full = { parentUuid: parent ?? null, isSidechain: false, sessionId: "s", ...record, uuid };
records.push(full);
if (!full.isSidechain) last = uuid;
@@ -33,6 +34,20 @@ export function transcript() {
attachment: () => add({ type: "attachment", attachment: { type: "x" } }),
boundary: () => add({ type: "system", subtype: "compact_boundary", compactMetadata: {}, logicalParentUuid: last }, null),
summary: (content = "summary") => add({ type: "user", isCompactSummary: true, message: { role: "user", content } }),
+ // v0.10: a compaction that keeps the last messages (Claude Code 2.1.304+), as written where it happened: the
+ // boundary (no parent; its logical parent is the last message), the summary after it, the kept messages left
+ // where they were. The next records hang off the last kept one ("tail", as when the records of the /compact
+ // command were written first) or off the summary. `list`: preservedMessages instead of preservedSegment.
+ compact: (kept: string[], after: "tail" | "summary" = "summary", content = "summary", extra: Json = {}, list = false) => {
+ const tail = kept[kept.length - 1];
+ const anchor = `00000000-0000-4000-8000-${String(++n + base + 500).padStart(12, "0")}`;
+ const metadata = list ? { preservedMessages: { anchorUuid: anchor, uuids: kept, allUuids: kept } } : { preservedSegment: { headUuid: kept[0], anchorUuid: anchor, tailUuid: tail } };
+ const boundary = add({ type: "system", subtype: "compact_boundary", compactMetadata: { trigger: "manual", ...metadata }, logicalParentUuid: tail, ...extra }, null);
+ add({ type: "user", isCompactSummary: true, message: { role: "user", content }, uuid: anchor, ...extra }, boundary);
+ if (after === "tail") last = tail;
+ return { boundary, anchor };
+ },
+ from: (uuid: string) => { last = uuid; },
get last() { return last; },
};
}
diff --git a/spike/src/notes.test.ts b/spike/src/notes.test.ts
index be97bc5..4573e13 100644
--- a/spike/src/notes.test.ts
+++ b/spike/src/notes.test.ts
@@ -228,3 +228,20 @@ test("the panel's data: each image's scene and noted words, and per turn what wa
const claude = panelStateOf("s", index, new Set(), null, null, true, [], true, claudeTurnTexts(index.chain));
assert.deepEqual([claude.images[0].scene, claude.images[0].search], ["white room", "white room | wide shot"]);
});
+
+test("v0.10: a correction replaces the feature line; a line under another numbering is translated or dropped", () => {
+ const notes = new Map<string, Notes>();
+ addNotes(notes, "[//]: # (cam IMG-005 角色|正面近景,右眉有疤)\n\nok", 2);
+ addNotes(notes, "[//]: # (cam IMG-005 角色|正面近景,另一种写法)", 3);
+ assert.equal(notes.get("IMG-005")?.line, "角色|正面近景,右眉有疤");
+ addNotes(notes, "[//]: # (cam IMG-005 更正:角色|正面近景,左眉有疤)\n[//]: # (cam IMG-006 corrected: street | wide shot)", 4);
+ assert.equal(notes.get("IMG-005")?.line, "角色|正面近景,左眉有疤");
+ assert.equal(notes.get("IMG-006")?.line, "street | wide shot");
+ // An empty correction changes nothing.
+ addNotes(notes, "[//]: # (cam IMG-005 更正:)", 5);
+ assert.equal(notes.get("IMG-005")?.line, "角色|正面近景,左眉有疤");
+ const mapped = new Map<string, Notes>();
+ addNotes(mapped, "[//]: # (cam IMG-001 书房|窗边)\n[//]: # (cam IMG-002 评价:太暗)\n[//]: # (cam IMG-003 门口|白天)", 7, (id) => ({ "IMG-001": "IMG-095", "IMG-002": "IMG-096" } as Record<string, string>)[id] ?? null);
+ assert.deepEqual([...mapped.keys()], ["IMG-095", "IMG-096"]);
+ assert.deepEqual(mapped.get("IMG-096")?.ratings, [{ turn: 7, text: "太暗" }]);
+});