notesoup 0.52.6 → 0.53.0

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.
Files changed (84) hide show
  1. package/README.md +3 -1
  2. package/dist/plugins/claude/src/helper.js +34 -7
  3. package/dist/plugins/claude/src/history.d.ts +7 -2
  4. package/dist/plugins/claude/src/history.js +53 -22
  5. package/dist/plugins/claude/src/text.d.ts +5 -0
  6. package/dist/plugins/claude/src/text.js +12 -0
  7. package/dist/plugins/codex/src/cli.d.ts +2 -0
  8. package/dist/plugins/codex/src/cli.js +25 -0
  9. package/dist/plugins/codex/src/history.d.ts +8 -0
  10. package/dist/plugins/codex/src/history.js +238 -0
  11. package/dist/plugins/codex/src/hooks.d.ts +9 -0
  12. package/dist/plugins/codex/src/hooks.js +196 -0
  13. package/dist/plugins/codex/src/identity.d.ts +35 -0
  14. package/dist/plugins/codex/src/identity.js +134 -0
  15. package/dist/plugins/codex/src/mcp.d.ts +7 -0
  16. package/dist/plugins/codex/src/mcp.js +159 -0
  17. package/dist/plugins/codex/src/state.d.ts +23 -0
  18. package/dist/plugins/codex/src/state.js +92 -0
  19. package/dist/plugins/codex/src/text.d.ts +14 -0
  20. package/dist/plugins/codex/src/text.js +25 -0
  21. package/dist/plugins/codex/src/transcript.d.ts +39 -0
  22. package/dist/plugins/codex/src/transcript.js +313 -0
  23. package/dist/src/boot/render.js +11 -10
  24. package/dist/src/boot/text.d.ts +4 -5
  25. package/dist/src/boot/text.js +14 -28
  26. package/dist/src/budget/text.d.ts +1 -1
  27. package/dist/src/budget/text.js +1 -1
  28. package/dist/src/history/history.js +12 -11
  29. package/dist/src/tools/history.d.ts +5 -3
  30. package/dist/src/tools/history.js +9 -11
  31. package/dist/test/claude-history.test.js +135 -3
  32. package/dist/test/codex-history.test.d.ts +1 -0
  33. package/dist/test/codex-history.test.js +330 -0
  34. package/dist/test/codex-plugin.test.d.ts +1 -0
  35. package/dist/test/codex-plugin.test.js +365 -0
  36. package/dist/test/dependencies.test.js +8 -2
  37. package/dist/test/dsh.test.js +1 -1
  38. package/dist/test/helpers/dependency-graph.js +1 -1
  39. package/dist/test/history.integration.test.js +26 -1
  40. package/dist/test/model-facing-text.test.js +41 -26
  41. package/dist/test/notes.integration.test.js +3 -0
  42. package/docs/claude-code-mod.md +6 -2
  43. package/docs/codex.md +91 -0
  44. package/docs/dsh.md +1 -1
  45. package/docs/reset-lifecycle.md +1 -1
  46. package/docs/tool-results.md +2 -2
  47. package/package.json +6 -3
  48. package/playbook.md +1 -1
  49. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  50. package/plugins/claude/dist/claude/helper.js +120 -74
  51. package/plugins/claude/playbook.md +1 -1
  52. package/plugins/claude/skills/dream/SKILL.md +1 -1
  53. package/plugins/claude/skills/memory/SKILL.md +1 -1
  54. package/plugins/claude/src/helper.ts +34 -9
  55. package/plugins/claude/src/history.ts +54 -22
  56. package/plugins/claude/src/text.ts +13 -0
  57. package/plugins/codex/README.md +43 -0
  58. package/plugins/codex/dist/codex/notesoup.js +27800 -0
  59. package/plugins/codex/hooks/hooks.json +41 -0
  60. package/plugins/codex/mcp.json +10 -0
  61. package/plugins/codex/plugin.json +6 -0
  62. package/plugins/codex/src/cli.ts +26 -0
  63. package/plugins/codex/src/history.ts +193 -0
  64. package/plugins/codex/src/hooks.ts +190 -0
  65. package/plugins/codex/src/identity.ts +147 -0
  66. package/plugins/codex/src/mcp.ts +171 -0
  67. package/plugins/codex/src/state.ts +102 -0
  68. package/plugins/codex/src/text.ts +31 -0
  69. package/plugins/codex/src/transcript.ts +275 -0
  70. package/plugins/paseo/OVERVIEW.md +6 -2
  71. package/plugins/paseo/client/brain-empty-card.tsx +3 -1
  72. package/plugins/paseo/client/brain-empty-transformer.ts +7 -14
  73. package/plugins/paseo/client/notes-op-transformer.ts +10 -18
  74. package/plugins/paseo/client/tool-result.ts +31 -0
  75. package/plugins/paseo/test/brain-empty.test.ts +24 -1
  76. package/plugins/paseo/test/fixtures/claude-tool-calls.ts +86 -0
  77. package/plugins/paseo/test/notes-op.test.ts +39 -1
  78. package/skills/dream/SKILL.md +1 -1
  79. package/skills/memory/SKILL.md +1 -1
  80. package/src/boot/render.ts +11 -9
  81. package/src/boot/text.ts +16 -30
  82. package/src/budget/text.ts +1 -1
  83. package/src/history/history.ts +12 -10
  84. package/src/tools/history.ts +14 -13
