notesoup 0.56.1 → 0.57.1

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 (60) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/pi/entries.d.ts +0 -1
  3. package/dist/plugins/pi/entries.js +0 -1
  4. package/dist/plugins/pi/reset/lifecycle.d.ts +2 -1
  5. package/dist/plugins/pi/reset/lifecycle.js +19 -36
  6. package/dist/plugins/pi/runtime.js +14 -10
  7. package/dist/plugins/pi/text.d.ts +0 -2
  8. package/dist/plugins/pi/text.js +2 -6
  9. package/dist/src/history/claude.d.ts +2 -0
  10. package/dist/src/history/claude.js +13 -2
  11. package/dist/src/history/codex-transcript.d.ts +15 -3
  12. package/dist/src/history/codex-transcript.js +57 -21
  13. package/dist/src/history/codex.d.ts +4 -2
  14. package/dist/src/history/codex.js +3 -3
  15. package/dist/src/history/corpus.d.ts +8 -1
  16. package/dist/src/history/corpus.js +17 -1
  17. package/dist/src/history/history.d.ts +16 -10
  18. package/dist/src/history/history.js +9 -9
  19. package/dist/src/history/local.d.ts +2 -0
  20. package/dist/src/history/local.js +35 -38
  21. package/dist/src/history/prefilter.d.ts +5 -0
  22. package/dist/src/history/prefilter.js +95 -0
  23. package/dist/src/history/query.d.ts +29 -27
  24. package/dist/src/history/query.js +82 -34
  25. package/dist/src/history/summary-cache.d.ts +10 -0
  26. package/dist/src/history/summary-cache.js +129 -0
  27. package/dist/src/tools/history.js +31 -20
  28. package/dist/test/agent-loop.test.js +143 -110
  29. package/dist/test/codex-history.test.js +90 -4
  30. package/dist/test/codex-plugin.test.js +6 -2
  31. package/dist/test/history-corpus.test.js +221 -33
  32. package/dist/test/history-prefilter.test.d.ts +1 -0
  33. package/dist/test/history-prefilter.test.js +174 -0
  34. package/dist/test/history-summary-cache.test.d.ts +1 -0
  35. package/dist/test/history-summary-cache.test.js +297 -0
  36. package/dist/test/history.integration.test.js +87 -52
  37. package/dist/test/marker.test.js +1 -1
  38. package/dist/test/model-facing-text.test.js +3 -4
  39. package/dist/test/reset-lifecycle.test.js +52 -12
  40. package/docs/history-sessions.md +26 -2
  41. package/docs/reset-lifecycle.md +14 -13
  42. package/docs/tool-results.md +4 -2
  43. package/package.json +1 -1
  44. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  45. package/plugins/claude/dist/claude/helper.js +425 -122
  46. package/plugins/codex/dist/codex/notesoup.js +423 -123
  47. package/plugins/pi/entries.ts +0 -1
  48. package/plugins/pi/reset/lifecycle.ts +19 -35
  49. package/plugins/pi/runtime.ts +14 -10
  50. package/plugins/pi/text.ts +2 -7
  51. package/src/history/claude.ts +16 -2
  52. package/src/history/codex-transcript.ts +52 -17
  53. package/src/history/codex.ts +5 -5
  54. package/src/history/corpus.ts +19 -2
  55. package/src/history/history.ts +11 -11
  56. package/src/history/local.ts +34 -38
  57. package/src/history/prefilter.ts +86 -0
  58. package/src/history/query.ts +77 -33
  59. package/src/history/summary-cache.ts +119 -0
  60. package/src/tools/history.ts +33 -20
@@ -6,16 +6,14 @@ 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, MARKER_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, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
10
10
  import { historyFromSession } from "../plugins/pi/history.js";
11
11
  import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
12
12
  import { assertBootHistory } from "./helpers/extension.js";
13
13
  import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
14
14
  import { FORCED_CONTINUATIONS, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, warningPrompt } from "../src/budget/text.js";
