notesoup 0.56.0 → 0.57.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 (59) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/pi/marker.d.ts +4 -2
  3. package/dist/plugins/pi/marker.js +18 -8
  4. package/dist/plugins/pi/reset/lifecycle.js +6 -0
  5. package/dist/plugins/pi/runtime.js +8 -8
  6. package/dist/plugins/pi/text.js +1 -1
  7. package/dist/src/history/claude.d.ts +2 -0
  8. package/dist/src/history/claude.js +13 -2
  9. package/dist/src/history/codex-transcript.d.ts +15 -3
  10. package/dist/src/history/codex-transcript.js +57 -21
  11. package/dist/src/history/codex.d.ts +4 -2
  12. package/dist/src/history/codex.js +3 -3
  13. package/dist/src/history/corpus.d.ts +8 -1
  14. package/dist/src/history/corpus.js +17 -1
  15. package/dist/src/history/history.d.ts +16 -10
  16. package/dist/src/history/history.js +9 -9
  17. package/dist/src/history/local.d.ts +2 -0
  18. package/dist/src/history/local.js +35 -38
  19. package/dist/src/history/prefilter.d.ts +5 -0
  20. package/dist/src/history/prefilter.js +95 -0
  21. package/dist/src/history/query.d.ts +29 -27
  22. package/dist/src/history/query.js +82 -34
  23. package/dist/src/history/summary-cache.d.ts +10 -0
  24. package/dist/src/history/summary-cache.js +129 -0
  25. package/dist/src/tools/history.js +31 -20
  26. package/dist/test/agent-loop.test.js +62 -27
  27. package/dist/test/codex-history.test.js +90 -4
  28. package/dist/test/codex-plugin.test.js +6 -2
  29. package/dist/test/history-corpus.test.js +221 -33
  30. package/dist/test/history-prefilter.test.d.ts +1 -0
  31. package/dist/test/history-prefilter.test.js +174 -0
  32. package/dist/test/history-summary-cache.test.d.ts +1 -0
  33. package/dist/test/history-summary-cache.test.js +297 -0
  34. package/dist/test/history.integration.test.js +87 -52
  35. package/dist/test/marker.test.js +46 -15
  36. package/dist/test/model-facing-text.test.js +1 -1
  37. package/dist/test/reset-lifecycle.test.js +4 -6
  38. package/docs/architecture.md +1 -1
  39. package/docs/history-sessions.md +26 -2
  40. package/docs/reset-lifecycle.md +4 -4
  41. package/docs/tool-results.md +4 -2
  42. package/package.json +1 -1
  43. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  44. package/plugins/claude/dist/claude/helper.js +425 -122
  45. package/plugins/codex/dist/codex/notesoup.js +423 -123
  46. package/plugins/pi/marker.ts +18 -12
  47. package/plugins/pi/reset/lifecycle.ts +5 -0
  48. package/plugins/pi/runtime.ts +8 -8
  49. package/plugins/pi/text.ts +1 -1
  50. package/src/history/claude.ts +16 -2
  51. package/src/history/codex-transcript.ts +52 -17
  52. package/src/history/codex.ts +5 -5
  53. package/src/history/corpus.ts +19 -2
  54. package/src/history/history.ts +11 -11
  55. package/src/history/local.ts +34 -38
  56. package/src/history/prefilter.ts +86 -0
  57. package/src/history/query.ts +77 -33
  58. package/src/history/summary-cache.ts +119 -0
  59. package/src/tools/history.ts +33 -20
@@ -3,8 +3,8 @@ import { Type } from "typebox";
3
3
  import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "./output.js";
4
4
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
5
5
  import { historyRoles, searchQuery } from "./schema.js";
6
- import { HistoryPageSchema, corpusSelection, selectCorpusPage, selectPage, sessionRepresentative } from "../history/query.js";
7
- import { currentHistory, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity } from "../history/corpus.js";
6
+ import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage } from "../history/query.js";
7
+ import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity } from "../history/corpus.js";
8
8
  import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema } from "../history/history.js";
9
9
  /** One read: identity, tool summary and a flat document slice. */