@@ -70,11 +70,7 @@ function renderRead(data) {
70
70
  const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
71
71
  return [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
72
72
  }
73
- /* ------------------------------------------------------------------ shared bounding */
74
- /** Include rendering and cursors in the budget, not just row contents. */
75
- function pageFits(page) {
76
- return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
77
- }
73
+ const plainText = (text) => text;
78
74
  // Sample known ids in the refusal message itself, never as a second listing.
79
75
  const MAX_REPORTED_WINDOWS = 5;
80
76
  /** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
@@ -106,9 +102,9 @@ export const historyWindows = {
106
102
  description: "List this session's context windows, oldest first, with seq ranges.",
107
103
  parameters: historyWindowsParameters,
108
104
  outputSchema: resultSchema(HistoryWindowsDataSchema),
109
- async execute(_params, projection, sessionId) {
105
+ async execute(_params, projection, sessionId, wrapText = plainText) {
110
106
  const data = { session_id: sessionId, windows: [], more: projection.windows.length };
111
- const fits = (candidate) => fitsResult(success(candidate), (result) => renderOutcome(result, renderWindows));
107
+ const fits = (candidate) => fitsResult(success(candidate), (result) => wrapText(renderOutcome(result, renderWindows)));
112
108
  for (const window of projection.windows) {
113
109
  let first = null;
114
110
  let last = null;
@@ -151,7 +147,7 @@ export const historyList = {
151
147
  description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
152
148
  parameters: historyListParameters,
153
149
  outputSchema: resultSchema(HistoryPageSchema),
154
- async execute(params, projection) {
150
+ async execute(params, projection, wrapText = plainText) {
155
151
  const resolved = resolveWindowId(projection, params.window_id);
156
152
  if (!resolved.ok)
157
153
  return resolved.outcome;
@@ -159,7 +155,9 @@ export const historyList = {
159
155
  const badWindow = badWindowId(projection, scoped);
160
156
  if (badWindow)
161
157
  return badWindow;
162
- return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
158
+ // Charge wrapped rendering and cursors, not only event previews.
159
+ const fits = (page) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
160
+ return selectPage(projection, scoped, fits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
163
161
  },
164
162
  render: (result) => renderOutcome(result, renderPage),
165
163
  };
@@ -171,7 +169,7 @@ export const historyRead = {
171
169
  description: "Read one event in full: tool arguments, output, and nested calls.",
172
170
  parameters: historyReadParameters,
173
171
  outputSchema: resultSchema(HistoryReadDataSchema),
174
- async execute(params, projection) {
172
+ async execute(params, projection, wrapText = plainText) {
175
173
  const item = allItems(projection).find((event) => event.seq === params.seq);
176
174
  // Address checks run in one order: past the end of the file, off this branch, then
177
175
  // consumed by a pairing. Only the last two can mention what is at the address.
@@ -201,7 +199,7 @@ export const historyRead = {
201
199
  ...toolSummary(item),
202
200
  ...nestedCallSummary(item),
203
201
  ...window,
204
- }), (result) => renderOutcome(result, renderRead));
202
+ }), (result) => wrapText(renderOutcome(result, renderRead)));
205
203
  },
206
204
  render: (result) => renderOutcome(result, renderRead),
207
205
  };
@@ -9,6 +9,7 @@ import { unavailableNotesSnapshot } from "../src/boot/snapshot.js";
9
9
  import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
10
10
  import { allItems, eventDocument } from "../src/history/history.js";
11
11
  import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
12
+ import { TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
12
13
  import { dispatch } from "../plugins/claude/src/helper.js";
13
14
  const sessionId = "synthetic-session";
14
15
  function row(uuid, parentUuid, type, content, extra = {}) {
@@ -84,11 +85,15 @@ test("Claude file-history deltas do not become events or change history addresse
84
85
  assert.deepEqual(project([delta, rows[0], delta, rows[1], delta], "a"), baseline);
85
86
  assert.equal(baseline.highestSeq, 2);
86
87
  });
87
- test("Claude skips unknown record types unless selected ancestry requires them", () => {
88
+ test("Claude skips unknown record types and treats required skipped UUIDs as gaps, not content", () => {
88
89
  const u = user("u", null, "hello"), a = assistant("a", "u", [{ type: "text", text: "reply" }]);
89
90
  const unknown = { type: "future-record", uuid: "future", parentUuid: "not-on-disk", content: "private metadata" };
90
91
  assert.deepEqual(project([unknown, u, unknown, a, unknown], "a"), project([u, a], "a"));
91
- assert.throws(() => project([u, unknown, { ...a, parentUuid: "future" }], "a"), /missing Claude transcript ancestor: future/);
92
+ const incomplete = project([u, unknown, { ...a, parentUuid: "future" }], "a");
93
+ assert.deepEqual(incomplete.missingAncestors, ["future"]);
94
+ assert.equal(incomplete.currentWindowOrdinal, undefined);
95
+ assert.deepEqual(allItems(incomplete).map((event) => event.seq), [2]);
96
+ assert.doesNotMatch(allItems(incomplete).map(eventDocument).join("\n"), /private metadata|hello/);
92
97
  });
93
98
  test("Claude duplicate UUID records do not allocate again or move addresses on reload", () => {
94
99
  const u = user("u", null, "hello"), a = assistant("a", "u", [call("one")]);
@@ -182,7 +187,7 @@ test("Claude resolves forward persisted ancestry without renumbering or using la
182
187
  assert.equal(allItems(projection).find((event) => event.text === "hook notice")?.windowId, `claude:${sessionId}:0`);
183
188
  assert.equal(allItems(projection).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:1`);
184
189
  assert.deepEqual(project(rows, "new"), projection);
185
- assert.throws(() => project([notice], "notice"), /missing.*ancestor/);
190
+ assert.deepEqual(project([notice], "notice").missingAncestors, ["attachment"]);
186
191
  assert.equal(project([user("u", null, bootText(9))], "u").windows.length, 1, "ordinary user text is not a trusted retained boot");
187
192
  });
188
193
  test("Claude attachments expose recorded renderings only and keep non-rendered nodes in ancestry", () => {
@@ -203,8 +208,135 @@ test("Claude tolerates only the uncommitted JSONL tail, not malformed committed
203
208
  assert.throws(() => project([row("u", null, "user", { type: "text", text: "not an array" })], "u"), /message content/);
204
209
  assert.throws(() => project([user("u", null, "first"), user("u", null, "conflict")], "u"), /conflicting.*duplicate UUID/);
205
210
  assert.throws(() => project([{ ...user("u", null, "first"), isSidechain: true }], "u"), /only the main/);
211
+ assert.throws(() => project([user("u", "a", "cycle"), assistant("a", "u", "cycle")], "a"), /cyclic Claude transcript ancestry/);
212
+ assert.throws(() => project([user("u", "missing", "gap"), assistant("a", "a", "cycle")], "a"), /cyclic Claude transcript ancestry/);
206
213
  assert.throws(() => project([{ ...user("u", null, "first"), sessionId: "another-session" }], "u"), /different session/);
207
214
  });
215
+ test("Claude gaps retain only confirmed suffixes, keep pairing/seqs, and disappear when the ancestor is appended", async () => {
216
+ const rows = [user("prefix", null, "unconfirmed prefix"), assistant("sibling", "prefix", "unrelated sibling"),
217
+ assistant("suffix", "missing", [{ type: "text", text: "searchable suffix" }, call("one")]),
218
+ row("output", "suffix", "user", [result("one", "confirmed output")]),
219
+ assistant("gap-sibling", "missing", "unrelated gap sibling")];
220
+ const incomplete = project(rows, "output");
221
+ assert.deepEqual(incomplete.missingAncestors, ["missing"]);
222
+ assert.equal(incomplete.currentWindowOrdinal, undefined);
223
+ assert.deepEqual(allItems(incomplete).map((event) => event.seq), [3, 4, 5]);
224
+ assert.equal(incomplete.pairedResults.get(6), 4);
225
+ assert.equal(incomplete.highestSeq, 7);
226
+ assert.match(incomplete.windows[0].windowId, /:unknown:missing$/);
227
+ const suffix = await historyList.execute({ query: "searchable suffix" }, incomplete);
228
+ assert.ok(suffix.ok);
229
+ assert.deepEqual(suffix.data.items.map((item) => "seq" in item ? item.seq : -1), [3]);
230
+ const tool = await historyRead.execute({ seq: 4 }, incomplete);
231
+ assert.ok(tool.ok);
232
+ assert.match(tool.data.text, /confirmed output/);
233
+ assert.doesNotMatch(allItems(incomplete).map(eventDocument).join("\n"), /unconfirmed prefix|unrelated sibling|unrelated gap sibling/);
234
+ // A later first occurrence gets the next append seq, never an inserted seq.
235
+ const recovered = project([...rows, user("missing", "prefix", "recovered ancestor")], "output");
236
+ assert.deepEqual(recovered.missingAncestors, []);
237
+ assert.equal(recovered.currentWindowOrdinal, 0);
238
+ assert.equal(recovered.highestSeq, 8);
239
+ assert.deepEqual(allItems(recovered).map((event) => event.seq), [1, 3, 4, 5, 8]);
240
+ assert.equal(recovered.pairedResults.get(6), 4);
241
+ assert.ok(!recovered.branchSeqs.has(2) && !recovered.branchSeqs.has(7), "recovery never selects either sibling");
242
+ });
243
+ test("Claude helper reports gaps on list/read/windows and re-anchors reset state only with a retained boot", async (t) => {
244
+ const root = mkdtempSync(join(tmpdir(), "claude-history-gap-"));
245
+ t.after(() => rmSync(root, { recursive: true, force: true }));
246
+ const transcriptPath = join(root, "transcript.jsonl");
247
+ const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
248
+ const rows = [user("prefix", null, "do not expose disconnected prefix"),
249
+ { type: "future-record", uuid: "missing", parentUuid: "prefix", content: "do not expose metadata" },
250
+ assistant("suffix", "missing", "confirmed suffix")];
251
+ const history = { sessionId, transcriptPath, headUuid: "suffix" };
252
+ const invoke = (tool, params = {}) => dispatch({ op: "tool", tool, params, identity, history });
253
+ writeFileSync(transcriptPath, jsonl(rows));
254
+ for (const [tool, params] of [["history_list", {}], ["history_read", { seq: 2 }], ["history_windows", {}],
255
+ ["history_list", { query: "no matches" }], ["history_read", { seq: 99 }]]) {
256
+ const response = await invoke(tool, params);
257
+ assert.match(response.text, /history is incomplete: missing ancestor UUID\(s\): "missing"/);
258
+ assert.doesNotMatch(response.text, /do not expose/);
259
+ }
260
+ assert.match((await invoke("history_list")).text, /confirmed suffix/);
261
+ const excluded = await invoke("history_read", { seq: 1 });
262
+ assert.equal(excluded.ok, false);
263
+ assert.match(excluded.text, /outside the confirmed selected history/);
264
+ assert.match((await invoke("history_list", { window_id: "@previous" })).text, /Cannot resolve "@previous"/);
265
+ await assert.rejects(invoke("history_list", { window_id: "@previous", before_seq: "invalid" }), /invalid history_list parameters: before_seq/);
266
+ await assert.rejects(invoke("history_read", { seq: "2" }), /invalid history_read parameters: seq/);
267
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /cannot determine the current window ordinal/);
268
+ // A native boundary alone cannot count the missing earlier resets. A quoted
269
+ // identity without the full retained protocol is not a new ordinal anchor.
270
+ rows.push(compact("boundary", "suffix"), row("partial", "boundary", "user", "Current context window id: claude:synthetic-session:8"));
271
+ writeFileSync(transcriptPath, jsonl(rows));
272
+ history.headUuid = "partial";
273
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /cannot determine the current window ordinal/);
274
+ rows.push(row("boot", "partial", "user", bootText(8), { isCompactSummary: true }), user("after", "boot", "after anchored reset"));
275
+ writeFileSync(transcriptPath, jsonl(rows));
276
+ history.headUuid = "after";
277
+ const anchored = await readClaudeHistory(history);
278
+ assert.equal(anchored.currentWindowOrdinal, 8);
279
+ assert.deepEqual(anchored.windows.map((window) => window.windowId), [`claude:${sessionId}:8`, `claude:${sessionId}:unknown:missing`], "unknown segments are listed separately, not inserted into the numbered timeline");
280
+ assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 8 }, "never windows.length - 1");
281
+ assert.match((await invoke("history_read", { seq: 6 })).text, /window claude:synthetic-session:8/);
282
+ assert.match((await invoke("history_windows")).text, /history is incomplete/);
283
+ assert.match((await invoke("history_list", { window_id: "@previous" })).text, /Cannot resolve "@previous"/);
284
+ rows.push(compact("next", "after"), row("next-boot", "next", "user", bootText(9)), user("latest", "next-boot", "latest"));
285
+ writeFileSync(transcriptPath, jsonl(rows));
286
+ history.headUuid = "latest";
287
+ const previous = await invoke("history_list", { window_id: "@previous" });
288
+ assert.ok(previous.ok);
289
+ assert.match(previous.text, /after anchored reset/);
290
+ assert.doesNotMatch(previous.text, /confirmed suffix/);
291
+ // Restore the record as a supported message: warning disappears on the next
292
+ // read, without any in-memory repair state or changed existing addresses.
293
+ rows.push(user("missing", "prefix", "recovered ancestor"));
294
+ writeFileSync(transcriptPath, jsonl(rows));
295
+ assert.doesNotMatch((await invoke("history_windows")).text, /history is incomplete|:unknown:/);
296
+ assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 9 });
297
+ });
298
+ test("Claude gap windows sort by confirmed ordinal despite forward references, without duplicating paired output", async () => {
299
+ const rows = [row("notice", "boot9", "system", "notice"),
300
+ row("boot8", "missing", "user", bootText(8), { isCompactSummary: true }),
301
+ assistant("call", "boot8", [call("t")]), compact("boundary9", "call"),
302
+ row("boot9", "boundary9", "user", bootText(9)), row("result", "notice", "user", [result("t", "output")])];
303
+ const projection = project(rows, "result");
304
+ const windows = await historyWindows.execute({}, projection, sessionId);
305
+ assert.ok(windows.ok);
306
+ assert.deepEqual(windows.data.windows.map((window) => window.window_id), [8, 9].map((ordinal) => `claude:${sessionId}:${ordinal}`));
307
+ assert.equal(projection.currentWindowOrdinal, 9);
308
+ assert.equal(projection.highestSeq, 8);
309
+ assert.deepEqual(allItems(projection).filter((event) => event.role === "tool").map((event) => [event.seq, event.text]), [[4, "output"]]);
310
+ assert.equal(projection.pairedResults.get(8), 4);
311
+ const alias = await historyRead.execute({ seq: 8 }, projection);
312
+ assert.ok(!alias.ok);
313
+ assert.equal(alias.error.code, "not_an_event");
314
+ assert.match(alias.error.message, /read seq 4/);
315
+ });
316
+ test("Claude gap notices participate in list/read budgets without changing read coordinates", async (t) => {
317
+ const root = mkdtempSync(join(tmpdir(), "claude-history-budget-"));
318
+ t.after(() => rmSync(root, { recursive: true, force: true }));
319
+ const transcriptPath = join(root, "transcript.jsonl"), text = "x".repeat(50000);
320
+ writeFileSync(transcriptPath, jsonl([assistant("head", "missing", text)]));
321
+ const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
322
+ const history = { sessionId, transcriptPath, headUuid: "head" };
323
+ const invoke = async (tool, params) => {
324
+ const response = await dispatch({ op: "tool", tool, params, identity, history });
325
+ assert.ok(response.ok);
326
+ assert.match(response.text, /history is incomplete.*"missing"/);
327
+ assert.ok(Buffer.byteLength(response.text, "utf8") <= TOOL_OUTPUT_MAX_BYTES, `${tool}: ${Buffer.byteLength(response.text, "utf8")} bytes`);
328
+ return response.text;
329
+ };
330
+ const first = await invoke("history_read", { seq: 1, max_chars: 50000 });
331
+ const offset = Number(/\[truncated; continue at offset_chars=(\d+)\]$/.exec(first)?.[1]);
332
+ assert.ok(offset > 0 && offset < text.length);
333
+ const firstBody = /\n\n(x+)\n\n\[truncated;/.exec(first)?.[1];
334
+ assert.equal(firstBody, text.slice(0, offset), "the footer addresses the first undelivered character, not the decorated text");
335
+ const rest = await invoke("history_read", { seq: 1, offset_chars: offset, max_chars: 50000 });
336
+ assert.equal(/\n\n(x+)$/.exec(rest)?.[1], text.slice(offset));
337
+ assert.doesNotMatch(rest, /\[truncated;/);
338
+ await invoke("history_list", { max_chars_per_item: 50000 });
339
+ });
208
340
  test("Claude helper history tools reuse shared schemas, outcomes and text rendering from a supplied path", async (t) => {
209
341
  const root = mkdtempSync(join(tmpdir(), "claude-history-"));
210
342
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,330 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, writeFile, appendFile, mkdir, readFile, rm, stat } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { zstdCompressSync } from "node:zlib";
6
+ import { test } from "node:test";
7
+ import { readCodexHistory } from "../plugins/codex/src/history.js";
8
+ import { readCodexTranscriptState } from "../plugins/codex/src/transcript.js";
9
+ import { allItems, eventDocument } from "../src/history/history.js";
10
+ import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
11
+ /* Producer-shaped synthetic fixtures, not captured/private transcripts.
12
+ * Frozen official rust-v0.160.1, d27764b82f7118f674371e6d6e76271d9d606edb:
13
+ * - history/src/{lib.rs,rollout_payload.rs}: flattened JSONL envelope, top-level
14
+ * metadata, raw replacement_history + aligned replacement_history_metadata.
15
+ * - protocol/src/{protocol.rs,models.rs,items.rs,mcp.rs}: exact case/field shapes;
16
+ * item_completed's TurnItem is PascalCase; McpToolCall fields are camelCase;
17
+ * legacy MCP Result uses {Ok:{...}}/{Err:string}, not flattened MCP fields.
18
+ * - rollout/src/{ordinal.rs,policy.rs,compression.rs}: legacy omits ordinals,
19
+ * paginated uses native (possibly gapped) ordinals, .jsonl.zst decoded offsets.
20
+ * - thread-store/src/local/{rollout_lineage.rs,revert_thread.rs}: history_base
21
+ * is an exclusive physical rollout-ID + ordinal + decoded byte coordinate;
22
+ * replacement filename has stable thread ID and distinct _rollout-id suffix.
23
+ * - core/src/agent/control_tests.rs: paginated full-history children COPY only
24
+ * inference context and mark subagent_history_start_ordinal, not history_base.
25
+ */
26
+ const ROOT = "019a0000-0000-7000-8000-000000000001";
27
+ const CHILD = "019a0000-0000-7000-8000-000000000002";
28
+ const FORK = "019a0000-0000-7000-8000-000000000003";
29
+ const REVERT = "019a0000-0000-7000-8000-000000000004";
30
+ const W0 = "019a0000-0000-7000-8000-000000000010";
31
+ const W1 = "019a0000-0000-7000-8000-000000000011";
32
+ const W2 = "019a0000-0000-7000-8000-000000000012";
33
+ const WC = "019a0000-0000-7000-8000-000000000013";
34
+ const AT = "2026-10-06T01:02:03.000Z";
35
+ const row = (type, payload, ordinal, metadata) => ({ timestamp: AT, ...(ordinal === undefined ? {} : { ordinal }), type, payload, ...(metadata ? { metadata } : {}) });
36
+ function meta(id = ROOT, extra = {}) {
37
+ return { session_id: ROOT, id, timestamp: AT, cwd: "/workspace/native", originator: "codex_cli_rs", cli_version: "0.160.1", source: "cli", model_provider: "openai", base_instructions: { text: "base" }, history_mode: "paginated", context_window: { window_id: W0 }, ...extra };
38
+ }
39
+ function settings(model) {
40
+ return { model, model_provider_id: "openai", approval_policy: "on-request", approvals_reviewer: "user", permission_profile: { type: "managed", file_system: { type: "restricted", entries: [] }, network: "restricted" }, cwd: "/workspace/native", collaboration_mode: { mode: "default", settings: { model, reasoning_effort: null, developer_instructions: null } }, disabled_plugin_ids: [] };
41
+ }
42
+ function turnContext(model) {
43
+ return { turn_id: "turn-1", cwd: "/workspace/native", approval_policy: "on-request", sandbox_policy: { type: "read-only" }, model, summary: "auto" };
44
+ }
45
+ const message = (role, text, id = `msg-${role}`) => ({ type: "message", id, role, content: [{ type: role === "assistant" ? "output_text" : "input_text", text }] });
46
+ const completed = (item, thread = ROOT) => ({ type: "item_completed", thread_id: thread, turn_id: "turn-1", item, started_at_ms: 1791248523000, completed_at_ms: 1791248524000 });
47
+ const command = (id, extra = {}) => ({ type: "CommandExecution", id, command: ["bash", "-lc", "printf output"], cwd: "file:///workspace/native", parsed_cmd: [], source: "agent", status: "failed", stdout: "partial", stderr: "error", aggregated_output: "partial\nerror", exit_code: 2, duration: { secs: 0, nanos: 1000000 }, formatted_output: "partial\nerror", ...extra });
48
+ function compact(window, previous, number, replacement = []) {
49
+ return { message: "", replacement_history: replacement, replacement_history_metadata: replacement.map(() => ({ client_authored: false })), window_number: number, first_window_id: W0, previous_window_id: previous, window_id: window, compaction_response_id: null, latest_token_usage_record: null };
50
+ }
51
+ const jsonl = (rows) => rows.map((r) => JSON.stringify(r) + "\n").join("");
52
+ const nativeName = (thread, rollout) => `rollout-2026-10-06T01-02-03-${thread}${rollout ? `_${rollout}` : ""}.jsonl`;
53
+ async function fixture(t) {
54
+ const home = await mkdtemp(join(tmpdir(), "notesoup-codex-history-test-"));
55
+ t.after(() => rm(home, { recursive: true, force: true }));
56
+ const day = join(home, "sessions", "2026", "10", "06");
57
+ await mkdir(day, { recursive: true });
58
+ return { home, day, path: join(day, nativeName(ROOT)) };
59
+ }
60
+ test("root: raw messages, top-level envelope metadata, native tool pairing and no display duplicates", async (t) => {
61
+ const f = await fixture(t);
62
+ await writeFile(f.path, jsonl([
63
+ row("session_meta", meta(), 0),
64
+ row("turn_context", turnContext("gpt-5.4"), 1),
65
+ row("response_item", message("system", "system context"), 2),
66
+ row("response_item", message("developer", "developer context"), 3, { client_authored: true, user_input_order: 1 }),
67
+ row("response_item", message("user", "please run this"), 4),
68
+ row("event_msg", completed({ type: "UserMessage", id: "user-ui", content: [{ type: "text", text: "please run this", text_elements: [] }] }), 5),
69
+ row("response_item", { type: "function_call", name: "exec_command", arguments: '{"cmd":"printf output"}', call_id: "cmd-1" }, 6),
70
+ row("event_msg", completed(command("cmd-1")), 7),
71
+ row("response_item", { type: "function_call_output", call_id: "cmd-1", output: "partial\nerror" }, 8),
72
+ row("response_item", message("assistant", "finished", "a1"), 9),
73
+ row("event_msg", completed({ type: "AgentMessage", id: "a1", content: [{ type: "Text", text: "finished" }], phase: "final_answer" }), 10),
74
+ ]));
75
+ const before = await readFile(f.path), info = await stat(f.path);
76
+ const result = await readCodexHistory({ transcriptPath: f.path, threadId: ROOT });
77
+ assert.equal(result.threadId, ROOT);
78
+ assert.equal(result.rootSessionId, ROOT);
79
+ assert.equal(result.model, "gpt-5.4");
80
+ assert.equal(result.currentWindowId, W0);
81
+ assert.equal(result.currentWindowNumber, 0);
82
+ assert.equal(result.firstWindowId, W0);
83
+ assert.equal(result.previousWindowId, undefined);
84
+ const { projection } = result, items = allItems(projection);
85
+ assert.deepEqual(items.map((i) => i.seq), [3, 4, 5, 7, 10]);
86
+ assert.deepEqual(items.map((i) => i.role), ["context", "context", "user", "tool", "assistant"]);
87
+ const tool = await historyRead.execute({ seq: 7 }, projection);
88
+ assert.ok(tool.ok);
89
+ assert.equal(tool.data.tool, "exec_command");
90
+ assert.equal(tool.data.tool_status, "error");
91
+ assert.match(historyRead.render(tool), /printf output/);
92
+ assert.match(historyRead.render(tool), /partial\nerror/);
93
+ assert.equal(tool.data.output_truncated, undefined);
94
+ assert.equal(tool.data.nested_calls, undefined);
95
+ const paired = await historyRead.execute({ seq: 9 }, projection);
96
+ assert.equal(paired.ok, false);
97
+ assert.match(historyRead.render(paired), /read seq 7 instead/);
98
+ const omitted = await historyRead.execute({ seq: 6 }, projection);
99
+ assert.match(historyRead.render(omitted), /holds nothing/);
100
+ const page = await historyList.execute({ query: "printf output" }, projection);
101
+ assert.ok(page.ok);
102
+ assert.equal(page.data.items.length, 1);
103
+ assert.match(historyList.render(page), /seq 7/);
104
+ assert.deepEqual(await readFile(f.path), before);
105
+ assert.equal((await stat(f.path)).mtimeMs, info.mtimeMs);
106
+ });
107
+ test("two native checkpoints retain old raw history; replacement_history is not new dialogue", async (t) => {
108
+ const f = await fixture(t);
109
+ const prefix = [row("session_meta", meta(), 0), row("response_item", message("user", "old raw text"), 1), row("response_item", message("assistant", "old answer"), 2)];
110
+ await writeFile(f.path, jsonl(prefix));
111
+ const first = await readCodexHistory({ transcriptPath: f.path, threadId: ROOT });
112
+ await appendFile(f.path, jsonl([
113
+ row("compacted", compact(W1, W0, 1, [message("user", "COPIED CHECKPOINT TEXT")]), 3),
114
+ row("event_msg", completed({ type: "ContextCompaction", id: "ui-compact" }), 4),
115
+ row("response_item", message("user", "middle text"), 5),
116
+ row("compacted", compact(W2, W1, 2), 6),
117
+ row("response_item", message("assistant", "current text"), 7),
118
+ ]));
119
+ const second = await readCodexHistory({ transcriptPath: f.path, threadId: ROOT });
120
+ assert.equal(second.currentWindowId, W2);
121
+ assert.equal(second.currentWindowNumber, 2);
122
+ assert.equal(second.previousWindowId, W1);
123
+ assert.equal(second.firstWindowId, W0);
124
+ assert.deepEqual(allItems(second.projection).filter((i) => i.seq <= 3), allItems(first.projection));
125
+ assert.doesNotMatch(allItems(second.projection).map(eventDocument).join("\n"), /COPIED CHECKPOINT TEXT/);
126
+ const windows = await historyWindows.execute({}, second.projection, second.threadId);
127
+ assert.ok(windows.ok);
128
+ assert.equal(windows.data.session_id, ROOT);
129
+ assert.deepEqual(windows.data.windows.map((w) => [w.window_id, w.first_seq, w.last_seq]), [
130
+ [`codex:${ROOT}:${W0}`, 2, 3], [`codex:${ROOT}:${W1}`, 4, 6], [`codex:${ROOT}:${W2}`, 7, 8],
131
+ ]);
132
+ const previous = await historyList.execute({ window_id: "@previous", roles: ["user"] }, second.projection);
133
+ assert.match(historyList.render(previous), /middle text/);
134
+ const old = await historyRead.execute({ seq: 2 }, second.projection);
135
+ assert.match(historyRead.render(old), /old raw text/);
136
+ const { projection: _projection, ...facts } = second;
137
+ assert.deepEqual(await readCodexTranscriptState({ transcriptPath: f.path, threadId: ROOT }), facts);
138
+ assert.deepEqual(await readCodexHistory({ transcriptPath: f.path, threadId: ROOT }), second);
139
+ });
140
+ test("legacy source coordinates stay append-stable including a pending call and incomplete/valid JSON append tails", async (t) => {
141
+ const f = await fixture(t);
142
+ const head = jsonl([
143
+ row("session_meta", meta(ROOT, { history_mode: "legacy" })),
144
+ row("response_item", { type: "function_call", call_id: "pending", name: "lookup", arguments: '{"q":"needle"}' }),
145
+ ]);
146
+ await writeFile(f.path, head + '{"timestamp":');
147
+ const source = { transcriptPath: f.path, threadId: ROOT };
148
+ const pending = await readCodexHistory(source);
149
+ assert.equal(allItems(pending.projection)[0]?.execution?.status, "unfinished");
150
+ const result = row("response_item", { type: "function_call_output", call_id: "pending", output: [{ type: "input_text", text: "answer" }, { type: "input_image", image_url: "data:omitted" }] });
151
+ await writeFile(f.path, head + JSON.stringify(result));
152
+ assert.deepEqual(await readCodexHistory(source), pending); // JSON without delimiter is not committed
153
+ await appendFile(f.path, "\n");
154
+ const complete = await readCodexHistory(source);
155
+ assert.equal(allItems(complete.projection)[0]?.seq, 2);
156
+ assert.equal(allItems(complete.projection)[0]?.execution?.status, "ok");
157
+ assert.match(eventDocument(allItems(complete.projection)[0]), /answer\n\[Codex image content omitted\]/);
158
+ await appendFile(f.path, jsonl([row("response_item", message("assistant", "later"))]));
159
+ assert.deepEqual(allItems((await readCodexHistory(source)).projection).slice(0, 1), allItems(complete.projection));
160
+ });
161
+ test("paginated native ordinal gaps never become mutable display ranks", async (t) => {
162
+ const f = await fixture(t);
163
+ await writeFile(f.path, jsonl([row("session_meta", meta(), 0), row("response_item", message("user", "one"), 20), row("response_item", message("assistant", "two"), 49)]));
164
+ const result = await readCodexHistory({ transcriptPath: f.path, threadId: ROOT });
165
+ assert.deepEqual(allItems(result.projection).map((i) => i.seq), [21, 50]);
166
+ await appendFile(f.path, jsonl([row("response_item", message("user", "three"), 100)]));
167
+ const appended = await readCodexHistory({ transcriptPath: f.path, threadId: ROOT });
168
+ assert.deepEqual(allItems(appended.projection).slice(0, 2), allItems(result.projection));
169
+ assert.equal(appended.projection.highestSeq, 101);
170
+ });
171
+ test("fork + reverted physical lineage resolves only bounded ancestry, including archived zstd", async (t) => {
172
+ const f = await fixture(t);
173
+ const ancestor = jsonl([row("session_meta", meta(), 0), row("response_item", message("user", "父前缀 🦈"), 1), row("response_item", message("assistant", "kept answer"), 2)]);
174
+ const archived = join(f.home, "archived_sessions");
175
+ await mkdir(archived);
176
+ await writeFile(join(archived, nativeName(ROOT) + ".zst"), zstdCompressSync(Buffer.from(ancestor + jsonl([row("response_item", message("assistant", "EXCLUDED ROOT SUFFIX"), 3)]))));
177
+ const base = { thread_id: ROOT, end_ordinal_exclusive: 3, end_byte_offset: Buffer.byteLength(ancestor) };
178
+ const forkPath = join(f.day, nativeName(FORK));
179
+ const forkPrefix = jsonl([
180
+ row("session_meta", meta(FORK, { forked_from_id: ROOT, forked_from_ordinal_exclusive: 3, history_base: base, context_window: { window_id: WC } }), 3),
181
+ row("response_item", message("user", "fork-local kept"), 4),
182
+ ]);
183
+ await writeFile(forkPath, forkPrefix + jsonl([row("response_item", message("assistant", "EXCLUDED FORK SUFFIX"), 5)]));
184
+ // Same thread ID, NEW physical rollout ID, cutoff addresses the prior file.
185
+ const replacementPath = join(f.day, nativeName(FORK, REVERT));
186
+ await writeFile(replacementPath, jsonl([
187
+ row("session_meta", meta(FORK, { forked_from_id: ROOT, forked_from_ordinal_exclusive: 3, history_base: { thread_id: FORK, end_ordinal_exclusive: 5, end_byte_offset: Buffer.byteLength(forkPrefix) }, context_window: { window_id: WC } }), 5),
188
+ row("response_item", message("assistant", "new branch"), 6),
189
+ ]));
190
+ await writeFile(join(f.day, nativeName(CHILD)), "THIS SIBLING MUST NEVER BE PARSED\n");
191
+ const result = await readCodexHistory({ transcriptPath: replacementPath, threadId: FORK });
192
+ const text = allItems(result.projection).map(eventDocument).join("\n");
193
+ assert.match(text, /父前缀 🦈/);
194
+ assert.match(text, /fork-local kept/);
195
+ assert.match(text, /new branch/);
196
+ assert.doesNotMatch(text, /EXCLUDED|SIBLING/);
197
+ assert.deepEqual(allItems(result.projection).map((i) => i.seq), [2, 3, 5, 7]);
198
+ assert.equal(result.currentWindowId, WC);
199
+ assert.equal(result.threadId, FORK);
200
+ assert.ok(result.projection.windows.every((w) => w.windowId.startsWith(`codex:${FORK}:`)));
201
+ });
202
+ test("child root session_id isn't thread identity; copied inference prefix isn't child dialogue", async (t) => {
203
+ const f = await fixture(t), path = join(f.day, nativeName(CHILD));
204
+ await writeFile(path, jsonl([
205
+ row("session_meta", meta(CHILD, { parent_thread_id: ROOT, forked_from_id: ROOT, source: { subagent: { thread_spawn: { parent_thread_id: ROOT, depth: 1, agent_path: "/root/worker", agent_nickname: "worker", agent_role: "default" } } }, subagent_history_start_ordinal: 3, context_window: { window_id: WC } }), 0),
206
+ row("response_item", message("user", "INHERITED MODEL CONTEXT"), 1, { inherited_user_message: true }),
207
+ row("response_item", message("developer", "INHERITED DEVELOPER"), 2),
208
+ row("event_msg", { type: "thread_settings_applied", thread_id: CHILD, thread_settings: settings("child-model") }, 3),
209
+ row("response_item", message("user", "child task"), 4),
210
+ ]));
211
+ const result = await readCodexHistory({ transcriptPath: path, threadId: CHILD });
212
+ assert.equal(result.rootSessionId, ROOT);
213
+ assert.equal(result.threadId, CHILD);
214
+ const windows = await historyWindows.execute({}, result.projection, result.threadId);
215
+ assert.ok(windows.ok);
216
+ assert.equal(windows.data.session_id, CHILD);
217
+ assert.equal(result.model, "child-model");
218
+ assert.equal(result.currentWindowId, WC);
219
+ assert.doesNotMatch(allItems(result.projection).map(eventDocument).join("\n"), /INHERITED/);
220
+ assert.equal(allItems(result.projection).at(-1)?.seq, 5);
221
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: ROOT }), /not requested threadId.*session_id is root-scoped/);
222
+ });
223
+ test("custom calls, MCP error envelopes, standalone terminal facts and opaque omissions", async (t) => {
224
+ const f = await fixture(t);
225
+ await writeFile(f.path, jsonl([
226
+ row("session_meta", meta(ROOT, { history_mode: "legacy" })),
227
+ row("response_item", { type: "custom_tool_call", call_id: "patch", name: "apply_patch", input: "*** Begin Patch\n*** End Patch" }),
228
+ row("response_item", { type: "custom_tool_call_output", call_id: "patch", output: "patched" }),
229
+ row("response_item", { type: "function_call", call_id: "mcp-1", name: "mcp__repo__read", arguments: '{"path":"nope"}' }),
230
+ row("event_msg", { type: "mcp_tool_call_end", call_id: "mcp-1", invocation: { server: "repo", tool: "read", arguments: { path: "nope" } }, duration: { secs: 0, nanos: 1 }, result: { Ok: { content: [{ type: "text", text: "not found" }], isError: true } } }),
231
+ row("response_item", { type: "function_call_output", call_id: "mcp-1", output: "not found" }),
232
+ row("event_msg", completed(command("user-shell", { source: "user_shell" }))),
233
+ row("response_item", { type: "reasoning", summary: [{ type: "summary_text", text: "recorded summary" }], encrypted_content: "SECRET OPAQUE BYTES" }),
234
+ row("response_item", { type: "function_call", call_id: "bad-json", name: "bad", arguments: "{broken" }),
235
+ ]));
236
+ const { projection } = await readCodexHistory({ transcriptPath: f.path, threadId: ROOT });
237
+ const items = allItems(projection);
238
+ assert.equal(items[0]?.execution?.arguments?.input, "*** Begin Patch\n*** End Patch");
239
+ assert.equal(items[1]?.execution?.status, "error");
240
+ assert.equal(items[2]?.execution?.name, "terminal");
241
+ assert.equal(items[2]?.execution?.status, "error");
242
+ assert.match(eventDocument(items[2]), /partial\nerror/);
243
+ assert.match(eventDocument(items[3]), /recorded summary/);
244
+ assert.doesNotMatch(items.map(eventDocument).join("\n"), /SECRET OPAQUE BYTES/);
245
+ assert.equal(items.at(-1)?.execution?.arguments?.raw_arguments, "{broken");
246
+ });
247
+ test("native lifecycle and hook-runtime persisted output use wire spellings and shared raw identities", async (t) => {
248
+ const f = await fixture(t);
249
+ // From protocol.rs EventMsg serde renames and hook_runtime.rs record_pending_input:
250
+ // raw FunctionCallOutput(id/name, no call_id) -> ItemCompleted(FunctionCallOutput).
251
+ // HookStarted/HookCompleted themselves are transient in rollout/src/policy.rs.
252
+ await writeFile(f.path, jsonl([
253
+ row("session_meta", meta(), 0),
254
+ row("event_msg", { type: "thread_settings_applied", thread_id: ROOT, thread_settings: settings("current-settings-model") }, 1),
255
+ row("event_msg", { type: "task_started", turn_id: "turn-1", model_context_window: 272000, collaboration_mode_kind: "default" }, 2),
256
+ row("response_item", { ...message("developer", "hook additional context", "hook-context"), internal_chat_message_metadata_passthrough: { content_item_kinds: ["hooks.additional_context"] } }, 3),
257
+ row("response_item", { type: "function_call_output", id: "hook-result", name: "hook_tool", output: "hook output only once" }, 4),
258
+ row("event_msg", completed({ type: "FunctionCallOutput", id: "hook-result", name: "hook_tool", output: "hook output only once" }), 5),
259
+ row("response_item", { type: "function_call", call_id: "mcp-native", name: "mcp__repo__read", arguments: '{"path":"x"}' }, 6),
260
+ row("response_item", { type: "function_call_output", call_id: "mcp-native", output: "MCP wire error only once" }, 7),
261
+ row("event_msg", completed({ type: "McpToolCall", id: "mcp-native", server: "repo", tool: "read", arguments: { path: "x" }, status: "failed", result: { content: [{ type: "text", text: "MCP wire error only once" }], isError: true }, error: { message: "failure" } }), 8),
262
+ row("response_item", message("assistant", "final answer only once"), 9),
263
+ row("event_msg", { type: "task_complete", turn_id: "turn-1", last_agent_message: "final answer only once" }, 10),
264
+ row("turn_context", turnContext("frozen-companion-model"), 11),
265
+ ]));
266
+ const result = await readCodexHistory({ transcriptPath: f.path, threadId: ROOT });
267
+ assert.equal(result.model, "current-settings-model");
268
+ const items = allItems(result.projection), text = items.map(eventDocument).join("\n");
269
+ assert.match(text, /Codex task_started/);
270
+ assert.match(text, /Codex task_complete/);
271
+ assert.equal(text.match(/hook output only once/g)?.length, 1);
272
+ assert.equal(text.match(/MCP wire error only once/g)?.length, 1);
273
+ assert.equal(text.match(/final answer only once/g)?.length, 1);
274
+ assert.equal(items.find((i) => i.seq === 7)?.execution?.status, "error");
275
+ assert.equal(items.find((i) => i.seq === 5)?.execution?.name, "hook_tool");
276
+ });
277
+ test("header-only native facts exist before any compaction, but absent facts are never fabricated", async (t) => {
278
+ const f = await fixture(t), source = { transcriptPath: f.path, threadId: ROOT };
279
+ await writeFile(f.path, jsonl([row("session_meta", meta(), 0)]));
280
+ assert.equal((await readCodexTranscriptState(source)).currentWindowId, W0);
281
+ assert.equal((await readCodexHistory(source)).projection.windows.length, 1);
282
+ await writeFile(f.path, jsonl([row("session_meta", meta(ROOT, { context_window: null }), 0)]));
283
+ const facts = await readCodexTranscriptState(source);
284
+ assert.equal(facts.currentWindowId, undefined);
285
+ assert.equal(facts.currentWindowNumber, undefined);
286
+ assert.equal(facts.firstWindowId, undefined);
287
+ assert.equal((await readCodexHistory(source)).projection.windows.length, 0);
288
+ await appendFile(f.path, jsonl([row("response_item", message("user", "unaddressable"), 1)]));
289
+ await assert.rejects(readCodexHistory(source), /native window identity missing/);
290
+ });
291
+ test("committed malformed, unsupported, unsafe and unproved native shapes refuse explicitly", async (t) => {
292
+ const f = await fixture(t), source = { transcriptPath: f.path, threadId: ROOT };
293
+ await assert.rejects(readCodexHistory(source), /ENOENT/);
294
+ const head = row("session_meta", meta(), 0);
295
+ for (const [rows, expected] of [
296
+ [[row("session_meta", meta(ROOT, { cli_version: "0.161.0" }), 0)], /Unsupported Codex producer/],
297
+ [[head, row("future_record", {}, 1)], /Unsupported Codex rollout record/],
298
+ [[head, row("response_item", { type: "future_item" }, 1)], /Unsupported Codex response/],
299
+ [[head, row("response_item", message("user", "x"))], /paginated record ordinal/],
300
+ [[head, row("response_item", message("user", "x"), 0)], /non-increasing/],
301
+ [[head, row("response_item", message("user", "x"), Number.MAX_SAFE_INTEGER + 1)], /unsafe/],
302
+ [[head, row("response_item", { item: message("user", "wrong envelope") }, 1)], /response_item.type/],
303
+ [[head, row("compacted", { ...compact(W1, W0, 1), replacement_history_metadata: [{}] }, 1)], /metadata alignment/],
304
+ [[head, row("event_msg", { type: "thread_rolled_back", num_turns: 1 }, 1)], /thread_rolled_back/],
305
+ [[head, row("session_meta", meta(CHILD), 1)], /copied session_meta ancestry/],
306
+ ]) {
307
+ await writeFile(f.path, jsonl(rows));
308
+ await assert.rejects(readCodexHistory(source), expected);
309
+ }
310
+ await writeFile(f.path, jsonl([head]) + "{broken}\n");
311
+ await assert.rejects(readCodexHistory(source), /Malformed committed.*line 2/);
312
+ });
313
+ test("missing or mismatched ancestry and unsafe cutoff pairs never fall back to concatenation", async (t) => {
314
+ const f = await fixture(t), path = join(f.day, nativeName(CHILD));
315
+ const ancestor = jsonl([row("session_meta", meta(), 0), row("response_item", message("user", "kept"), 1)]);
316
+ const base = { thread_id: ROOT, end_ordinal_exclusive: 2, end_byte_offset: Buffer.byteLength(ancestor) };
317
+ const writeChild = async (history_base, extra = {}) => writeFile(path, jsonl([row("session_meta", meta(CHILD, { history_base, forked_from_id: ROOT, ...extra }), history_base.end_ordinal_exclusive)]));
318
+ await writeChild(base);
319
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }), /no local source file/);
320
+ await writeFile(f.path, ancestor);
321
+ await writeChild({ ...base, end_byte_offset: base.end_byte_offset - 1 });
322
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }), /complete decoded JSONL boundary/);
323
+ await writeChild({ ...base, end_ordinal_exclusive: 3 });
324
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }), /ordinal cutoff is beyond the proved prefix/);
325
+ await writeChild(base, { forked_from_ordinal_exclusive: 1 });
326
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }), /exceeds the logical fork cutoff/);
327
+ await writeChild(base);
328
+ await writeFile(f.path, jsonl([row("session_meta", meta(FORK), 0), row("response_item", message("user", "kept"), 1)]));
329
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }), /identity mismatch/);
330
+ });
@@ -0,0 +1 @@
1
+ export {};