15
- import { commandWarningContent, promptBlock } from "../plugins/pi/text.js";
16
- import { registerResetLifecycle } from "../plugins/pi/reset/lifecycle.js";
17
- import { buildResetDrafts } from "../plugins/pi/reset/artifacts.js";
18
- import { currentWindowId } from "../plugins/pi/window.js";
15
+ import { commandWarningContent } from "../plugins/pi/text.js";
16
+ import { DREAM_NAMESPACE, HISTORY_NAMESPACE, NOTES_NAMESPACE } from "../plugins/pi/tool-result.js";
19
17
  async function openFixture(options) {
20
18
  const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
21
19
  const ownsDir = options.cwd === undefined;
@@ -278,6 +276,49 @@ test("real AgentSession: turn-end markers reach tool continuations and allow one
278
276
  }
279
277
  }
280
278
  });
279
+ test("real AgentSession: notesoup tool directory is a stable system section across requests and reset", async () => {
280
+ let fixture;
281
+ let directory;
282
+ const activeTools = ["empty_brain", "get_context_remaining", "notes_write"];
283
+ const namespaces = [NOTES_NAMESPACE, HISTORY_NAMESPACE, DREAM_NAMESPACE];
284
+ fixture = await openFixture({
285
+ compactionEnabled: false,
286
+ tools: activeTools,
287
+ hook: (pi) => pi.on("before_agent_start", (event) => {
288
+ event.systemPromptOptions.sections.host_context = "Host-owned context";
289
+ }),
290
+ script: (request, context) => {
291
+ const system = getCurrentSystemMessage(context.messages);
292
+ const section = system?.sections?.notesoup_tools;
293
+ assert.equal(typeof section, "string", "the directory reaches the model as a named system section");
294
+ for (const { name, description } of namespaces)
295
+ assert.ok(section.includes(`${name}: ${description}`));
296
+ assert.ok(system?.sections?.preamble?.includes("Use the tools as requested."), "the host prompt is preserved");
297
+ assert.ok(system?.sections?.host_context?.includes("Host-owned context"), "other sections are preserved");
298
+ assert.deepEqual(system?.toolsAdded?.map((tool) => tool.name).sort(), activeTools, "discovery does not activate tools");
299
+ if (directory === undefined)
300
+ directory = section;
301
+ else
302
+ assert.equal(section, directory, "the directory is unchanged across requests and reset");
303
+ assert.equal(context.messages.filter((message) => message.role === "system" && message.sections?.notesoup_tools !== undefined).length, 1, "unchanged content adds no section delta");
304
+ return request === 2
305
+ ? assistant(fixture, [{ type: "toolCall", id: "directory-reset", name: "empty_brain", arguments: {} }], "toolUse")
306
+ : assistant(fixture, [{ type: "text", text: "directory available" }]);
307
+ },
308
+ });
309
+ try {
310
+ await fixture.session.prompt("Read the directory.");
311
+ await fixture.session.waitForIdle();
312
+ await fixture.session.prompt("DIRECTORY_RESET_SENTINEL");
313
+ await fixture.session.waitForIdle();
314
+ assert.equal(fixture.requests.length, 3, "two prompts and one reset continuation");
315
+ assert.equal(resetMarkers(fixture).length, 1);
316
+ assertFreshRequest(fixture, 2, "DIRECTORY_RESET_SENTINEL");
317
+ }
318
+ finally {
319
+ fixture.close();
320
+ }
321
+ });
281
322
  test("real Pi codemode receives typed notes/history outcomes, including expected errors", async () => {
282
323
  let fixture;
283
324
  fixture = await openFixture({
@@ -509,6 +550,31 @@ test("real AgentSession: explicit tiny-session wipe ignores keepRecentTokens and
509
550
  fixture.close();
510
551
  }
511
552
  });
553
+ test("real AgentSession: a model-requested reset does not carry its original text-and-image prompt", async () => {
554
+ let fixture;
555
+ const input = "IMAGE_RESET_UNANSWERED: describe this image";
556
+ const image = { type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAn0lEQVRoge2SQQkAQRDD6qSOT20ErIh7hIFCBKSh4etpohuwAdUrsgv1LtEN2IDqFdmFepfoBmxA9YrsQr1LdAM2oHpFdqHeJboBG1C9IrtQ7xLdgA2oXpFdqHeJbsAGVK/ILtS7RDdgA6pXZBfqXaIbsAHVK7IL9S7RDdiA6hXZhXqX6AZsQPWK7EK9S3QDNqB6RXah3iW6ARtQveIfHlqMEYdT3J7gAAAAAElFTkSuQmCC", mimeType: "image/png" };
557
+ fixture = await openFixture({
558
+ compactionEnabled: false,
559
+ script: (request, context) => {
560
+ if (request === 1)
561
+ return assistant(fixture, [{ type: "toolCall", id: "wipe-image-input", name: "empty_brain", arguments: {} }], "toolUse");
562
+ assert.equal(request, 2);
563
+ assert.equal(JSON.stringify(context.messages).includes(input) || JSON.stringify(context.messages).includes(image.data), false, "the model-requested reset does not replay the input it already received");
564
+ return assistant(fixture, [{ type: "text", text: "image prompt answered" }]);
565
+ },
566
+ });
567
+ try {
568
+ await fixture.session.prompt(input, { images: [image] });
569
+ await fixture.session.waitForIdle();
570
+ assert.equal(fixture.requests.length, 2);
571
+ const carried = fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
572
+ assert.equal(carried.length, 0, "a model-requested reset owns its handoff through notes and last_word");
573
+ }
574
+ finally {
575
+ fixture.close();
576
+ }
577
+ });
512
578
  test("real AgentSession: manual command spans its tool batch and stops at settlement", async () => {
513
579
  let fixture;
514
580
  fixture = await openFixture({
@@ -557,7 +623,7 @@ test("real AgentSession: manual command spans its tool batch and stops at settle
557
623
  fixture.close();
558
624
  }
559
625
  });
560
- test("real AgentSession: /empty text is carried verbatim and answered after close-out", async () => {
626
+ test("real AgentSession: /empty text is close-out context and stops after reset", async () => {
561
627
  let fixture;
562
628
  const prompt = 'AFTER_CLEAR_PROMPT_SENTINEL /cm "literal text" \nsecond line';
563
629
  fixture = await openFixture({
@@ -566,24 +632,21 @@ test("real AgentSession: /empty text is carried verbatim and answered after clos
566
632
  if (request === 1)
567
633
  return assistant(fixture, [{ type: "text", text: "initial work" }]);
568
634
  if (request === 2) {
569
- assert.ok(text(context).includes(JSON.stringify(promptBlock(`/empty ${prompt}`)).slice(1, -1)));
635
+ assert.ok(text(context).includes(JSON.stringify(`/empty ${prompt}`).slice(1, -1)));
570
636
  return assistant(fixture, [{ type: "toolCall", id: "prompt-wipe", name: "empty_brain", arguments: { last_word: "saved" } }], "toolUse");
571
637
  }
572
- assert.equal(request, 3);
573
- assertFreshRequest(fixture, 2, "PROMPT_RESET_OLD_SENTINEL");
574
- assertUserContent(context, [{ type: "text", text: prompt }]);
575
- return assistant(fixture, [{ type: "text", text: "prompt handled" }]);
638
+ throw new Error("command argument must not start fresh-window work");
576
639
  },
577
640
  });
578
641
  try {
579
642
  await fixture.session.prompt("PROMPT_RESET_OLD_SENTINEL");
580
643
  await fixture.session.prompt(`/empty ${prompt}`);
581
644
  await fixture.session.waitForIdle();
582
- assert.equal(fixture.requests.length, 3);
645
+ assert.equal(fixture.requests.length, 2);
583
646
  assert.equal(resetMarkers(fixture).length, 1);
584
647
  const branch = fixture.sessionManager.getBranch();
585
- const continuationIndex = branch.findIndex((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
586
- 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]);
648
+ assert.equal(branch.some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
649
+ assert.equal(JSON.stringify(fixture.sessionManager.buildSessionProjection().messages).includes("AFTER_CLEAR_PROMPT_SENTINEL"), false);
587
650
  assert.equal(fixture.notices.some(isResetSuccessNotice), false);
588
651
  }
589
652
  finally {
@@ -625,16 +688,12 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
625
688
  if (request === 1)
626
689
  assert.equal(text(context).includes("FIRST_RESET_PROMPT"), false, "the prompt belongs to the close-out, not the turn already running");
627
690
  // The close-out embeds the human's command line verbatim, so the closing turn sees
628
- // what the next window was asked to do. Only the accepted command appears.
691
+ // the command context. Only the accepted command appears.
629
692
  if (request === 2) {
630
- assert.ok(text(context).includes("FIRST_RESET_PROMPT"), "the close-out carries the command line");
693
+ assert.ok(text(context).includes(JSON.stringify("/fresh-window FIRST_RESET_PROMPT").slice(1, -1)), "the close-out carries the original command line as plain text");
631
694
  assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false, "the refused repeat never enters the close-out");
632
695
  }
633
- if (request === 3) {
634
- assert.ok(text(context).includes("FIRST_RESET_PROMPT"), "the fresh window still receives the prompt");
635
- assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false);
636
- }
637
- assert.ok(request <= 3);
696
+ assert.ok(request <= 2);
638
697
  return assistant(fixture, [{ type: "text", text: "done" }]);
639
698
  },
640
699
  });
@@ -646,7 +705,8 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
646
705
  release();
647
706
  await running;
648
707
  await fixture.session.waitForIdle();
649
- assert.equal(fixture.requests.length, 3);
708
+ assert.equal(fixture.requests.length, 2);
709
+ assert.equal(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
650
710
  assert.equal(resetMarkers(fixture).length, 1);
651
711
  assert.ok(fixture.notices.some((notice) => notice.includes("Brain already being emptied")));
652
712
  }
@@ -655,6 +715,31 @@ test("real AgentSession: streaming clear prompt keeps the first request", async
655
715
  fixture.close();
656
716
  }
657
717
  });
718
+ test("real AgentSession: hard-reserve reset carries the original text and image and continues", async () => {
719
+ let fixture;
720
+ const input = "HARD_RESERVE_IMAGE_INPUT";
721
+ const image = { type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAn0lEQVRoge2SQQkAQRDD6qSOT20ErIh7gIFCBKSh4et1LtEN2IDqFdmFepfoBmxA9YrsQr1LdAM2oHpFdqHeJboBG1C9IrtQ7xLdgA2oXpFdqHeJbsAGVK/ILtS7RDdgA6pXZBfqXaIbsAHVK7IL9S7RDdiA6hXZhXqX6AZsQPWK7EK9S3QDNqB6RXah3iW6ARtQveIfHlqMEYdT3J7gAAAAAElFTkSuQmCC", mimeType: "image/png" };
722
+ fixture = await openFixture({
723
+ defaultReserveTokens: 80_000,
724
+ script: (request, context) => {
725
+ if (request === 1)
726
+ return assistant(fixture, [{ type: "text", text: "reserve reached" }], "stop", { usage: usage(80_000) });
727
+ assert.equal(request, 2);
728
+ assertUserContent(context, [{ type: "text", text: input }, image]);
729
+ return assistant(fixture, [{ type: "text", text: "carried image answered" }]);
730
+ },
731
+ });
732
+ try {
733
+ await fixture.session.prompt(input, { images: [image] });
734
+ await fixture.session.waitForIdle();
735
+ assert.equal(fixture.requests.length, 2);
736
+ assert.equal(resetMarkers(fixture).length, 1);
737
+ assert.equal(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 1);
738
+ }
739
+ finally {
740
+ fixture.close();
741
+ }
742
+ });
658
743
  test("real AgentSession: manual hard-reserve reset stops clean and mixed-tool turns without fresh provider work", async () => {
659
744
  for (const mixed of [false, true]) {
660
745
  let fixture;
@@ -698,15 +783,13 @@ test("real AgentSession: manual hard-reserve reset stops clean and mixed-tool tu
698
783
  }
699
784
  }
700
785
  });
701
- test("real AgentSession: overflowing /empty close-out forces a reset and retries its text only once", async () => {
786
+ test("real AgentSession: overflowing /empty close-out forces a reset and stops", async () => {
702
787
  let fixture;
703
788
  fixture = await openFixture({
704
- script: (request, context) => {
789
+ script: (request) => {
705
790
  if (request === 1)
706
791
  return assistant(fixture, [{ type: "text", text: "before overflow" }]);
707
- assert.ok(request <= 3, "an oversized carried prompt cannot loop");
708
- if (request === 3)
709
- assertUserContent(context, [{ type: "text", text: "OVERSIZED_MANUAL_PROMPT" }]);
792
+ assert.equal(request, 2, "command text must not trigger a retry");
710
793
  return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
711
794
  },
712
795
  });
@@ -714,9 +797,9 @@ test("real AgentSession: overflowing /empty close-out forces a reset and retries
714
797
  await fixture.session.prompt("MANUAL_OVERFLOW_OLD_SENTINEL");
715
798
  await fixture.session.prompt("/empty OVERSIZED_MANUAL_PROMPT");
716
799
  await fixture.session.waitForIdle();
717
- assert.equal(fixture.requests.length, 3);
800
+ assert.equal(fixture.requests.length, 2);
718
801
  assert.equal(resetMarkers(fixture).length, 1);
719
- assertFreshRequest(fixture, 2, "MANUAL_OVERFLOW_OLD_SENTINEL");
802
+ assert.equal(fixture.sessionManager.getBranch().some((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE), false);
720
803
  assert.equal(resetMarkers(fixture)[0].data.origin, "forced");
721
804
  assert.ok(fixture.notices.some(isResetSuccessNotice));
722
805
  }
@@ -843,98 +926,48 @@ test("real AgentSession: user abort, synthetic aborted response, and generic err
843
926
  }
844
927
  }
845
928
  });
846
- test("real AgentSession: input during bare /empty is hidden-steered, carried with images, and answered after a safety reset", async () => {
929
+ test("real AgentSession: input during prompted /empty is carried with images and answered after reset", async () => {
847
930
  let fixture;
848
- let started;
849
- let release;
850
- const ready = new Promise((resolve) => { started = resolve; });
851
- const gate = new Promise((resolve) => { release = resolve; });
931
+ let closeoutStarted;
932
+ let releaseCloseout;
933
+ const closeoutReady = new Promise((resolve) => { closeoutStarted = resolve; });
934
+ const closeoutGate = new Promise((resolve) => { releaseCloseout = resolve; });
852
935
  const input = "DEFERRED_HUMAN_INPUT\n verbatim";
853
936
  const image = { type: "image", data: "aGVsbG8=", mimeType: "image/png" };
854
937
  fixture = await openFixture({
855
938
  script: async (request, context) => {
856
939
  if (request === 1) {
857
- started();
858
- await gate;
859
- return assistant(fixture, [{ type: "text", text: "saving notes" }]);
940
+ closeoutStarted();
941
+ await closeoutGate;
942
+ assert.ok(text(context).includes(JSON.stringify(commandWarningContent("/empty CLOSE_OUT_CONTEXT")).slice(1, -1)));
943
+ assert.equal(text(context).includes(input), false, "the separate input is not sent to the closing model");
944
+ assert.equal(text(context).includes("next_window_prompt"), false, "no hidden steer reaches the provider");
945
+ return assistant(fixture, [{ type: "text", text: "close-out ready for reset" }], "stop", { usage: usage(80_000) });
860
946
  }
861
- if (request === 2) {
862
- assertUserContent(context, [{ type: "text", text: promptBlock(input) }, image]);
863
- return assistant(fixture, [{ type: "toolCall", id: "deferred-pressure", name: "notes_write", arguments: { address: "deferred.md", content: "saved" } }], "toolUse", { usage: usage(80_000) });
864
- }
865
- assert.equal(request, 3, "carried input continues instead of taking the bare-command stop");
866
- assertFreshRequest(fixture, 2, "saving notes");
947
+ assert.equal(request, 2, "the intercepted input resumes in the fresh window");
867
948
  assertUserContent(context, [{ type: "text", text: input }, image]);
949
+ assert.equal(text(context).includes("CLOSE_OUT_CONTEXT"), false, "the fresh window excludes old-window close-out text");
950
+ assert.equal(text(context).includes("next_window_prompt"), false, "the fresh provider request contains no hidden steer");
868
951
  return assistant(fixture, [{ type: "text", text: "deferred input answered" }]);
869
952
  },
870
953
  });
871
954
  try {
872
- const command = fixture.session.prompt("/empty");
873
- await ready;
955
+ const closing = fixture.session.prompt("/empty CLOSE_OUT_CONTEXT");
956
+ await closeoutReady;
874
957
  await fixture.session.prompt(input, { images: [image], streamingBehavior: "followUp" });
875
- release();
876
- await command;
877
- await fixture.session.waitForIdle();
878
- assert.equal(fixture.requests.length, 3);
879
- assert.equal(resetMarkers(fixture).length, 1);
880
- const branch = fixture.sessionManager.getBranch();
881
- const steer = branch.find((entry) => entry.type === "custom_message" && entry.customType === NEXT_WINDOW_PROMPT_TYPE);
882
- assert.ok(steer?.type === "custom_message");
883
- assert.equal(steer.display, false);
884
- assert.deepEqual(steer.content, [{ type: "text", text: promptBlock(input) }, image], "the bare block and original images reach the closing model");
885
- assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 1);
886
- assert.equal(fixture.streamSignals.at(-1), false, "the stop-pending safeguard cannot swallow carried input");
887
- }
888
- finally {
889
- release();
890
- fixture.close();
891
- }
892
- });
893
- test("real AgentSession: a hidden steer queued during reset construction is not replayed beside carried input", async () => {
894
- let fixture;
895
- let started;
896
- let release;
897
- const building = new Promise((resolve) => { started = resolve; });
898
- const gate = new Promise((resolve) => { release = resolve; });
899
- const input = "LATE_BUILD_INPUT";
900
- fixture = await openFixture({
901
- tools: [],
902
- extensionFactory: (pi) => {
903
- const lifecycle = registerResetLifecycle(pi, {
904
- isEnabled: () => true,
905
- budget: { automaticResetEnabled: () => false, hardReserveDue: () => false, consumeTurnEnd: () => [], clear() { } },
906
- async buildReset(ctx, isCurrent, lastWord, firstSeq, origin) {
907
- started();
908
- await gate;
909
- return buildResetDrafts(ctx, undefined, isCurrent, lastWord, firstSeq, origin);
910
- },
911
- });
912
- pi.on("before_agent_start", (_event, ctx) => { lifecycle.command(currentWindowId(ctx), false); });
913
- },
914
- script: (request, context) => {
915
- if (request === 1)
916
- return assistant(fixture, [{ type: "text", text: "closing old window" }]);
917
- assert.equal(request, 2);
918
- assertUserContent(context, [{ type: "text", text: input }]);
919
- assert.equal(text(context).includes("notesoup:next_window_prompt"), false, "the stale queued steer must not duplicate the carried input");
920
- return assistant(fixture, [{ type: "text", text: "late input answered" }]);
921
- },
922
- });
923
- try {
924
- const closing = fixture.session.prompt("close out");
925
- await building;
926
- await fixture.session.prompt(input, { streamingBehavior: "steer" });
927
- release();
958
+ releaseCloseout();
928
959
  await closing;
929
960
  await fixture.session.waitForIdle();
930
961
  assert.equal(fixture.requests.length, 2);
931
- assert.equal(text(fixture.requests[1]).includes("notesoup:next_window_prompt"), false);
932
962
  const branch = fixture.sessionManager.getBranch();
933
- const markerIndex = branch.findIndex((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
934
- assert.ok(branch.slice(markerIndex + 1).some((entry) => entry.type === "custom_message" && entry.customType === NEXT_WINDOW_PROMPT_TYPE), "Pi really delivered the queued steer after committing the boundary");
963
+ assert.equal(branch.some((entry) => entry.type === "custom_message" && JSON.stringify(entry).includes("next-window-prompt")), false, "the branch contains no next-window steer");
964
+ assert.equal(resetMarkers(fixture).length, 1, "one reset marker commits at settlement");
965
+ const carried = branch.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
966
+ assert.equal(carried.length, 1);
967
+ assert.deepEqual(carried[0]?.type === "custom_message" ? carried[0].content : undefined, [{ type: "text", text: input }, image]);
935
968
  }
936
969
  finally {
937
- release();
970
+ releaseCloseout();
938
971
  fixture.close();
939
972
  }
940
973
  });
@@ -956,7 +989,6 @@ test("real AgentSession: abort after handled input preserves originals without f
956
989
  }
957
990
  assert.equal(request, 2);
958
991
  assertUserContent(context, original);
959
- assert.equal(text(context).includes("notesoup:next_window_prompt"), false);
960
992
  return assistant(fixture, [{ type: "text", text: "resumed after abort" }]);
961
993
  },
962
994
  });
@@ -981,7 +1013,7 @@ test("real AgentSession: abort after handled input preserves originals without f
981
1013
  fixture.close();
982
1014
  }
983
1015
  });
984
- test("real AgentSession: a close-out error does not discard handled input", async () => {
1016
+ test("real AgentSession: a close-out error answers handled input without resetting", async () => {
985
1017
  let fixture;
986
1018
  let started;
987
1019
  let release;
@@ -997,7 +1029,7 @@ test("real AgentSession: a close-out error does not discard handled input", asyn
997
1029
  }
998
1030
  assert.equal(request, 2);
999
1031
  assertUserContent(context, [{ type: "text", text: "ERROR_HANDLED_INPUT" }]);
1000
- assert.equal(text(context).includes("notesoup:next_window_prompt"), false);
1032
+ assert.equal(text(context).includes("next_window_prompt"), false, "no hidden steer reaches the provider");
1001
1033
  return assistant(fixture, [{ type: "text", text: "handled input answered without reset" }]);
1002
1034
  },
1003
1035
  });
@@ -1008,11 +1040,12 @@ test("real AgentSession: a close-out error does not discard handled input", asyn
1008
1040
  release();
1009
1041
  await closing;
1010
1042
  await fixture.session.waitForIdle();
1011
- const originals = fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
1012
- assert.equal(originals.length, 1);
1013
1043
  assert.equal(fixture.requests.length, 2);
1014
1044
  assertUserContent(fixture.requests[1], [{ type: "text", text: "ERROR_HANDLED_INPUT" }]);
1015
- assert.equal(resetMarkers(fixture).length, 0, "ordinary errors still do not force a reset");
1045
+ const originals = fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
1046
+ assert.equal(originals.length, 1, "the failed close-out restores one visible copy");
1047
+ assert.deepEqual(originals[0]?.type === "custom_message" ? originals[0].content : undefined, "ERROR_HANDLED_INPUT");
1048
+ assert.equal(resetMarkers(fixture).length, 0, "ordinary errors do not force a reset");
1016
1049
  }
1017
1050
  finally {
1018
1051
  release();
@@ -1175,7 +1208,7 @@ test("real AgentSession: two retain-none checkpoints survive session-file reopen
1175
1208
  assert.equal(branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).length, 2);
1176
1209
  assert.ok(JSON.stringify(branch).includes("PERSISTED_OLD_WINDOW_SENTINEL"), "raw history survives disk reopen");
1177
1210
  const canonical = reopened.buildSessionProjection().messages;
1178
- assert.equal(JSON.stringify(canonical).includes("PERSISTED_OLD_WINDOW_SENTINEL"), false, "disk-loaded canonical context agrees with the fresh request");
1211
+ assert.equal(JSON.stringify(canonical).includes("PERSISTED_OLD_WINDOW_SENTINEL"), false, "model-requested resets do not carry the original prompt");
1179
1212
  assert.ok(canonical.some((message) => message.role === "compactionSummary"), "the accepted empty-summary wrapper survives reload");
1180
1213
  const system = getCurrentSystemMessage(canonical);
1181
1214
  assert.ok(JSON.stringify(system).includes("Use the tools as requested."), "the complete system prompt survives the checkpoint");
@@ -1372,7 +1405,7 @@ test("real AgentSession: overflow and recoverable length reset and retry once; r
1372
1405
  assert.equal(repeated.sessionManager.getBranch().filter((entry) => entry.type === "compaction").length, 2);
1373
1406
  assert.equal(repeated.requests.length, 3, "an automatic continuation still gets only one recovery request");
1374
1407
  assertFreshRequest(repeated, 2, "REPEATED_OVERFLOW_SENTINEL");
1375
- assert.equal(repeated.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 0, "our own automatic continuation has no human input to carry");
1408
+ assert.equal(repeated.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE).length, 0, "model-owned reset and its input-free continuation do not carry the original prompt");
1376
1409
  }
1377
1410
  finally {
1378
1411
  repeated.close();
@@ -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
  });