10
10
  const HistoryReadDataSchema = Type.Object({
@@ -43,24 +43,29 @@ function renderPageItem(item) {
43
43
  function renderFoldedRow(row) {
44
44
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
45
45
  const identity = row.session === undefined ? {} : { session: row.session };
46
- const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, from: "oldest", roles: ["tool", "context"] })}`;
46
+ const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
47
47
  return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
48
48
  }
49
49
  function renderPage(page) {
50
50
  // An empty selection has no anchors either, so it would otherwise render as nothing at all.
51
- if (page.items.length === 0)
51
+ if (page.items.length === 0 && !page.folded_after)
52
52
  return `${page.notice ?? ""}No events match these filters.`;
53
- const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
53
+ const body = [...page.items.flatMap((item) => [...(item.folded_before ? [renderFoldedRow(item.folded_before)] : []), renderPageItem(item)]), ...(page.folded_after ? [renderFoldedRow(page.folded_after)] : [])].join("\n\n");
54
+ if (isMultiPage(page)) {
55
+ const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
56
+ return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
57
+ }
58
+ const first = page.items[0];
59
+ const last = page.items.at(-1);
54
60
  const cursors = [
55
- page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
56
- page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
61
+ page.has_older ? `→ older: ${JSON.stringify({ ...(first.session === undefined ? {} : { session: first.session }), before_seq: first.seq })}` : "",
62
+ page.has_newer ? `→ newer: ${JSON.stringify({ ...(last.session === undefined ? {} : { session: last.session }), after_seq: last.seq })}` : "",
57
63
  ].filter((line) => line !== "");
58
64
  return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
59
65
  }
60
66
  function renderRead(data) {
61
67
  const tool = toolHeader(data);
62
- const afterSeq = data.seq - 10;
63
- const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
68
+ const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), after_seq: Math.max(0, data.seq - 10), before_seq: data.seq + 10 })})`;
64
69
  return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
65
70
  }
66
71
  const plainText = (text) => text;
@@ -71,11 +76,11 @@ export const historyListParameters = Type.Object({
71
76
  query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
72
77
  roles: historyRoles(),
73
78
  before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
74
- after_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
79
+ after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
75
80
  since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
76
81
  until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
77
- from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
78
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
82
+ from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional) Which end `limit` counts from: newest or oldest (default oldest when `after_seq` is set, else newest). Results stay oldest first." })),
83
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
79
84
  max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
80
85
  }, { additionalProperties: false });
