notesoup 0.54.0 → 0.54.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/plugins/claude/src/helper.d.ts +2 -1
- package/dist/plugins/claude/src/helper.js +19 -23
- package/dist/plugins/claude/src/history.d.ts +3 -14
- package/dist/plugins/claude/src/history.js +2 -298
- package/dist/plugins/claude/src/text.d.ts +0 -1
- package/dist/plugins/claude/src/text.js +0 -1
- package/dist/plugins/codex/src/history.d.ts +3 -8
- package/dist/plugins/codex/src/history.js +2 -238
- package/dist/plugins/codex/src/mcp.js +7 -7
- package/dist/plugins/codex/src/transcript.d.ts +3 -39
- package/dist/plugins/codex/src/transcript.js +2 -313
- package/dist/plugins/dsh/history.d.ts +3 -0
- package/dist/plugins/dsh/history.js +15 -0
- package/dist/plugins/dsh/tools.js +4 -5
- package/dist/plugins/pi/history-tools.d.ts +1 -1
- package/dist/plugins/pi/history-tools.js +9 -5
- package/dist/plugins/pi/history.d.ts +2 -3
- package/dist/plugins/pi/history.js +4 -147
- package/dist/src/boot/render.js +2 -4
- package/dist/src/boot/text.d.ts +3 -1
- package/dist/src/boot/text.js +11 -5
- package/dist/src/history/claude.d.ts +16 -0
- package/dist/src/history/claude.js +336 -0
- package/dist/src/history/codex-transcript.d.ts +39 -0
- package/dist/src/history/codex-transcript.js +315 -0
- package/dist/src/history/codex.d.ts +8 -0
- package/dist/src/history/codex.js +238 -0
- package/dist/src/history/corpus.d.ts +35 -0
- package/dist/src/history/corpus.js +54 -0
- package/dist/src/history/history.d.ts +4 -8
- package/dist/src/history/history.js +3 -11
- package/dist/src/history/local.d.ts +17 -0
- package/dist/src/history/local.js +101 -0
- package/dist/src/history/pi.d.ts +36 -0
- package/dist/src/history/pi.js +202 -0
- package/dist/src/history/query.d.ts +15 -5
- package/dist/src/history/query.js +42 -13
- package/dist/src/index.d.ts +4 -2
- package/dist/src/index.js +4 -3
- package/dist/src/tools/history.d.ts +7 -19
- package/dist/src/tools/history.js +80 -93
- package/dist/test/boot.integration.test.js +1 -2
- package/dist/test/claude-history.test.js +47 -34
- package/dist/test/claude-mod.test.js +7 -7
- package/dist/test/codex-history.test.js +4 -10
- package/dist/test/codex-plugin.test.js +32 -11
- package/dist/test/dependencies.test.js +3 -3
- package/dist/test/dsh.test.js +26 -4
- package/dist/test/helpers/extension.d.ts +0 -1
- package/dist/test/helpers/history-corpus.d.ts +7 -0
- package/dist/test/helpers/history-corpus.js +26 -0
- package/dist/test/history-corpus.test.d.ts +1 -0
- package/dist/test/history-corpus.test.js +307 -0
- package/dist/test/history.integration.test.js +40 -48
- package/dist/test/host-neutral.test.js +3 -18
- package/dist/test/model-facing-text.test.js +2 -0
- package/dist/test/notes.integration.test.js +1 -1
- package/dist/test/notes.test.js +1 -1
- package/docs/architecture.md +7 -5
- package/docs/claude-code-mod.md +7 -5
- package/docs/codex.md +3 -3
- package/docs/dsh.md +2 -2
- package/docs/history-sessions.md +52 -0
- package/docs/notes-library.md +1 -1
- package/docs/skills.md +1 -1
- package/docs/tool-results.md +8 -6
- package/package.json +3 -4
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +1992 -1231
- package/plugins/claude/skills/memory/SKILL.md +5 -3
- package/plugins/claude/src/helper.ts +19 -23
- package/plugins/claude/src/history.ts +3 -257
- package/plugins/claude/src/text.ts +0 -1
- package/plugins/codex/dist/codex/notesoup.js +1364 -813
- package/plugins/codex/src/history.ts +3 -193
- package/plugins/codex/src/mcp.ts +7 -7
- package/plugins/codex/src/transcript.ts +3 -275
- package/plugins/dsh/history.ts +17 -0
- package/plugins/dsh/tools.ts +4 -5
- package/plugins/paseo/client/markdown.tsx +19 -39
- package/plugins/paseo/client/notes-op-card.tsx +1 -1
- package/plugins/pi/history-tools.ts +11 -5
- package/plugins/pi/history.ts +8 -157
- package/skills/memory/SKILL.md +5 -3
- package/src/boot/render.ts +2 -5
- package/src/boot/text.ts +11 -5
- package/src/history/claude.ts +286 -0
- package/src/history/codex-transcript.ts +276 -0
- package/src/history/codex.ts +193 -0
- package/src/history/corpus.ts +69 -0
- package/src/history/history.ts +5 -12
- package/src/history/local.ts +93 -0
- package/src/history/pi.ts +199 -0
- package/src/history/query.ts +45 -15
- package/src/index.ts +5 -3
- package/src/tools/history.ts +71 -101
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
/** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
|
|
5
|
+
|
|
6
|
+
type Row = Record<string, unknown>;
|
|
7
|
+
type WindowPosition = { ordinal: number } | { unknownAncestor: string };
|
|
8
|
+
type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; position?: WindowPosition };
|
|
9
|
+
type Node = { first: Version; latest: Version; items: DecodedHistoryItem[] };
|
|
10
|
+
export type ClaudeHistorySource = { sessionId: string; transcriptPath: string; headUuid?: string };
|
|
11
|
+
/** Claude graph evidence stays in the adapter; shared queries only see addressed windows. */
|
|
12
|
+
export type ClaudeHistoryProjection = HistoryProjection & { missingAncestors: string[]; currentWindowOrdinal: number | undefined };
|
|
13
|
+
const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
|
|
14
|
+
const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
|
|
15
|
+
function object(value: unknown): value is Row { return typeof value === "object" && value !== null && !Array.isArray(value); }
|
|
16
|
+
function requiredString(value: unknown, field: string): string {
|
|
17
|
+
if (typeof value !== "string" || value.length === 0) throw new Error(`invalid Claude transcript ${field}`);
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function parent(row: Row): string | undefined {
|
|
21
|
+
if (row.parentUuid === null) return undefined;
|
|
22
|
+
return requiredString(row.parentUuid, "parentUuid");
|
|
23
|
+
}
|
|
24
|
+
function boundary(row: Row): boolean { return row.type === "system" && row.subtype === "compact_boundary"; }
|
|
25
|
+
|
|
26
|
+
/** A trailing incomplete write is not a committed line. Valid unterminated JSON is still readable. */
|
|
27
|
+
function rowsOf(text: string): Row[] {
|
|
28
|
+
const lines = text.split("\n"), rows: Row[] = [];
|
|
29
|
+
for (let index = 0; index < lines.length; index++) {
|
|
30
|
+
const line = lines[index]!;
|
|
31
|
+
if (line.trim() === "") continue;
|
|
32
|
+
let value: unknown;
|
|
33
|
+
try { value = JSON.parse(line); }
|
|
34
|
+
catch {
|
|
35
|
+
if (index === lines.length - 1 && !text.endsWith("\n")) break;
|
|
36
|
+
throw new Error(`malformed Claude transcript JSON at line ${index + 1}`);
|
|
37
|
+
}
|
|
38
|
+
if (!object(value) || typeof value.type !== "string") throw new Error(`invalid Claude transcript record at line ${index + 1}`);
|
|
39
|
+
rows.push(value);
|
|
40
|
+
}
|
|
41
|
+
return rows;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Only recorded visible text; never stringify unknown blocks or attachment internals (thinking included). */
|
|
45
|
+
function blocksOf(value: unknown): Row[] {
|
|
46
|
+
if (typeof value === "string") return [{ type: "text", text: value }];
|
|
47
|
+
if (!Array.isArray(value)) throw new Error("invalid Claude transcript message content");
|
|
48
|
+
return value.map((block) => {
|
|
49
|
+
if (!object(block) || typeof block.type !== "string") throw new Error("invalid Claude transcript content block");
|
|
50
|
+
if (block.type === "text") {
|
|
51
|
+
if (typeof block.text !== "string") throw new Error("invalid Claude transcript text block");
|
|
52
|
+
} else if (block.type !== "tool_use" && block.type !== "tool_result" && !NON_TEXT_BLOCKS.has(block.type)) {
|
|
53
|
+
throw new Error(`unsupported Claude transcript content block: ${block.type}`);
|
|
54
|
+
}
|
|
55
|
+
return block;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
function decode(row: Row, seq: number): DecodedHistoryItem[] {
|
|
59
|
+
// A system record without a body is graph metadata, not a message.
|
|
60
|
+
if (row.type === "system" && row.content == null) return [];
|
|
61
|
+
const common = { windowId: "", ...(typeof row.timestamp === "string" ? { createdAt: row.timestamp } : {}) };
|
|
62
|
+
let blocks: Row[], role: DecodedHistoryItem["role"];
|
|
63
|
+
if (row.type === "user" || row.type === "assistant") {
|
|
64
|
+
if (!object(row.message) || row.message.role !== row.type) throw new Error("invalid Claude transcript message role");
|
|
65
|
+
blocks = blocksOf(row.message.content);
|
|
66
|
+
role = row.isCompactSummary === true || row.isMeta === true ? "system" : row.type;
|
|
67
|
+
} else if (row.type === "system") {
|
|
68
|
+
blocks = blocksOf(row.content);
|
|
69
|
+
role = "system";
|
|
70
|
+
} else {
|
|
71
|
+
// Old/new attachments are graph nodes even when they put no bytes in the request.
|
|
72
|
+
// `rendered` is a list of native rendered messages, not raw attachment payloads.
|
|
73
|
+
if (row.rendered === undefined) blocks = [];
|
|
74
|
+
else if (Array.isArray(row.rendered)) blocks = row.rendered.flatMap((message) => {
|
|
75
|
+
if (!object(message)) throw new Error("invalid Claude transcript rendered attachment");
|
|
76
|
+
return blocksOf(message.content);
|
|
77
|
+
});
|
|
78
|
+
else throw new Error("invalid Claude transcript rendered attachment");
|
|
79
|
+
role = "system";
|
|
80
|
+
}
|
|
81
|
+
const items: DecodedHistoryItem[] = [{ ...common, seq, role, text: contentText(blocks) }];
|
|
82
|
+
for (const block of blocks) {
|
|
83
|
+
if (block.type === "tool_use") {
|
|
84
|
+
if (!object(block.input)) throw new Error("invalid Claude transcript tool arguments");
|
|
85
|
+
items.push({ ...common, seq: seq + items.length, role: "tool_call", text: "", toolName: requiredString(block.name, "tool name"), toolCallId: requiredString(block.id, "tool id"), arguments: block.input });
|
|
86
|
+
} else if (block.type === "tool_result") {
|
|
87
|
+
if (block.is_error !== undefined && typeof block.is_error !== "boolean") throw new Error("invalid Claude transcript tool error flag");
|
|
88
|
+
const output = block.content === undefined ? "" : contentText(blocksOf(block.content));
|
|
89
|
+
items.push({ ...common, seq: seq + items.length, role: "tool", text: output, toolCallId: requiredString(block.tool_use_id, "tool result id"), toolError: block.is_error === true });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return items;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The protocol tags a complete boot carries; `context_window` is the pre-rename spelling that
|
|
97
|
+
* sessions and Claude transcripts already on disk still use, so both stay readable.
|
|
98
|
+
*/
|
|
99
|
+
const BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent name: claude \(/;
|
|
100
|
+
const BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
|
|
101
|
+
const BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
|
|
102
|
+
|
|
103
|
+
/** Match the complete retained notesoup boot, not a casually quoted window-id line. */
|
|
104
|
+
function bootOrdinal(row: Row, retained: boolean): number | undefined {
|
|
105
|
+
if (!retained || row.type !== "user" || !object(row.message)) return undefined;
|
|
106
|
+
const text = contentText(row.message.content);
|
|
107
|
+
if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text)) return undefined;
|
|
108
|
+
// A fork copies the retained boot verbatim. Its ordinal survives, while
|
|
109
|
+
// public window ids below always belong to the current transcript session.
|
|
110
|
+
const suffix = /^Current context window id: claude:[^\n]+:(\d+)$/m.exec(text)?.[1];
|
|
111
|
+
if (suffix === undefined) return undefined;
|
|
112
|
+
const ordinal = Number(suffix);
|
|
113
|
+
return Number.isSafeInteger(ordinal) ? ordinal : undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** All addresses are allocated on the full first-occurrence log, before branch selection. */
|
|
117
|
+
export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection {
|
|
118
|
+
const nodes = new Map<string, Node>();
|
|
119
|
+
let nextSeq = 1;
|
|
120
|
+
for (const row of rowsOf(text)) {
|
|
121
|
+
// Ignore non-message records, including future metadata. If selected ancestry
|
|
122
|
+
// reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
|
|
123
|
+
if (!MESSAGE_TYPES.has(row.type as string)) continue;
|
|
124
|
+
const uuid = requiredString(row.uuid, "uuid");
|
|
125
|
+
parent(row);
|
|
126
|
+
if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
|
|
127
|
+
if (row.isSidechain === true || row.agentId !== undefined) throw new Error("Claude history supports only the main session transcript");
|
|
128
|
+
// Resolve the window in the graph as it existed at this append, not the final
|
|
129
|
+
// rewritten tree. A preserved old row stays in its original window; a NEW child
|
|
130
|
+
// of its rewritten version belongs to the new window.
|
|
131
|
+
const ancestor = boundary(row) && typeof row.logicalParentUuid === "string" ? row.logicalParentUuid : parent(row);
|
|
132
|
+
const version: Version = { row, ancestorUuid: ancestor, ancestor: ancestor === undefined ? undefined : nodes.get(ancestor)?.latest };
|
|
133
|
+
const previous = nodes.get(uuid);
|
|
134
|
+
if (previous) {
|
|
135
|
+
// Native resume/compaction rewrites provenance and parent links, not logical identities.
|
|
136
|
+
if (previous.first.row.type !== row.type || !["message", "content", "rendered"].every((field) => isDeepStrictEqual(previous.first.row[field], row[field]))) {
|
|
137
|
+
throw new Error(`conflicting Claude transcript duplicate UUID: ${uuid}`);
|
|
138
|
+
}
|
|
139
|
+
previous.latest = version;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const items = decode(row, nextSeq);
|
|
143
|
+
nextSeq += items.length;
|
|
144
|
+
nodes.set(uuid, { first: version, latest: version, items });
|
|
145
|
+
}
|
|
146
|
+
const missingAncestors = new Set<string>();
|
|
147
|
+
function positionOf(version: Version): WindowPosition {
|
|
148
|
+
// Resolve long chains iteratively. A gap destroys ordinal evidence, not the
|
|
149
|
+
// confirmed suffix. Only a retained boot can re-anchor that suffix's ordinal.
|
|
150
|
+
const chain: Version[] = [], calculating = new Set<Version>();
|
|
151
|
+
let cursor = version;
|
|
152
|
+
let before: WindowPosition = { ordinal: 0 };
|
|
153
|
+
while (cursor.position === undefined) {
|
|
154
|
+
// Forward references use the parent's first eventual version, not a rewrite.
|
|
155
|
+
cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
|
|
156
|
+
if (calculating.has(cursor)) throw new Error("cyclic Claude transcript ancestry");
|
|
157
|
+
calculating.add(cursor);
|
|
158
|
+
chain.push(cursor);
|
|
159
|
+
if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined) {
|
|
160
|
+
missingAncestors.add(cursor.ancestorUuid);
|
|
161
|
+
before = { unknownAncestor: cursor.ancestorUuid };
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
if (cursor.ancestor === undefined) break;
|
|
165
|
+
cursor = cursor.ancestor;
|
|
166
|
+
}
|
|
167
|
+
before = cursor.position ?? before;
|
|
168
|
+
for (const current of chain.reverse()) {
|
|
169
|
+
const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
|
|
170
|
+
const marked = bootOrdinal(current.row, retained);
|
|
171
|
+
current.position = marked !== undefined
|
|
172
|
+
? { ordinal: "ordinal" in before ? Math.max(before.ordinal, marked) : marked }
|
|
173
|
+
: "ordinal" in before ? { ordinal: before.ordinal + (boundary(current.row) ? 1 : 0) } : before;
|
|
174
|
+
before = current.position;
|
|
175
|
+
}
|
|
176
|
+
return version.position!;
|
|
177
|
+
}
|
|
178
|
+
if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
|
|
179
|
+
if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
|
|
180
|
+
|
|
181
|
+
// The inference tree uses the latest rewritten parents. At a compact boundary the logical
|
|
182
|
+
// parent and preserved segments use ORIGINAL ancestry: the old context is still history.
|
|
183
|
+
const selected = new Set<string>(), visited = new Set<string>(), visiting = new Set<string>();
|
|
184
|
+
type Visit = { uuid: string; historical: boolean; exit?: boolean };
|
|
185
|
+
const stack: Visit[] = [{ uuid: source.headUuid, historical: false }];
|
|
186
|
+
while (stack.length > 0) {
|
|
187
|
+
const step = stack.pop()!, { uuid, historical } = step;
|
|
188
|
+
const key = `${historical ? "old" : "live"}:${uuid}`;
|
|
189
|
+
if (step.exit) { visiting.delete(key); visited.add(key); continue; }
|
|
190
|
+
if (visited.has(key)) continue;
|
|
191
|
+
if (visiting.has(key)) throw new Error("cyclic Claude transcript ancestry");
|
|
192
|
+
visiting.add(key);
|
|
193
|
+
stack.push({ ...step, exit: true });
|
|
194
|
+
const node = nodes.get(uuid);
|
|
195
|
+
if (!node) { missingAncestors.add(uuid); continue; }
|
|
196
|
+
selected.add(uuid);
|
|
197
|
+
const row = (historical ? node.first : node.latest).row;
|
|
198
|
+
const ancestor = parent(row);
|
|
199
|
+
if (ancestor !== undefined) stack.push({ uuid: ancestor, historical });
|
|
200
|
+
if (!boundary(row)) continue;
|
|
201
|
+
if (row.logicalParentUuid != null) stack.push({ uuid: requiredString(row.logicalParentUuid, "logicalParentUuid"), historical: true });
|
|
202
|
+
const meta = row.compactMetadata;
|
|
203
|
+
if (!object(meta)) continue;
|
|
204
|
+
if (object(meta.preservedSegment)) {
|
|
205
|
+
for (const field of ["headUuid", "tailUuid"]) if (meta.preservedSegment[field] !== undefined) stack.push({ uuid: requiredString(meta.preservedSegment[field], field), historical: true });
|
|
206
|
+
}
|
|
207
|
+
if (object(meta.preservedMessages)) {
|
|
208
|
+
const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
|
|
209
|
+
if (uuids === undefined) continue;
|
|
210
|
+
if (!Array.isArray(uuids)) throw new Error("invalid Claude preserved messages");
|
|
211
|
+
for (const id of uuids) {
|
|
212
|
+
const uuid = requiredString(id, "preserved UUID");
|
|
213
|
+
// allUuids also names virtual/non-persisted attachments. It is auxiliary
|
|
214
|
+
// evidence, not a reason to pretend the stored parent chain is missing.
|
|
215
|
+
if (nodes.has(uuid)) stack.push({ uuid, historical: true });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const current = positionOf(nodes.get(source.headUuid)!.latest);
|
|
221
|
+
const windowId = (position: WindowPosition) => `claude:${source.sessionId}:${"ordinal" in position ? position.ordinal : `unknown:${position.unknownAncestor}`}`;
|
|
222
|
+
const windowsById = new Map<string, DecodedHistoryWindow & { ordinal?: number }>();
|
|
223
|
+
const branchSeqs = new Set<number>();
|
|
224
|
+
let maxOrdinal = "ordinal" in current ? current.ordinal : 0;
|
|
225
|
+
for (const [uuid, node] of nodes) {
|
|
226
|
+
if (!selected.has(uuid)) continue;
|
|
227
|
+
const position = positionOf(node.first);
|
|
228
|
+
if ("ordinal" in position) maxOrdinal = Math.max(maxOrdinal, position.ordinal);
|
|
229
|
+
const id = windowId(position);
|
|
230
|
+
let window = windowsById.get(id);
|
|
231
|
+
if (!window) {
|
|
232
|
+
window = { windowId: id, ...("ordinal" in position ? { ordinal: position.ordinal } : {}), items: [] };
|
|
233
|
+
windowsById.set(id, window);
|
|
234
|
+
}
|
|
235
|
+
window.createdAt ??= node.items[0]?.createdAt;
|
|
236
|
+
for (const item of node.items) { branchSeqs.add(item.seq); window.items.push({ ...item, windowId: id }); }
|
|
237
|
+
}
|
|
238
|
+
// Preserve complete-history empty windows (including copied boot ordinals).
|
|
239
|
+
// With gaps, report only evidenced windows, never invent the missing ordinals.
|
|
240
|
+
if (missingAncestors.size === 0) {
|
|
241
|
+
for (let ordinal = 0; ordinal <= maxOrdinal; ordinal++) {
|
|
242
|
+
const id = windowId({ ordinal });
|
|
243
|
+
if (!windowsById.has(id)) windowsById.set(id, { windowId: id, ordinal, items: [] });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// Forward references can put a newer numbered window on disk first. Unknown
|
|
247
|
+
// segments are a separate, unordered group, not an inferred place in that timeline.
|
|
248
|
+
const windows = [...windowsById.values()].sort((a, b) => a.ordinal === undefined
|
|
249
|
+
? b.ordinal === undefined ? 0 : 1
|
|
250
|
+
: b.ordinal === undefined ? -1 : a.ordinal - b.ordinal);
|
|
251
|
+
return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Offline files have no live append binding. A unique graph leaf proves one ancestry; never pick among siblings by file order. */
|
|
255
|
+
export function offlineClaudeHead(text: string): string {
|
|
256
|
+
const latest = new Map<string, Row>();
|
|
257
|
+
for (const row of rowsOf(text)) {
|
|
258
|
+
if (MESSAGE_TYPES.has(row.type as string)) latest.set(requiredString(row.uuid, "uuid"), row);
|
|
259
|
+
}
|
|
260
|
+
const ancestors = new Set<string>();
|
|
261
|
+
for (const row of latest.values()) {
|
|
262
|
+
const id = parent(row);
|
|
263
|
+
if (id !== undefined) ancestors.add(id);
|
|
264
|
+
if (!boundary(row)) continue;
|
|
265
|
+
if (typeof row.logicalParentUuid === "string") ancestors.add(row.logicalParentUuid);
|
|
266
|
+
const meta = row.compactMetadata;
|
|
267
|
+
if (!object(meta)) continue;
|
|
268
|
+
if (object(meta.preservedSegment)) {
|
|
269
|
+
for (const field of ["headUuid", "tailUuid"]) {
|
|
270
|
+
if (typeof meta.preservedSegment[field] === "string") ancestors.add(meta.preservedSegment[field]);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
if (object(meta.preservedMessages)) {
|
|
274
|
+
const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
|
|
275
|
+
if (Array.isArray(uuids)) for (const uuid of uuids) if (typeof uuid === "string") ancestors.add(uuid);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const leaves = [...latest.keys()].filter((uuid) => !ancestors.has(uuid));
|
|
279
|
+
if (leaves.length !== 1) throw new Error(`Offline Claude transcript has ${leaves.length} possible heads; no confirmed unique leaf (refusing to guess a selected branch)`);
|
|
280
|
+
return leaves[0]!;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
|
|
284
|
+
if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
|
|
285
|
+
return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
|
|
286
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/** Read-only local rollout decoder for official Codex 0.160.1 (d27764b82f71).
|
|
2
|
+
* Wire owners: history/src/{lib,rollout_payload}.rs, rollout/src/ordinal.rs,
|
|
3
|
+
* thread-store/src/local/rollout_lineage.rs. Not an app-server history client.
|
|
4
|
+
* Native .jsonl.zst reads require Node >=22.15 (node:zlib zstdDecompressSync).
|
|
5
|
+
*/
|
|
6
|
+
import { readFile, readdir, realpath, stat } from "node:fs/promises";
|
|
7
|
+
import { basename, dirname, join, relative, sep } from "node:path";
|
|
8
|
+
import * as zlib from "node:zlib";
|
|
9
|
+
|
|
10
|
+
export type CodexTranscriptSource = { transcriptPath: string; threadId: string };
|
|
11
|
+
export type CodexTranscriptState = {
|
|
12
|
+
threadId: string;
|
|
13
|
+
rootSessionId: string;
|
|
14
|
+
cliVersion: string;
|
|
15
|
+
cwd: string;
|
|
16
|
+
model?: string;
|
|
17
|
+
/** Native, UNPREFIXED identities, also used by MCP _meta.windowId. */
|
|
18
|
+
currentWindowId?: string;
|
|
19
|
+
currentWindowNumber?: number;
|
|
20
|
+
firstWindowId?: string;
|
|
21
|
+
previousWindowId?: string;
|
|
22
|
+
};
|
|
23
|
+
export type NativeObject = Record<string, unknown>;
|
|
24
|
+
export type CodexRecord = {
|
|
25
|
+
type: string;
|
|
26
|
+
payload: NativeObject;
|
|
27
|
+
metadata?: NativeObject;
|
|
28
|
+
timestamp: string;
|
|
29
|
+
/** One record owns one seq, including records omitted from presentation. */
|
|
30
|
+
seq: number;
|
|
31
|
+
/** Metadata belongs to its physical segment, not the root-scoped session_id. */
|
|
32
|
+
owner: string;
|
|
33
|
+
/** Native window at this point, absent only when the producer did not persist it. */
|
|
34
|
+
windowId?: string;
|
|
35
|
+
};
|
|
36
|
+
type Position = { thread_id: string; end_ordinal_exclusive: number; end_byte_offset: number };
|
|
37
|
+
type Segment = { meta: NativeObject; records: CodexRecord[] };
|
|
38
|
+
const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
39
|
+
const UUID_RE = new RegExp(`^${UUID}$`);
|
|
40
|
+
const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
|
|
41
|
+
const RECORD_TYPES = new Set(["session_meta", "response_item", "compacted", "turn_context", "event_msg", "token_usage_record", "world_state", "retained_context", "security_risk_score", "inter_agent_communication", "inter_agent_communication_metadata", "realtime_item"]);
|
|
42
|
+
const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction"]);
|
|
43
|
+
// Explicit resource limits, not guessed sequence offsets or partial successful history.
|
|
44
|
+
const MAX_BYTES = 128 * 1024 * 1024, MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
|
|
45
|
+
export function nativeObject(value: unknown, field: string): NativeObject {
|
|
46
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an object`);
|
|
47
|
+
return value as NativeObject;
|
|
48
|
+
}
|
|
49
|
+
export function nativeString(value: unknown, field: string): string {
|
|
50
|
+
if (typeof value !== "string") throw new Error(`Invalid Codex ${field}: expected a string`);
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
function responseShape(value: unknown): void {
|
|
54
|
+
const type = nativeString(nativeObject(value, "response_item").type, "response_item.type");
|
|
55
|
+
if (!RESPONSE_TYPES.has(type)) throw new Error(`Unsupported Codex response item: ${type}`);
|
|
56
|
+
}
|
|
57
|
+
function id(value: unknown, field: string): string {
|
|
58
|
+
const result = nativeString(value, field);
|
|
59
|
+
if (!UUID_RE.test(result)) throw new Error(`Invalid Codex ${field}: expected a canonical UUID`);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
function integer(value: unknown, field: string): number {
|
|
63
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value >= Number.MAX_SAFE_INTEGER) throw new Error(`Invalid Codex ${field}: unsafe or negative integer`);
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
function position(value: unknown): Position | undefined {
|
|
67
|
+
if (value == null) return undefined;
|
|
68
|
+
const p = nativeObject(value, "history_base");
|
|
69
|
+
return { thread_id: id(p.thread_id, "history_base.thread_id (rollout ID)"), end_ordinal_exclusive: integer(p.end_ordinal_exclusive, "history_base ordinal"), end_byte_offset: integer(p.end_byte_offset, "history_base byte offset") };
|
|
70
|
+
}
|
|
71
|
+
function initialWindow(meta: NativeObject): string | undefined {
|
|
72
|
+
return meta.context_window == null ? undefined : id(nativeObject(meta.context_window, "context_window").window_id, "context_window.window_id");
|
|
73
|
+
}
|
|
74
|
+
function checkMeta(meta: NativeObject): void {
|
|
75
|
+
id(meta.id, "session_meta.id");
|
|
76
|
+
if (meta.session_id != null) id(meta.session_id, "session_meta.session_id");
|
|
77
|
+
if (meta.cli_version !== "0.160.1") throw new Error(`Unsupported Codex producer ${String(meta.cli_version)}; this decoder supports official 0.160.1 only`);
|
|
78
|
+
nativeString(meta.cwd, "session_meta.cwd");
|
|
79
|
+
if (meta.history_mode !== undefined && meta.history_mode !== "legacy" && meta.history_mode !== "paginated") throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
|
|
80
|
+
for (const field of ["forked_from_id", "parent_thread_id"]) if (meta[field] != null) id(meta[field], field);
|
|
81
|
+
for (const field of ["forked_from_ordinal_exclusive", "subagent_history_start_ordinal"]) if (meta[field] != null) integer(meta[field], field);
|
|
82
|
+
initialWindow(meta);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Only newline-committed records count. A valid JSON value without its newline is still an append tail. */
|
|
86
|
+
function segmentFromBytes(bytes: Buffer, cutoff?: Position): Segment {
|
|
87
|
+
const limit = cutoff?.end_byte_offset ?? bytes.length;
|
|
88
|
+
if (limit > bytes.length || (cutoff && (limit === 0 || bytes[limit - 1] !== 10))) throw new Error("Unavailable Codex lineage: cutoff is not a complete decoded JSONL boundary");
|
|
89
|
+
const records: CodexRecord[] = [];
|
|
90
|
+
let meta: NativeObject | undefined, previous = -1, lineNumber = 0;
|
|
91
|
+
for (let offset = 0; offset < limit;) {
|
|
92
|
+
const newline = bytes.indexOf(10, offset);
|
|
93
|
+
if (newline < 0 || newline >= limit) break;
|
|
94
|
+
lineNumber++;
|
|
95
|
+
let row: NativeObject;
|
|
96
|
+
try {
|
|
97
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(offset, newline));
|
|
98
|
+
row = nativeObject(JSON.parse(text), "record");
|
|
99
|
+
} catch { throw new Error(`Malformed committed Codex JSONL record at line ${lineNumber}`); }
|
|
100
|
+
offset = newline + 1;
|
|
101
|
+
const type = nativeString(row.type, "record.type");
|
|
102
|
+
if (!RECORD_TYPES.has(type)) throw new Error(`Unsupported Codex rollout record: ${type}`);
|
|
103
|
+
const payload = nativeObject(row.payload, `${type}.payload`);
|
|
104
|
+
if (!meta) {
|
|
105
|
+
if (type !== "session_meta") throw new Error("Invalid Codex transcript: first record must be session_meta");
|
|
106
|
+
meta = payload;
|
|
107
|
+
checkMeta(meta);
|
|
108
|
+
} else if (type === "session_meta") {
|
|
109
|
+
// Legacy copied forks can contain replayed metadata with no provable original
|
|
110
|
+
// coordinates. Do not relabel a copied tree as independently spoken events.
|
|
111
|
+
throw new Error("Unavailable Codex history: copied session_meta ancestry has no proved source addresses");
|
|
112
|
+
}
|
|
113
|
+
const paginated = meta.history_mode === "paginated";
|
|
114
|
+
const ordinal = paginated ? integer(row.ordinal, "paginated record ordinal") : lineNumber - 1;
|
|
115
|
+
if (!paginated && row.ordinal != null) throw new Error("Invalid Codex legacy transcript: unexpected ordinal");
|
|
116
|
+
if (ordinal <= previous) throw new Error("Invalid Codex transcript: non-increasing record ordinals");
|
|
117
|
+
if (records.length === 0 && ordinal !== (position(meta.history_base)?.end_ordinal_exclusive ?? 0)) throw new Error("Invalid Codex transcript: metadata ordinal does not match history_base");
|
|
118
|
+
previous = ordinal;
|
|
119
|
+
if (cutoff && ordinal >= cutoff.end_ordinal_exclusive) throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
|
|
120
|
+
if (type === "event_msg" && payload.type === "thread_rolled_back") throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
|
|
121
|
+
if (type === "response_item") responseShape(payload);
|
|
122
|
+
records.push({ type, payload, timestamp: nativeString(row.timestamp, "record.timestamp"), seq: ordinal + 1, owner: meta.id as string, ...(row.metadata == null ? {} : { metadata: nativeObject(row.metadata, "response metadata") }) });
|
|
123
|
+
}
|
|
124
|
+
if (!meta) throw new Error("Unavailable Codex transcript: no committed session_meta yet");
|
|
125
|
+
const base = position(meta.history_base);
|
|
126
|
+
if (base && meta.history_mode !== "paginated") throw new Error("Invalid Codex history_base on a non-paginated transcript");
|
|
127
|
+
if (cutoff && meta.history_mode !== "paginated") throw new Error("Unavailable Codex lineage: referenced source is not paginated");
|
|
128
|
+
// A cutoff is a native coordinate pair, not permission to approximate an ordinal
|
|
129
|
+
// inside a gap. Usually the included prefix already proves its exclusive end.
|
|
130
|
+
if (cutoff && previous + 1 !== cutoff.end_ordinal_exclusive) {
|
|
131
|
+
const nextNewline = bytes.indexOf(10, limit);
|
|
132
|
+
if (nextNewline < 0) throw new Error("Unavailable Codex lineage: ordinal cutoff is beyond the proved prefix");
|
|
133
|
+
let next: NativeObject;
|
|
134
|
+
try { next = nativeObject(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(limit, nextNewline))), "cutoff successor"); }
|
|
135
|
+
catch { throw new Error("Unavailable Codex lineage: cannot prove ordinal cutoff successor"); }
|
|
136
|
+
if (integer(next.ordinal, "cutoff successor ordinal") !== cutoff.end_ordinal_exclusive) throw new Error("Unavailable Codex lineage: byte and ordinal cutoffs disagree");
|
|
137
|
+
}
|
|
138
|
+
const start = meta.subagent_history_start_ordinal;
|
|
139
|
+
if (start != null && (meta.history_mode !== "paginated" || previous < integer(start, "subagent history start") - 1)) throw new Error("Unavailable Codex history: incomplete inherited subagent prefix");
|
|
140
|
+
return { meta, records };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function within(root: string, path: string): boolean {
|
|
144
|
+
const rel = relative(root, path);
|
|
145
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
146
|
+
}
|
|
147
|
+
/** Infer storage roots only from the supplied native path, never $HOME or a private DB. */
|
|
148
|
+
function storageHome(path: string): string {
|
|
149
|
+
for (let cursor = dirname(path); dirname(cursor) !== cursor; cursor = dirname(cursor)) {
|
|
150
|
+
if (basename(cursor) === "sessions" || basename(cursor) === "archived_sessions") return dirname(cursor);
|
|
151
|
+
}
|
|
152
|
+
throw new Error("Unavailable Codex lineage: transcript must be under native sessions/ or archived_sessions/ to resolve history_base");
|
|
153
|
+
}
|
|
154
|
+
async function referencedPath(home: string, rolloutId: string): Promise<string> {
|
|
155
|
+
const matches: string[] = [], directories = [join(home, "sessions"), join(home, "archived_sessions")];
|
|
156
|
+
let entriesSeen = 0;
|
|
157
|
+
while (directories.length) {
|
|
158
|
+
const directory = directories.pop()!;
|
|
159
|
+
let entries;
|
|
160
|
+
try { entries = await readdir(directory, { withFileTypes: true }); }
|
|
161
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
162
|
+
for (const entry of entries) {
|
|
163
|
+
if (++entriesSeen > MAX_DIRECTORY_ENTRIES) throw new Error("Unavailable Codex lineage: native directory discovery limit exceeded");
|
|
164
|
+
const path = join(directory, entry.name);
|
|
165
|
+
if (entry.isDirectory()) directories.push(path);
|
|
166
|
+
else if (entry.isFile()) {
|
|
167
|
+
const name = FILE_RE.exec(entry.name);
|
|
168
|
+
if (name && (name[2] ?? name[1]) === rolloutId) matches.push(path);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
|
|
173
|
+
return matches[0]!;
|
|
174
|
+
}
|
|
175
|
+
async function decodedBytes(path: string, remaining: number): Promise<Buffer> {
|
|
176
|
+
const info = await stat(path);
|
|
177
|
+
if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
|
|
178
|
+
const bytes = await readFile(path);
|
|
179
|
+
// 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
|
|
180
|
+
if (path.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
|
|
181
|
+
const decoded = path.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(bytes, { maxOutputLength: remaining }) : bytes;
|
|
182
|
+
if (decoded.length > remaining) throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
|
|
183
|
+
return decoded;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
|
|
187
|
+
export async function readCodexTranscript(source: CodexTranscriptSource): Promise<{ state: CodexTranscriptState; records: CodexRecord[]; highestSeq: number }> {
|
|
188
|
+
if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath) throw new Error("Codex transcript_path is unavailable");
|
|
189
|
+
id(source.threadId, "requested threadId");
|
|
190
|
+
try {
|
|
191
|
+
let path = await realpath(source.transcriptPath), cutoff: Position | undefined, home: string | undefined;
|
|
192
|
+
let remaining = MAX_BYTES;
|
|
193
|
+
const segments: Segment[] = [], seen = new Set<string>();
|
|
194
|
+
while (true) {
|
|
195
|
+
if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
|
|
196
|
+
seen.add(path);
|
|
197
|
+
const bytes = await decodedBytes(path, remaining);
|
|
198
|
+
remaining -= bytes.length;
|
|
199
|
+
const segment = segmentFromBytes(bytes, cutoff);
|
|
200
|
+
if (segments.length === 0 && segment.meta.id !== source.threadId) throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
|
|
201
|
+
if (cutoff) {
|
|
202
|
+
const name = FILE_RE.exec(basename(path));
|
|
203
|
+
if (!name || (name[2] ?? name[1]) !== cutoff.thread_id || name[1] !== segment.meta.id) throw new Error("Unavailable Codex lineage: native filename/rollout/metadata identity mismatch");
|
|
204
|
+
}
|
|
205
|
+
segments.unshift(segment);
|
|
206
|
+
const base = position(segment.meta.history_base);
|
|
207
|
+
if (!base) break;
|
|
208
|
+
if (base.end_ordinal_exclusive === 0) throw new Error("Invalid Codex lineage: history_base must include source metadata");
|
|
209
|
+
home ??= storageHome(path);
|
|
210
|
+
path = await realpath(await referencedPath(home, base.thread_id));
|
|
211
|
+
if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path))) throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
|
|
212
|
+
cutoff = base;
|
|
213
|
+
}
|
|
214
|
+
// history_base is physical; forked_from_ordinal_exclusive is the logical
|
|
215
|
+
// parent boundary (protocol.rs HistoryPosition, revert_thread.rs). A revert
|
|
216
|
+
// may retain this thread's own later delta, but cannot grow inherited history.
|
|
217
|
+
for (let index = 0; index < segments.length; index++) {
|
|
218
|
+
const meta = segments[index]!.meta, end = meta.forked_from_ordinal_exclusive;
|
|
219
|
+
if (end != null && meta.forked_from_id != null) {
|
|
220
|
+
for (const ancestor of segments.slice(0, index)) {
|
|
221
|
+
if (ancestor.meta.id !== meta.id && ancestor.records.some((record) => record.seq - 1 >= (end as number))) throw new Error("Unavailable Codex lineage: physical ancestry exceeds the logical fork cutoff");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const selected = segments.at(-1)!.meta;
|
|
226
|
+
const state: CodexTranscriptState = { threadId: source.threadId, rootSessionId: (selected.session_id ?? selected.id) as string, cliVersion: selected.cli_version as string, cwd: selected.cwd as string };
|
|
227
|
+
const records: CodexRecord[] = [];
|
|
228
|
+
let window: string | undefined, first: string | undefined, previousWindow: string | undefined, number: number | undefined, sawCompacted = false, lastSeq = 0;
|
|
229
|
+
let contextModel: string | undefined, settingsModel: string | undefined;
|
|
230
|
+
for (const segment of segments) {
|
|
231
|
+
// Native reconstruction uses the requested header's initial identity unless
|
|
232
|
+
// an inherited checkpoint supplies the effective window (rollout_reconstruction.rs).
|
|
233
|
+
if (!sawCompacted) { window = initialWindow(segment.meta); first = window; previousWindow = undefined; number = window ? 0 : undefined; }
|
|
234
|
+
for (const record of segment.records) {
|
|
235
|
+
if (record.seq <= lastSeq) throw new Error("Unavailable Codex lineage: overlapping source coordinates");
|
|
236
|
+
lastSeq = record.seq;
|
|
237
|
+
if (record.type === "compacted") {
|
|
238
|
+
sawCompacted = true;
|
|
239
|
+
const p = record.payload;
|
|
240
|
+
nativeString(p.message, "compacted.message");
|
|
241
|
+
if (p.replacement_history != null && !Array.isArray(p.replacement_history)) throw new Error("Invalid Codex replacement_history");
|
|
242
|
+
if (Array.isArray(p.replacement_history)) p.replacement_history.forEach(responseShape);
|
|
243
|
+
if (p.replacement_history_metadata != null && (!Array.isArray(p.replacement_history_metadata) || !Array.isArray(p.replacement_history) || p.replacement_history_metadata.length !== p.replacement_history.length)) throw new Error("Invalid Codex replacement_history_metadata alignment");
|
|
244
|
+
// Numeric legacy window_id has no usable native identity; don't turn it
|
|
245
|
+
// into a UUID, or silently assign subsequent records to the old window.
|
|
246
|
+
window = p.window_id == null || typeof p.window_id === "number" ? undefined : id(p.window_id, "compacted.window_id");
|
|
247
|
+
number = p.window_number == null ? (typeof p.window_id === "number" ? integer(p.window_id, "legacy window number") : undefined) : integer(p.window_number, "window_number");
|
|
248
|
+
first = p.first_window_id == null ? undefined : id(p.first_window_id, "first_window_id");
|
|
249
|
+
previousWindow = p.previous_window_id == null ? undefined : id(p.previous_window_id, "previous_window_id");
|
|
250
|
+
}
|
|
251
|
+
record.windowId = window;
|
|
252
|
+
// Explicitly copied subagent inference context isn't child-local history.
|
|
253
|
+
// Preserve its coordinates as holes, not invented parent event addresses.
|
|
254
|
+
const start = segment.meta.subagent_history_start_ordinal;
|
|
255
|
+
if (start != null && record.type !== "session_meta" && record.seq - 1 < (start as number)) continue;
|
|
256
|
+
if (record.owner === source.threadId && record.type === "turn_context") contextModel = nativeString(record.payload.model, "turn_context.model");
|
|
257
|
+
if (record.type === "event_msg" && record.payload.type === "thread_settings_applied" && record.payload.thread_id === source.threadId) {
|
|
258
|
+
settingsModel = nativeString(nativeObject(record.payload.thread_settings, "thread_settings").model, "thread_settings.model");
|
|
259
|
+
}
|
|
260
|
+
records.push(record);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
Object.assign(state, { currentWindowId: window, currentWindowNumber: number, firstWindowId: first, previousWindowId: previousWindow });
|
|
264
|
+
// Native latest model settings win over a frozen companion TurnContext after
|
|
265
|
+
// compaction (history/src/lib.rs latest_disabled_plugin_ids has same ownership).
|
|
266
|
+
if (settingsModel ?? contextModel) state.model = settingsModel ?? contextModel;
|
|
267
|
+
return { state, records, highestSeq: lastSeq };
|
|
268
|
+
} catch (error) {
|
|
269
|
+
throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Same decoder and ownership as history; no independently guessed boot window. */
|
|
274
|
+
export async function readCodexTranscriptState(source: CodexTranscriptSource): Promise<CodexTranscriptState> {
|
|
275
|
+
return (await readCodexTranscript(source)).state;
|
|
276
|
+
}
|