81
86
  export const historyList = {
@@ -104,23 +109,29 @@ export const historyList = {
104
109
  const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
105
110
  if (!queries)
106
111
  sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
107
- const loaded = [];
112
+ const representative = !queries && scoped.data.roles === undefined && scoped.data.since === undefined && scoped.data.until === undefined;
113
+ const collector = new CorpusCollector(scoped.data);
114
+ let qualifying = 0;
108
115
  const notices = [];
109
- for (const session of sessions) {
110
- const result = await loadHistorySession(session, queries);
116
+ let unvisited = false;
117
+ for (const [index, session] of sessions.entries()) {
118
+ const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
111
119
  if (!result.ok || !result.data)
112
120
  continue;
113
- if (!queries && !sessionRepresentative(result.data.projection, scoped.data))
121
+ const added = "projection" in result.data ? collector.add(sessionIdentity(session), result.data.projection) : collector.addRepresentative(sessionIdentity(session), result.data.event);
122
+ if (!added)
114
123
  continue;
115
- loaded.push({ session: sessionIdentity(session), projection: result.data.projection });
124
+ qualifying++;
116
125
  if (result.data.notice)
117
126
  notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
118
- if (!queries && loaded.length >= Math.max(1, params.limit ?? 20))
127
+ if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
128
+ unvisited = index + 1 < sessions.length;
119
129
  break;
130
+ }
120
131
  }
121
132
  const notice = notices.length ? { notice: notices.join("") } : {};
122
- const result = selectCorpusPage(loaded, scoped.data, (page) => fits({ ...page, ...notice }), maxChars);
123
- return result.ok ? success({ ...result.data, ...notice }) : result;
133
+ const result = collector.page((page) => fits(markMultiPage({ ...page, ...notice })), maxChars, unvisited);
134
+ return result.ok ? success(markMultiPage({ ...result.data, ...notice })) : result;
124
135
  }
125
136
  const target = await resolveSession(corpus, selector.data);
126
137
  if (!target.ok)
@@ -6,8 +6,9 @@ import test from "node:test";
6
6
  import { createAssistantMessageEventStream, getCurrentSystemMessage } from "@earendil-works/pi-ai";
7
7
  import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
8
  import notesoup, { createNotesoup } from "../plugins/pi/extension.js";
9
- import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, NEXT_WINDOW_PROMPT_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
9
+ import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, MARKER_TYPE, NEXT_WINDOW_PROMPT_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
10
10
  import { historyFromSession } from "../plugins/pi/history.js";
11
+ import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
11
12
  import { assertBootHistory } from "./helpers/extension.js";
12
13
  import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
13
14
  import { FORCED_CONTINUATIONS, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, warningPrompt } from "../src/budget/text.js";
@@ -235,6 +236,48 @@ function assertFreshRequest(fixture, requestIndex, oldSentinel) {
235
236
  assert.ok(body.includes(WINDOW_IDENTITY_OPEN_TAG), "the new provider request includes the fresh context-window boot");
236
237
  assert.deepEqual(continuationLinesIn(body).length, 1, "the fresh window carries exactly one reset paragraph");
237
238
  }
239
+ test("real AgentSession: turn-end markers reach tool continuations and allow one-turn lag when steering crosses the interval", async () => {
240
+ for (const seedCount of [MARKER_INTERVAL - 4, MARKER_INTERVAL - 7]) {
241
+ let starts = 0;
242
+ let fixture;
243
+ fixture = await openFixture({
244
+ compactionEnabled: false,
245
+ hook: (pi, getSession) => {
246
+ pi.on("before_agent_start", () => { starts++; });
247
+ pi.on("tool_call", async () => { await getSession().steer("MARKER_MID_RUN_USER"); });
248
+ },
249
+ script: (request) => request === 1
250
+ ? assistant(fixture, [{ type: "toolCall", id: "marker-tool", name: "get_context_remaining", arguments: {} }], "toolUse")
251
+ : assistant(fixture, [{ type: "text", text: "steered input handled" }]),
252
+ });
253
+ try {
254
+ for (let i = 0; i < seedCount; i++)
255
+ fixture.sessionManager.appendMessage(assistant(fixture, [{ type: "text", text: "seed" }]));
256
+ await fixture.session.prompt("MARKER_INITIAL_USER");
257
+ await fixture.session.waitForIdle();
258
+ assert.equal(starts, 1);
259
+ assert.equal(fixture.requests.length, 2, "the marker does not create another model request");
260
+ assert.equal(text(fixture.requests[0]).includes("notesoup:marker"), false);
261
+ assert.equal(text(fixture.requests[1]).includes("notesoup:marker"), seedCount === MARKER_INTERVAL - 4);
262
+ assert.equal(text(fixture.requests[1]).split("MARKER_MID_RUN_USER").length - 1, 1);
263
+ const branch = fixture.sessionManager.getBranch();
264
+ const markers = branch.filter((entry) => entry.type === "custom_message" && entry.customType === MARKER_TYPE);
265
+ assert.equal(markers.length, 1);
266
+ const marker = markers[0];
267
+ const markerIndex = branch.indexOf(marker);
268
+ const userIndex = branch.findIndex((entry) => entry.type === "message" && entry.message.role === "user" && JSON.stringify(entry.message.content).includes("MARKER_MID_RUN_USER"));
269
+ assert.equal(markerIndex < userIndex, seedCount === MARKER_INTERVAL - 4, "a steering-only threshold crossing is marked after its response");
270
+ assert.ok(branch.slice(0, markerIndex).some((entry) => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolCallId === "marker-tool"));
271
+ const projection = historyFromSession({ sessionManager: fixture.sessionManager });
272
+ const addressed = projection.windows.flatMap((window) => window.items).find((item) => item.text.includes("<notesoup:marker"));
273
+ assert.ok(addressed);
274
+ assert.deepEqual(marker.type === "custom_message" ? marker.details : undefined, { seq: addressed.seq });
275
+ }
276
+ finally {
277
+ fixture.close();
278
+ }
279
+ }
280
+ });
238
281
  test("real Pi codemode receives typed notes/history outcomes, including expected errors", async () => {
239
282
  let fixture;
240
283
  fixture = await openFixture({
@@ -514,7 +557,7 @@ test("real AgentSession: manual command spans its tool batch and stops at settle
514
557
  fixture.close();
515
558
  }
516
559
  });
517
- test("real AgentSession: /empty text is carried verbatim and answered after close-out", async () => {
560
+ test("real AgentSession: /empty text is close-out context and stops after reset", async () => {
518
561
  let fixture;
519
562
  const prompt = 'AFTER_CLEAR_PROMPT_SENTINEL /cm "literal text" \nsecond line';
520
563
  fixture = await openFixture({
@@ -526,21 +569,18 @@ test("real AgentSession: /empty text is carried verbatim and answered after clos
526
569
  assert.ok(text(context).includes(JSON.stringify(promptBlock(`/empty ${prompt}`)).slice(1, -1)));
527
570
  return assistant(fixture, [{ type: "toolCall", id: "prompt-wipe", name: "empty_brain", arguments: { last_word: "saved" } }], "toolUse");
528
571
  }
529
- assert.equal(request, 3);
530
- assertFreshRequest(fixture, 2, "PROMPT_RESET_OLD_SENTINEL");
531
- assertUserContent(context, [{ type: "text", text: prompt }]);
532
- return assistant(fixture, [{ type: "text", text: "prompt handled" }]);
572
+ throw new Error("command argument must not start fresh-window work");
533
573
  },
534
574
  });
535
575
  try {
536
576
  await fixture.session.prompt("PROMPT_RESET_OLD_SENTINEL");
537
577
  await fixture.session.prompt(`/empty ${prompt}`);
538
578
  await fixture.session.waitForIdle();
539
- assert.equal(fixture.requests.length, 3);
579
+ assert.equal(fixture.requests.length, 2);
540
580
  assert.equal(resetMarkers(fixture).length, 1);
541
581
  const branch = fixture.sessionManager.getBranch();
542
- const continuationIndex = branch.findIndex((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
543
- assert.deepEqual(branch.slice(continuationIndex + 1, continuationIndex + 3).map((entry) => entry.type === "custom_message" ? entry.customType : entry.type), ["notesoup/reset-last-word", CARRIED_INPUT_TYPE]);
582
+ assert.equal(branch.some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
583
+ assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("AFTER_CLEAR_PROMPT_SENTINEL"), false);
544
584
  assert.equal(fixture.notices.some(isResetSuccessNotice), false);
545
585
  }
546
586
  finally {
@@ -582,16 +622,12 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
582
622
  if (request === 1)
583
623
  assert.equal(text(context).includes("FIRST_RESET_PROMPT"), false, "the prompt belongs to the close-out, not the turn already running");
584
624
  // The close-out embeds the human's command line verbatim, so the closing turn sees
585
- // what the next window was asked to do. Only the accepted command appears.
625
+ // the command context. Only the accepted command appears.
586
626
  if (request === 2) {
587
- assert.ok(text(context).includes("FIRST_RESET_PROMPT"), "the close-out carries the command line");
627
+ assert.ok(text(context).includes(JSON.stringify(promptBlock("/fresh-window FIRST_RESET_PROMPT")).slice(1, -1)), "the close-out carries the original command line");
588
628
  assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false, "the refused repeat never enters the close-out");
589
629
  }
590
- if (request === 3) {
591
- assert.ok(text(context).includes("FIRST_RESET_PROMPT"), "the fresh window still receives the prompt");
592
- assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false);
593
- }
594
- assert.ok(request <= 3);
630
+ assert.ok(request <= 2);
595
631
  return assistant(fixture, [{ type: "text", text: "done" }]);
596
632
  },
597
633
  });
@@ -603,7 +639,8 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
603
639
  release();
604
640
  await running;
605
641
  await fixture.session.waitForIdle();
606
- assert.equal(fixture.requests.length, 3);
642
+ assert.equal(fixture.requests.length, 2);
643
+ assert.equal(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
607
644
  assert.equal(resetMarkers(fixture).length, 1);
608
645
  assert.ok(fixture.notices.some((notice) => notice.includes("Brain already being emptied")));
609
646
  }
@@ -655,15 +692,13 @@ test("real AgentSession: manual hard-reserve reset stops clean and mixed-tool tu
655
692
  }
656
693
  }
657
694
  });
658
- test("real AgentSession: overflowing /empty close-out forces a reset and retries its text only once", async () => {
695
+ test("real AgentSession: overflowing /empty close-out forces a reset and stops", async () => {
659
696
  let fixture;
660
697
  fixture = await openFixture({
661
- script: (request, context) => {
698
+ script: (request) => {
662
699
  if (request === 1)
663
700
  return assistant(fixture, [{ type: "text", text: "before overflow" }]);
664
- assert.ok(request <= 3, "an oversized carried prompt cannot loop");
665
- if (request === 3)
666
- assertUserContent(context, [{ type: "text", text: "OVERSIZED_MANUAL_PROMPT" }]);
701
+ assert.equal(request, 2, "command text must not trigger a retry");
667
702
  return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
668
703
  },
669
704
  });
@@ -671,9 +706,9 @@ test("real AgentSession: overflowing /empty close-out forces a reset and retries
671
706
  await fixture.session.prompt("MANUAL_OVERFLOW_OLD_SENTINEL");
672
707
  await fixture.session.prompt("/empty OVERSIZED_MANUAL_PROMPT");
673
708
  await fixture.session.waitForIdle();
674
- assert.equal(fixture.requests.length, 3);
709
+ assert.equal(fixture.requests.length, 2);
675
710
  assert.equal(resetMarkers(fixture).length, 1);
676
- assertFreshRequest(fixture, 2, "MANUAL_OVERFLOW_OLD_SENTINEL");
711
+ assert.equal(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
677
712
  assert.equal(resetMarkers(fixture)[0].data.origin, "forced");
678
713
  assert.ok(fixture.notices.some(isResetSuccessNotice));
679
714
  }
@@ -800,7 +835,7 @@ test("real AgentSession: user abort, synthetic aborted response, and generic err
800
835
  }
801
836
  }
802
837
  });
803
- test("real AgentSession: input during bare /empty is hidden-steered, carried with images, and answered after a safety reset", async () => {
838
+ test("real AgentSession: input during prompted /empty is hidden-steered, carried with images, and answered after a safety reset", async () => {
804
839
  let fixture;
805
840
  let started;
806
841
  let release;
@@ -819,14 +854,14 @@ test("real AgentSession: input during bare /empty is hidden-steered, carried wit
819
854
  assertUserContent(context, [{ type: "text", text: promptBlock(input) }, image]);
820
855
  return assistant(fixture, [{ type: "toolCall", id: "deferred-pressure", name: "notes_write", arguments: { address: "deferred.md", content: "saved" } }], "toolUse", { usage: usage(80_000) });
821
856
  }
822
- assert.equal(request, 3, "carried input continues instead of taking the bare-command stop");
857
+ assert.equal(request, 3, "carried input continues despite command stop policy");
823
858
  assertFreshRequest(fixture, 2, "saving notes");
824
859
  assertUserContent(context, [{ type: "text", text: input }, image]);
825
860
  return assistant(fixture, [{ type: "text", text: "deferred input answered" }]);
826
861
  },
827
862
  });
828
863
  try {
829
- const command = fixture.session.prompt("/empty");
864
+ const command = fixture.session.prompt("/empty CLOSE_OUT_CONTEXT");
830
865
  await ready;
831
866
  await fixture.session.prompt(input, { images: [image], streamingBehavior: "followUp" });
832
867
  release();
@@ -1,11 +1,13 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdtemp, writeFile, appendFile, mkdir, readFile, rm, stat } from "node:fs/promises";
2
+ import fs, { mkdtemp, writeFile, appendFile, mkdir, readFile, realpath, rm, stat, symlink, truncate } from "node:fs/promises";
3
+ import { syncBuiltinESMExports } from "node:module";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
- import { zstdCompressSync } from "node:zlib";
6
+ import zlib, { zstdCompressSync } from "node:zlib";
6
7
  import { test } from "node:test";
7
8
  import { readCodexHistory } from "../plugins/codex/src/history.js";
8
9
  import { readCodexTranscriptState } from "../plugins/codex/src/transcript.js";
10
+ import { createCodexTranscriptReader } from "../src/history/codex-transcript.js";
9
11
  import { allItems, eventDocument } from "../src/history/history.js";
10
12
  import { historyList, historyRead } from "../src/tools/history.js";
11
13
  /* Producer-shaped synthetic fixtures, not captured/private transcripts.
@@ -57,6 +59,85 @@ async function fixture(t) {
57
59
  await mkdir(day, { recursive: true });
58
60
  return { home, day, path: join(day, nativeName(ROOT)) };
59
61
  }
62
+ function countSourceReads(t) {
63
+ const files = new Map(), read = fs.readFile, decompress = zlib.zstdDecompressSync;
64
+ let decompressions = 0;
65
+ t.mock.method(fs, "readFile", (...args) => {
66
+ const path = String(args[0]);
67
+ files.set(path, (files.get(path) ?? 0) + 1);
68
+ return read(...args);
69
+ });
70
+ t.mock.method(zlib, "zstdDecompressSync", (...args) => { decompressions++; return decompress(...args); });
71
+ syncBuiltinESMExports();
72
+ t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports(); });
73
+ return { files, decompressions: () => decompressions };
74
+ }
75
+ test("request reader reuses the original compressed Buffer by canonical path and rechecks consumption limits", async (t) => {
76
+ const f = await fixture(t), path = f.path + ".zst", alias = join(f.home, "alias.jsonl.zst");
77
+ const text = jsonl([row("session_meta", meta(), 0), row("response_item", message("user", "needle ".repeat(1000)), 1)]);
78
+ const compressed = zstdCompressSync(Buffer.from(text));
79
+ await writeFile(path, compressed);
80
+ await symlink(path, alias);
81
+ const reads = countSourceReads(t), readBytes = createCodexTranscriptReader();
82
+ const [bytes, same] = await Promise.all([readBytes(path), readBytes(alias)]);
83
+ assert.equal(bytes, same);
84
+ assert.equal(bytes.toString("utf8"), text);
85
+ const result = await readCodexHistory({ transcriptPath: alias, threadId: ROOT }, readBytes);
86
+ assert.deepEqual(result.dependencies, [await realpath(path)]);
87
+ assert.equal(allItems(result.projection)[0]?.text, "needle ".repeat(1000));
88
+ await assert.rejects(readBytes(path, compressed.length - 1), /read size limit exceeded/);
89
+ await assert.rejects(readBytes(path, bytes.length - 1), /decoded size limit exceeded/);
90
+ assert.deepEqual([...reads.files.values()], [1]);
91
+ assert.equal(reads.decompressions(), 1);
92
+ // A later load must see appends; no byte cache survives in the default reader.
93
+ await writeFile(path, zstdCompressSync(Buffer.from(text + jsonl([row("response_item", message("assistant", "later"), 2)]))));
94
+ assert.equal(allItems((await readCodexHistory({ transcriptPath: path, threadId: ROOT })).projection).at(-1)?.text, "later");
95
+ assert.deepEqual([...reads.files.values()], [2]);
96
+ assert.equal(reads.decompressions(), 2);
97
+ });
98
+ test("cached source bytes still charge the aggregate decoded lineage budget", async (t) => {
99
+ const f = await fixture(t), path = join(f.day, nativeName(CHILD));
100
+ const ancestor = jsonl([row("session_meta", meta(), 0), row("response_item", message("user", "kept"), 1)]);
101
+ await writeFile(f.path, ancestor);
102
+ await writeFile(path, jsonl([row("session_meta", meta(CHILD, { history_base: { thread_id: ROOT, end_ordinal_exclusive: 2, end_byte_offset: Buffer.byteLength(ancestor) } }), 2)]));
103
+ // Sparse, uncommitted tails count against decoded resource limits, not event count.
104
+ for (const source of [path, f.path])
105
+ await truncate(source, 64 * 1024 * 1024 + 1);
106
+ const reads = countSourceReads(t), readBytes = createCodexTranscriptReader();
107
+ await readBytes(path);
108
+ await readBytes(f.path);
109
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }, readBytes), /size limit exceeded/);
110
+ assert.deepEqual([...reads.files.values()], [1, 1]);
111
+ });
112
+ test("preloaded Buffers cannot bypass metadata, cutoff, cycle or containment checks", async (t) => {
113
+ const f = await fixture(t), path = join(f.day, nativeName(CHILD));
114
+ const ancestor = jsonl([row("session_meta", meta(), 0), row("response_item", message("user", "kept"), 1)]);
115
+ const base = { thread_id: ROOT, end_ordinal_exclusive: 2, end_byte_offset: Buffer.byteLength(ancestor) };
116
+ await writeFile(f.path, ancestor);
117
+ await writeFile(path, jsonl([row("session_meta", meta(CHILD, { history_base: { ...base, end_byte_offset: base.end_byte_offset - 1 } }), 2)]));
118
+ let readBytes = createCodexTranscriptReader();
119
+ await readBytes(path);
120
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: ROOT }, readBytes), /not requested threadId/);
121
+ await readBytes(f.path);
122
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }, readBytes), /complete decoded JSONL boundary/);
123
+ await writeFile(path, jsonl([row("session_meta", meta(CHILD, { history_base: { ...base, thread_id: CHILD } }), 2)]));
124
+ readBytes = createCodexTranscriptReader();
125
+ await readBytes(path);
126
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }, readBytes), /cycle or ancestry depth/);
127
+ // Native discovery ignores symlink files, but a symlinked native directory must
128
+ // still pass canonical containment before a cached ancestor can be consumed.
129
+ const outside = join(f.home, "outside"), archived = join(f.home, "archived_sessions");
130
+ await mkdir(outside);
131
+ const escaped = join(outside, nativeName(ROOT));
132
+ await writeFile(escaped, ancestor);
133
+ await rm(f.path);
134
+ await symlink(outside, archived);
135
+ await writeFile(path, jsonl([row("session_meta", meta(CHILD, { history_base: base }), 2)]));
136
+ readBytes = createCodexTranscriptReader();
137
+ await readBytes(escaped);
138
+ await readBytes(path);
139
+ await assert.rejects(readCodexHistory({ transcriptPath: path, threadId: CHILD }, readBytes), /escapes native storage roots/);
140
+ });
60
141
  test("root: raw messages, top-level envelope metadata, native tool pairing and no display duplicates", async (t) => {
61
142
  const f = await fixture(t);
62
143
  await writeFile(f.path, jsonl([
@@ -131,7 +212,7 @@ test("two native checkpoints retain old raw history; replacement_history is not
131
212
  assert.match(historyList.render(earlier), /^seq 6 \| user\nmiddle text$/);
132
213
  const old = await historyRead.execute({ seq: 2 }, second.projection);
133
214
  assert.match(historyRead.render(old), /old raw text/);
134
- const { projection: _projection, ...facts } = second;
215
+ const { projection: _projection, dependencies: _dependencies, lineageSources: _lineageSources, ...facts } = second;
135
216
  assert.deepEqual(await readCodexTranscriptState({ transcriptPath: f.path, threadId: ROOT }), facts);
136
217
  assert.deepEqual(await readCodexHistory({ transcriptPath: f.path, threadId: ROOT }), second);
137
218
  });
@@ -186,7 +267,12 @@ test("fork + reverted physical lineage resolves only bounded ancestry, including
186
267
  row("response_item", message("assistant", "new branch"), 6),
187
268
  ]));
188
269
  await writeFile(join(f.day, nativeName(CHILD)), "THIS SIBLING MUST NEVER BE PARSED\n");
189
- const result = await readCodexHistory({ transcriptPath: replacementPath, threadId: FORK });
270
+ const reads = countSourceReads(t), readBytes = createCodexTranscriptReader();
271
+ await readBytes(replacementPath); // The local prefilter's root read is handed to strict decode.
272
+ const result = await readCodexHistory({ transcriptPath: replacementPath, threadId: FORK }, readBytes);
273
+ assert.deepEqual(result.dependencies, await Promise.all([replacementPath, forkPath, join(archived, nativeName(ROOT) + ".zst")].map((path) => realpath(path))));
274
+ assert.deepEqual([...reads.files.values()], [1, 1, 1]);
275
+ assert.equal(reads.decompressions(), 1);
190
276
  const text = allItems(result.projection).map(eventDocument).join("\n");
191
277
  assert.match(text, /父前缀 🦈/);
192
278
  assert.match(text, /fork-local kept/);
@@ -178,8 +178,12 @@ test("bundled Codex MCP reads another harness and wildcard results retain their
178
178
  assert.equal(list.isError, undefined, textOf(list));
179
179
  const page = list.structuredContent;
180
180
  assert.deepEqual(new Set(page.items.map((item) => item.session)), new Set([`codex:${ROOT}`, "pi:foreign-pi"]));
181
- assert.equal(page.page_older, null);
182
- assert.equal(page.page_newer, null);
181
+ assert.equal(page.has_older, false);
182
+ assert.equal(page.has_newer, false);
183
+ const limited = await call(client, { name: "history_list", arguments: { session: "*", query: "needle", limit: 1 }, _meta: metaFor(ROOT, ROOT) });
184
+ assert.equal(limited.structuredContent.has_older, true);
185
+ assert.match(textOf(limited), /→ more older results: narrow with since\/until/);
186
+ assert.doesNotMatch(textOf(limited), /before_seq|after_seq/);
183
187
  const invalid = await call(client, { name: "history_read", arguments: { session: "*", seq: 1 }, _meta: metaFor(ROOT, ROOT) });
184
188
  assert.equal(errorCode(invalid), "invalid_session");
185
189
  });