notesoup 0.47.1 → 0.48.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 (88) hide show
  1. package/README.md +2 -2
  2. package/dist/src/boot/render.d.ts +14 -7
  3. package/dist/src/boot/render.js +29 -16
  4. package/dist/src/boot/text.d.ts +25 -4
  5. package/dist/src/boot/text.js +60 -13
  6. package/dist/src/budget/constants.d.ts +2 -4
  7. package/dist/src/budget/constants.js +2 -4
  8. package/dist/src/budget/policy.d.ts +2 -2
  9. package/dist/src/budget/policy.js +3 -3
  10. package/dist/src/budget/text.d.ts +29 -9
  11. package/dist/src/budget/text.js +51 -10
  12. package/dist/src/claude/helper.d.ts +2 -3
  13. package/dist/src/claude/helper.js +45 -11
  14. package/dist/src/claude/history.d.ts +9 -0
  15. package/dist/src/claude/history.js +271 -0
  16. package/dist/src/dsh/budget.js +1 -1
  17. package/dist/src/dsh/engine.d.ts +2 -1
  18. package/dist/src/dsh/engine.js +18 -9
  19. package/dist/src/dsh/index.js +9 -4
  20. package/dist/src/dsh/tools.js +1 -1
  21. package/dist/src/dsh/window.d.ts +2 -1
  22. package/dist/src/dsh/window.js +14 -8
  23. package/dist/src/history/query.js +59 -81
  24. package/dist/src/notes/address.d.ts +5 -0
  25. package/dist/src/notes/address.js +20 -21
  26. package/dist/src/notes/store.js +12 -19
  27. package/dist/src/pi/boot.d.ts +1 -1
  28. package/dist/src/pi/boot.js +28 -5
  29. package/dist/src/pi/budget.d.ts +1 -3
  30. package/dist/src/pi/budget.js +20 -61
  31. package/dist/src/pi/entries.d.ts +0 -1
  32. package/dist/src/pi/entries.js +0 -1
  33. package/dist/src/pi/history.d.ts +3 -0
  34. package/dist/src/pi/history.js +4 -0
  35. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  36. package/dist/src/pi/reset/artifacts.js +16 -14
  37. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  38. package/dist/src/pi/reset/lifecycle.js +48 -72
  39. package/dist/src/pi/runtime.js +9 -8
  40. package/dist/src/pi/window.d.ts +12 -6
  41. package/dist/src/pi/window.js +7 -0
  42. package/dist/test/agent-loop.test.js +53 -30
  43. package/dist/test/boot.integration.test.js +123 -12
  44. package/dist/test/budget-settings.integration.test.js +10 -6
  45. package/dist/test/claude-history.test.d.ts +1 -0
  46. package/dist/test/claude-history.test.js +184 -0
  47. package/dist/test/claude-mod.test.js +236 -42
  48. package/dist/test/dsh.test.js +80 -3
  49. package/dist/test/helpers/extension.d.ts +3 -0
  50. package/dist/test/helpers/extension.js +33 -5
  51. package/dist/test/history.integration.test.js +66 -0
  52. package/dist/test/host-neutral.test.js +1 -1
  53. package/dist/test/model-facing-text.test.d.ts +1 -0
  54. package/dist/test/model-facing-text.test.js +181 -0
  55. package/dist/test/notes.integration.test.js +16 -18
  56. package/dist/test/reset-lifecycle.test.js +201 -46
  57. package/docs/architecture.md +3 -3
  58. package/docs/claude-code-mod.md +15 -3
  59. package/docs/dsh.md +2 -2
  60. package/docs/reset-lifecycle.md +32 -20
  61. package/docs/skills.md +1 -1
  62. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  63. package/mods/notesoup/dist/claude/helper.js +836 -92
  64. package/mods/notesoup/hooks/register.ts +140 -38
  65. package/package.json +1 -1
  66. package/src/boot/render.ts +41 -23
  67. package/src/boot/text.ts +69 -13
  68. package/src/budget/constants.ts +2 -4
  69. package/src/budget/policy.ts +3 -3
  70. package/src/budget/text.ts +61 -10
  71. package/src/claude/helper.ts +53 -22
  72. package/src/claude/history.ts +228 -0
  73. package/src/dsh/budget.ts +1 -1
  74. package/src/dsh/engine.ts +16 -9
  75. package/src/dsh/index.ts +8 -3
  76. package/src/dsh/tools.ts +1 -1
  77. package/src/dsh/window.ts +15 -9
  78. package/src/history/query.ts +57 -82
  79. package/src/notes/address.ts +19 -16
  80. package/src/notes/store.ts +9 -14
  81. package/src/pi/boot.ts +27 -5
  82. package/src/pi/budget.ts +20 -58
  83. package/src/pi/entries.ts +0 -1
  84. package/src/pi/history.ts +7 -2
  85. package/src/pi/reset/artifacts.ts +17 -14
  86. package/src/pi/reset/lifecycle.ts +56 -79
  87. package/src/pi/runtime.ts +9 -8
  88. package/src/pi/window.ts +11 -1
@@ -7,8 +7,10 @@ import { createAssistantMessageEventStream, getCurrentSystemMessage } from "@ear
7
7
  import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
8
  import notesoup, { createNotesoup } from "../src/pi/extension.js";
9
9
  import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../src/pi/entries.js";
10
- import { CONTEXT_WINDOW_OPEN_TAG } from "../src/boot/text.js";
11
- import { CONTINUATION, GUIDANCE_OPEN_TAG, WARNING_CONTENT, WARNING_PROMPT } from "../src/budget/text.js";
10
+ import { historyFromSession } from "../src/pi/history.js";
11
+ import { assertBootHistory } from "./helpers/extension.js";
12
+ import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
13
+ import { FORCED_CONTINUATIONS, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, warningContent, warningPrompt } from "../src/budget/text.js";
12
14
  async function openFixture(options) {
13
15
  const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
14
16
  const ownsDir = options.cwd === undefined;
@@ -194,8 +196,12 @@ function text(message) {
194
196
  return JSON.stringify(message?.messages ?? []);
195
197
  }
196
198
  /** `text()` serializes to JSON, so match the reset prose in its escaped form. */
197
- const CONTINUATION_JSON = JSON.stringify(CONTINUATION).slice(1, -1);
198
- const WARNING_JSON = JSON.stringify(WARNING_PROMPT).slice(1, -1);
199
+ const CONTINUATION_JSON_LINES = [...NORMAL_CONTINUATIONS, ...FORCED_CONTINUATIONS].map((line) => JSON.stringify(line).slice(1, -1));
200
+ /** How many distinct reset paragraphs a serialized request carries; one fresh window carries one. */
201
+ function continuationLinesIn(body) {
202
+ return CONTINUATION_JSON_LINES.filter((line) => body.includes(line));
203
+ }
204
+ const WARNING_JSON = JSON.stringify(warningPrompt()).slice(1, -1);
199
205
  function resetMarkers(fixture) {
200
206
  return fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
201
207
  }
@@ -216,8 +222,8 @@ function contextRemainingResults(fixture) {
216
222
  function assertFreshRequest(fixture, requestIndex, oldSentinel) {
217
223
  const body = text(fixture.requests[requestIndex]);
218
224
  assert.equal(body.includes(oldSentinel), false, "the new provider request excludes the old window transcript");
219
- assert.ok(body.includes(CONTEXT_WINDOW_OPEN_TAG), "the new provider request includes the fresh context-window boot");
220
- assert.equal(body.split(CONTINUATION_JSON).length - 1, 1, "the fresh window carries exactly one reset message");
225
+ assert.ok(body.includes(WINDOW_IDENTITY_OPEN_TAG), "the new provider request includes the fresh context-window boot");
226
+ assert.deepEqual(continuationLinesIn(body).length, 1, "the fresh window carries exactly one reset paragraph");
221
227
  }
222
228
  test("real Pi codemode receives typed notes/history outcomes, including expected errors", { timeout: 20000 }, async () => {
223
229
  let fixture;
@@ -342,7 +348,7 @@ test("real AgentSession: early guidance reaches its crossing request and later r
342
348
  fixture.close();
343
349
  }
344
350
  });
345
- test("real AgentSession: an aborted final warning stays silent until a successful retry commits it", async () => {
351
+ test("real AgentSession: a final warning notifies before the response, even if aborted, without repeating on retry", async () => {
346
352
  let fixture;
347
353
  fixture = await openFixture({
348
354
  compactionEnabled: true,
@@ -352,6 +358,7 @@ test("real AgentSession: an aborted final warning stays silent until a successfu
352
358
  if (request === 2)
353
359
  return assistant(fixture, [{ type: "toolCall", id: "abort-budget-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
354
360
  assert.ok(text(context).includes(WARNING_JSON), "the final warning reaches the model on both attempts");
361
+ assert.equal(fixture.budgetNotices(), 1, "the UI is notified before the model responds, once across retries");
355
362
  return assistant(fixture, [{ type: "text", text: `response ${request}` }], request === 3 ? "aborted" : "stop", { usage: usage(60_000) });
356
363
  },
357
364
  });
@@ -362,13 +369,13 @@ test("real AgentSession: an aborted final warning stays silent until a successfu
362
369
  await fixture.session.waitForIdle();
363
370
  assert.equal(fixture.requests.length, 3, "budget probes reach one final-warning attempt");
364
371
  assert.equal(warnings().length, 0, "the aborted attempt leaves no durable warning");
365
- assert.equal(notices(), 0, "an uncommitted warning never notifies");
372
+ assert.equal(notices(), 1, "the aborted request already notified at injection");
366
373
  await fixture.session.prompt("Retry successfully.");
367
374
  await fixture.session.waitForIdle();
368
375
  assert.equal(warnings().length, 1, "the successful retry commits one hidden warning");
369
376
  assert.equal(resetMarkers(fixture).length, 0, "committing the warning does not authorize a reset at normal stop");
370
377
  assert.equal(fixture.requests.length, 4, "the retry settles without a fresh-window continuation");
371
- assert.equal(notices(), 1, "the committed warning notifies once");
378
+ assert.equal(notices(), 1, "committing the retry does not repeat the notification");
372
379
  assert.equal(fixture.notices.some((notice) => notice.includes("Context running low")), false, "early guidance remains UI-silent");
373
380
  }
374
381
  finally {
@@ -386,6 +393,7 @@ test("real AgentSession: final warning survives its reset boundary and notifies
386
393
  return assistant(fixture, [{ type: "toolCall", id: "final-budget-probe-2", name: "get_context_remaining", arguments: {} }], "toolUse", { usage: usage(60_000) });
387
394
  if (request === 3) {
388
395
  assert.ok(text(context).includes(WARNING_JSON), "the final warning reaches the model");
396
+ assert.equal(fixture.budgetNotices(), 1, "warning notifies before the wipe tool runs");
389
397
  return assistant(fixture, [{ type: "toolCall", id: "final-budget-wipe", name: "empty_brain", arguments: {} }], "toolUse", { usage: usage(60_000) });
390
398
  }
391
399
  return assistant(fixture, [{ type: "text", text: "fresh window ready" }]);
@@ -432,7 +440,8 @@ test("real AgentSession: explicit tiny-session wipe ignores keepRecentTokens and
432
440
  assert.equal(resetMarkers(fixture).length, 1, "explicit wipe does not depend on Pi's compaction keep window");
433
441
  const marker = resetMarkers(fixture)[0];
434
442
  assert.equal(marker.type, "custom");
435
- assert.deepEqual(Object.keys(marker.data), ["windowId"]);
443
+ assert.deepEqual(Object.keys(marker.data), ["windowId", "origin"]);
444
+ assert.equal(marker.data.origin, "normal", "the model's own wipe opens the normal handoff");
436
445
  const windowId = marker.data.windowId;
437
446
  const boot = fixture.sessionManager.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details && typeof entry.details === "object" && entry.details.windowId === windowId);
438
447
  assert.ok(boot && boot.type === "custom_message", "the reset boot is persisted after the marker");
@@ -477,7 +486,7 @@ test("real AgentSession: manual command spans its tool batch and stops at settle
477
486
  assert.ok(warningIndex >= 0 && warningIndex < checkpointIndex, "the idle warning is durable before the checkpoint");
478
487
  const warning = branch[warningIndex];
479
488
  assert.ok(warning?.type === "custom_message");
480
- assert.equal(warning.content, WARNING_CONTENT);
489
+ assert.equal(warning.content, warningContent());
481
490
  assert.equal(branch[markerIndex - 1]?.id, branch[checkpointIndex]?.id);
482
491
  assert.ok(branch.slice(0, checkpointIndex).some((entry) => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "notes_write"), "note write finishes before the checkpoint");
483
492
  const marker = resetMarkers(fixture)[0];
@@ -494,17 +503,19 @@ test("real AgentSession: manual command spans its tool batch and stops at settle
494
503
  fixture.close();
495
504
  }
496
505
  });
497
- test("real AgentSession: clear commands append a prompt after continuation and resume once", { timeout: 25000 }, async () => {
506
+ test("real AgentSession: a clear command keeps its prompt out of the fresh window and resumes once", { timeout: 25000 }, async () => {
498
507
  for (const mode of ["empty-brain", "fresh-window", "hard-reserve", "overflow"]) {
499
508
  let fixture;
500
- const prompt = 'AFTER_CLEAR_PROMPT /cm "literal text"';
509
+ const prompt = 'AFTER_CLEAR_PROMPT_SENTINEL /cm "literal text"';
510
+ // `text()` serializes to JSON, so a quoted argument reaches the provider in its escaped form.
511
+ const promptJson = JSON.stringify(prompt).slice(1, -1);
501
512
  fixture = await openFixture({
502
513
  compactionEnabled: mode === "hard-reserve",
503
514
  script: (request, context) => {
504
515
  if (request === 1)
505
516
  return assistant(fixture, [{ type: "text", text: "initial work" }]);
506
517
  if (request === 2) {
507
- assert.equal(text(context).includes(prompt), false, "the old window never sees the trailing prompt");
518
+ assert.ok(text(context).includes(promptJson), "the closing window sees the human's command line verbatim");
508
519
  if (mode === "overflow")
509
520
  return assistant(fixture, [], "error", { errorMessage: "Prompt too long: context exceeds maximum context length" });
510
521
  return mode === "hard-reserve"
@@ -513,8 +524,9 @@ test("real AgentSession: clear commands append a prompt after continuation and r
513
524
  }
514
525
  assert.equal(request, 3, "exactly one fresh-window request");
515
526
  assert.equal(text(context).includes("PROMPT_RESET_OLD_SENTINEL"), false);
516
- assert.equal(text(context).split(prompt).length - 1, 1);
517
- assert.ok(text(context).indexOf(CONTINUATION_JSON) < text(context).indexOf(prompt), "wake-up prose precedes the appended prompt");
527
+ assert.equal(text(context).includes("AFTER_CLEAR_PROMPT_SENTINEL"), false, "the fresh window is not handed the prompt");
528
+ assert.equal(text(context).includes("literal text"), false, "not even the quoted argument survives the reset");
529
+ assert.deepEqual(continuationLinesIn(text(context)).length, 1, "wake-up prose opens the fresh window, once");
518
530
  return assistant(fixture, [{ type: "text", text: "prompt handled" }]);
519
531
  },
520
532
  });
@@ -526,11 +538,7 @@ test("real AgentSession: clear commands append a prompt after continuation and r
526
538
  assert.equal(resetMarkers(fixture).length, 1);
527
539
  const branch = fixture.sessionManager.getBranch();
528
540
  const continuationIndex = branch.findIndex((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
529
- const appended = branch[continuationIndex + 1];
530
- assert.ok(appended?.type === "custom_message");
531
- assert.equal(appended.customType, "notesoup/reset-prompt");
532
- assert.equal(appended.content, prompt);
533
- assert.equal(appended.display, true);
541
+ assert.equal(branch.slice(continuationIndex + 1).filter((entry) => entry.type === "custom_message").length, 0, "nothing is injected after the continuation");
534
542
  assert.ok(fixture.notices.some((notice) => notice.includes("Brain emptied")));
535
543
  }
536
544
  finally {
@@ -570,10 +578,16 @@ test("real AgentSession: streaming clear prompt keeps the first request", { time
570
578
  started();
571
579
  await gate;
572
580
  }
573
- if (request <= 2)
574
- assert.equal(text(context).includes("FIRST_RESET_PROMPT"), false);
581
+ if (request === 1)
582
+ assert.equal(text(context).includes("FIRST_RESET_PROMPT"), false, "the prompt belongs to the close-out, not the turn already running");
583
+ // The close-out embeds the human's command line verbatim, so the closing turn sees
584
+ // what the next window was asked to do. Only the accepted command appears.
585
+ if (request === 2) {
586
+ assert.ok(text(context).includes("FIRST_RESET_PROMPT"), "the close-out carries the command line");
587
+ assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false, "the refused repeat never enters the close-out");
588
+ }
575
589
  if (request === 3) {
576
- assert.ok(text(context).includes("FIRST_RESET_PROMPT"));
590
+ assert.ok(text(context).includes("FIRST_RESET_PROMPT"), "the fresh window still receives the prompt");
577
591
  assert.equal(text(context).includes("IGNORED_RESET_PROMPT"), false);
578
592
  }
579
593
  assert.ok(request <= 3);
@@ -804,7 +818,13 @@ test("real AgentSession: user abort, synthetic aborted response, and generic err
804
818
  await fixture.session.prompt("AFTER_UNSUCCESSFUL_CLOSEOUT");
805
819
  await fixture.session.waitForIdle();
806
820
  assert.equal(resetMarkers(fixture).length, 0, "no pending close-out leaks into a later prompt");
807
- assert.equal(JSON.stringify(fixture.sessionManager.getBranch()).includes("SHOULD_NOT_RUN_AFTER_FAILURE"), false, "cancelled prompt is never appended");
821
+ // The close-out is armed when the command is typed, so its text is durable before the
822
+ // outcome is known. A cancelled close-out keeps the command line, but must never
823
+ // publish it as the next window's prompt.
824
+ const branch = fixture.sessionManager.getBranch();
825
+ const wipe = branch.find((entry) => entry.type === "custom_message" && entry.customType === MANUAL_WIPE_TYPE);
826
+ assert.ok(wipe && JSON.stringify(wipe).includes("SHOULD_NOT_RUN_AFTER_FAILURE"), `${mode} keeps the human's command line in the close-out it armed`);
827
+ assert.equal(JSON.stringify(branch).includes("notesoup/reset-prompt"), false, `${mode} never publishes a prompt for a window that opened`);
808
828
  }
809
829
  finally {
810
830
  fixture.close();
@@ -874,9 +894,9 @@ test("real AgentSession: a reset survives all notes-home read failures with an i
874
894
  const boot = fixture.sessionManager.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details && typeof entry.details === "object" && entry.details.windowId === windowId);
875
895
  assert.ok(boot && boot.type === "custom_message");
876
896
  const bootText = typeof boot.content === "string" ? boot.content : JSON.stringify(boot.content);
877
- assert.ok(bootText.includes("THE HUMAN · @human"));
897
+ assert.equal(bootText.includes("@human — the human"), true);
878
898
  assert.equal(bootText.match(/This drawer wouldn't open/g)?.length, 5, "each failed section gets one recovery line");
879
- assert.ok(bootText.includes("<context_window_protocol>"));
899
+ assert.ok(bootText.includes(NOTES_PROTOCOL_OPEN_TAG));
880
900
  }
881
901
  finally {
882
902
  fixture.close();
@@ -1022,7 +1042,10 @@ test("real AgentSession: two retain-none checkpoints survive session-file reopen
1022
1042
  const previousWindowId = previousMarker.data.windowId;
1023
1043
  const latestBoot = branch.find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details?.windowId === latestWindowId);
1024
1044
  assert.ok(latestBoot && latestBoot.type === "custom_message" && typeof latestBoot.content === "string");
1025
- assert.ok(latestBoot.content.includes(`Previous context window id: ${previousWindowId}`));
1045
+ const projection = historyFromSession({ sessionManager: reopened });
1046
+ assert.equal(projection.windows.at(-2)?.windowId, previousWindowId);
1047
+ assert.equal(projection.windows.at(-1)?.windowId, latestWindowId);
1048
+ assertBootHistory(latestBoot.content, projection);
1026
1049
  }
1027
1050
  finally {
1028
1051
  rmSync(sessionDir, { recursive: true, force: true });
@@ -1139,7 +1162,7 @@ test("real AgentSession: the complete system message and a changed tool loadout
1139
1162
  return assistant(fixture, [{ type: "toolCall", id: "wipe-system", name: "empty_brain", arguments: {} }], "toolUse");
1140
1163
  }
1141
1164
  assert.deepEqual(effectiveToolNames, ["empty_brain", "get_context_remaining"]);
1142
- assert.ok(JSON.stringify(context.messages).includes(CONTEXT_WINDOW_OPEN_TAG));
1165
+ assert.ok(JSON.stringify(context.messages).includes(WINDOW_IDENTITY_OPEN_TAG));
1143
1166
  return assistant(fixture, [{ type: "text", text: "all system sections survived" }]);
1144
1167
  },
1145
1168
  });
@@ -1331,7 +1354,7 @@ test("real AgentSession: injected settings managers own live policy and ignore c
1331
1354
  });
1332
1355
  await Promise.all([first.session.prompt("INJECTED_FIRST"), second.session.prompt("INJECTED_SECOND")]);
1333
1356
  await Promise.all([first.session.waitForIdle(), second.session.waitForIdle()]);
1334
- assert.deepEqual(contextRemainingResults(first), [0], "the injected high reserve reaches the warning line in the real tool result");
1357
+ assert.deepEqual(contextRemainingResults(first), [0], "the injected high reserve reaches the hard-reserve line in the real tool result");
1335
1358
  assert.ok((contextRemainingResults(second)[0] ?? 0) > 0, "the second injected reserve produces a distinct real tool result");
1336
1359
  assert.equal(resetMarkers(first).length, 1, "enabled injected policy resets at the first session's reserve");
1337
1360
  assert.equal(resetMarkers(second).length, 0, "disabled injected policy does not inherit the first session's reset decision");
@@ -5,11 +5,11 @@ import { rmSync, writeFileSync } from "node:fs";
5
5
  import test from "node:test";
6
6
  import { historyFromSession } from "../src/pi/history.js";
7
7
  import { BOOT_TYPE, GUIDANCE_TYPE, RESET_MARKER_TYPE } from "../src/pi/entries.js";
8
- import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
9
- import { CONTINUATION } from "../src/budget/text.js";
8
+ import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
9
+ import { FORCED_CONTINUATIONS, NORMAL_CONTINUATIONS } from "../src/budget/text.js";
10
10
  import { listNotes } from "./helpers/notes.js";
11
11
  import { CONTINUATION_TYPE, MANUAL_WIPE_TYPE } from "../src/pi/entries.js";
12
- import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultData, resultJson, resultRead, runContextHook, runContextWithSystemHook, runHandlers, runManualCompact, runCommand, sentOf, } from "./helpers/extension.js";
12
+ import { appendText, assertBootHistory, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultData, resultJson, resultRead, runContextHook, runContextWithSystemHook, runHandlers, runManualCompact, runCommand, sentOf, } from "./helpers/extension.js";
13
13
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
14
14
  const testEnvironment = installExtensionTestHooks("notesoup-integration");
15
15
  test("custom reset marker removes old provider context while history remains searchable", async () => {
@@ -31,11 +31,12 @@ test("custom reset marker removes old provider context while history remains sea
31
31
  assert.equal(checkpoint.summary, "");
32
32
  assert.equal(checkpoint.firstKeptEntryId, checkpoint.id);
33
33
  assert.equal(marker.parentId, checkpoint.id, "marker follows the native checkpoint");
34
- assert.deepEqual(Object.keys(marker.data), ["windowId"]);
34
+ assert.deepEqual(Object.keys(marker.data), ["windowId", "origin"]);
35
+ assert.equal(marker.data.origin, "normal", "an explicit tool wipe records the model's own call as the origin");
35
36
  const projected = await runContextWithSystemHook(captured, ctx, sessionManager.buildSessionContext().messages);
36
37
  const providerText = JSON.stringify(projected?.messages ?? []);
37
38
  assert.equal(providerText.includes("OLD-UNIQUE-TRANSCRIPT"), false);
38
- assert.equal(providerText.includes(CONTEXT_WINDOW_OPEN_TAG), true);
39
+ assert.equal(providerText.includes(WINDOW_IDENTITY_OPEN_TAG), true);
39
40
  assert.equal(providerText.includes(RESET_MARKER_TYPE), false, "plain reset state never reaches the provider");
40
41
  const projection = historyFromSession(ctx);
41
42
  const windows = projection.windows;
@@ -69,16 +70,14 @@ test("the root boot and reset boot carry durable window identity", async () => {
69
70
  assert.equal(noticesOf(ctx).length, 0, "reload is silent");
70
71
  assert.deepEqual(rootBoot?.message.details, { windowId: `pcw:${sessionManager.getSessionId().slice(0, 8)}:root` });
71
72
  const rootText = typeof rootBoot?.message.content === "string" ? rootBoot.message.content : "";
72
- assert.ok(rootText.startsWith(CONTEXT_WINDOW_OPEN_TAG), "root block omits the reset line");
73
- assert.equal(rootText.includes(CONTINUATION), false, "root startup carries no reset message");
74
- assert.equal(rootText.includes("Previous context window id:"), false, "root block omits the previous-id line");
75
- assert.match(rootText, new RegExp(`First context window id: pcw:${sessionManager.getSessionId().slice(0, 8)}:root`));
76
- assert.match(rootText, new RegExp(`Current context window id: pcw:${sessionManager.getSessionId().slice(0, 8)}:root`));
73
+ assert.ok(rootText.startsWith(WINDOW_IDENTITY_OPEN_TAG), "root block omits the reset line");
74
+ assert.equal(rootText.includes(NORMAL_CONTINUATIONS[0]), false, "root startup carries no reset handoff");
75
+ assertBootHistory(rootText, historyFromSession(ctx));
77
76
  assert.ok(rootText.includes("decisions.md"));
78
77
  const decisionsMeta = (await listNotes(ctx, { scope: "session" })).find((row) => row.path === "decisions.md")?.meta;
79
78
  assert.ok(decisionsMeta);
80
79
  assert.match(rootText, /decisions\.md · (?:just now|\d+s ago)/, "boot note metadata carries a relative update time");
81
- assert.ok(rootText.includes(CONTEXT_WINDOW_PROTOCOL_OPEN_TAG));
80
+ assert.ok(rootText.includes(NOTES_PROTOCOL_OPEN_TAG));
82
81
  // Reset: the marker and boot are committed together at the turn boundary.
83
82
  await call(captured, "empty_brain", {}, ctx);
84
83
  assert.equal(noticesOf(ctx).length, 0, "requesting a reset does not announce success");
@@ -86,7 +85,7 @@ test("the root boot and reset boot carry durable window identity", async () => {
86
85
  assert.equal(boundary.continue, true);
87
86
  await runHandlers(captured, "turn_start", {}, ctx);
88
87
  await runHandlers(captured, "agent_settled", {}, ctx);
89
- assert.equal(noticesOf(ctx).filter((notice) => notice.message.includes("Brain emptied")).length, 1, "the committed reset is announced once");
88
+ assert.deepEqual(noticesOf(ctx).filter((notice) => notice.message.includes("Brain emptied")), [{ message: "🥣 Brain emptied", type: "info" }], "the committed reset is announced once");
90
89
  const entries = sessionManager.getBranch();
91
90
  const marker = entries.find((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE);
92
91
  assert.ok(marker && marker.type === "custom");
@@ -94,8 +93,75 @@ test("the root boot and reset boot carry durable window identity", async () => {
94
93
  const resetBoot = entries.find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE && entry.details && typeof entry.details === "object" && entry.details.windowId === resetWindowId);
95
94
  assert.ok(resetBoot && resetBoot.type === "custom_message");
96
95
  assert.equal(resetBoot.details.windowId, marker.data.windowId);
96
+ assertBootHistory(String(resetBoot.content), historyFromSession(ctx));
97
97
  const continuation = entries.find((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
98
98
  assert.ok(continuation && continuation.type === "custom_message" && continuation.display === false, "the resumed run is represented by one hidden continuation");
99
+ assert.ok(NORMAL_CONTINUATIONS.includes(String(continuation.content)), "a tool-requested reset draws the normal handoff");
100
+ });
101
+ test("an empty root boot starts at the first projected seq", async () => {
102
+ const sessionManager = manager();
103
+ const captured = makeExtension(sessionManager);
104
+ const ctx = context(sessionManager);
105
+ await runHandlers(captured, "session_start", { reason: "startup" }, ctx);
106
+ const body = String(captured.sent[0]?.message.content);
107
+ const projection = historyFromSession(ctx);
108
+ assert.equal(projection.windows.length, 1);
109
+ assert.equal(projection.windows[0].items[0].seq, 1);
110
+ assertBootHistory(body, projection);
111
+ });
112
+ test("boot ranges include tool-call slots and both completed reset checkpoints", async () => {
113
+ const sessionManager = manager();
114
+ const captured = makeExtension(sessionManager);
115
+ const ctx = context(sessionManager);
116
+ await runHandlers(captured, "session_start", { reason: "startup" }, ctx);
117
+ appendText(sessionManager, "user", "before tools");
118
+ sessionManager.appendMessage({
119
+ role: "assistant",
120
+ content: [
121
+ { type: "toolCall", id: "boot-call-1", name: "read", arguments: { path: "one" } },
122
+ { type: "toolCall", id: "boot-call-2", name: "read", arguments: { path: "two" } },
123
+ ],
124
+ stopReason: "toolUse",
125
+ timestamp: Date.now(),
126
+ });
127
+ for (const id of ["boot-call-1", "boot-call-2"]) {
128
+ sessionManager.appendMessage({ role: "toolResult", toolCallId: id, toolName: "read", content: [{ type: "text", text: id }], isError: false, timestamp: Date.now() });
129
+ }
130
+ for (let reset = 0; reset < 2; reset++) {
131
+ await call(captured, "empty_brain", {}, ctx);
132
+ await commitTurnEndBoundary(captured, sessionManager, ctx);
133
+ const boot = sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).at(-1);
134
+ assert.ok(boot?.type === "custom_message");
135
+ const projection = historyFromSession(ctx);
136
+ assertBootHistory(String(boot.content), projection);
137
+ assert.equal(projection.pairedResults.size, 2, "paired results still occupy seq slots");
138
+ for (let index = 0; index < projection.windows.length - 1; index++) {
139
+ const old = projection.windows[index];
140
+ assert.equal(Math.max(...old.items.map((item) => item.seq)), projection.windows[index + 1].items[0].seq - 1);
141
+ }
142
+ }
143
+ });
144
+ test("a boot beyond three windows shows only root, the previous window, and the current one", async () => {
145
+ const sessionManager = manager();
146
+ const captured = makeExtension(sessionManager);
147
+ const ctx = context(sessionManager);
148
+ await runHandlers(captured, "session_start", { reason: "startup" }, ctx);
149
+ for (let round = 0; round < 4; round++) {
150
+ appendText(sessionManager, "user", `work before reset ${round}`);
151
+ await call(captured, "empty_brain", {}, ctx);
152
+ await commitTurnEndBoundary(captured, sessionManager, ctx);
153
+ }
154
+ const projection = historyFromSession(ctx);
155
+ assert.equal(projection.windows.length, 5);
156
+ const boot = sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).at(-1);
157
+ assert.ok(boot?.type === "custom_message");
158
+ const identity = String(boot.content).split(WINDOW_IDENTITY_CLOSE_TAG)[0];
159
+ assertBootHistory(String(boot.content), projection);
160
+ // The block is rewritten once per window, so naming every old window would repeat the whole
161
+ // history every time. The omitted middle windows stay reachable through history_*.
162
+ const named = [...identity.matchAll(/^[├└]─ (\S+)/gm)].map((line) => line[1]);
163
+ assert.deepEqual(named, ["root", projection.windows.at(-2).windowId.slice(-8), projection.windows.at(-1).windowId.slice(-8)]);
164
+ assert.equal(identity.includes(projection.windows[1].windowId.slice(-8)), false, "an old middle window is not listed");
99
165
  });
100
166
  test("an aborted async boot repair emits no boot, continuation, or incomplete-notes notice", async () => {
101
167
  const notesHome = process.env.PI_NOTES_HOME;
@@ -138,6 +204,10 @@ test("a marker tail with only metadata repairs its missing boot and continuation
138
204
  assert.ok(branch.findIndex((entry) => entry.id === continuationEntries[0]?.id) > branch.findIndex((entry) => entry.id === bootEntries[0]?.id), "the continuation follows its boot");
139
205
  assert.equal(captured.sent.length, 2, "repair emits only the missing boot and continuation, without a model turn");
140
206
  assert.equal(captured.sent[0]?.message.customType, BOOT_TYPE);
207
+ const repairedIdentity = String(captured.sent[0]?.message.content).split(WINDOW_IDENTITY_CLOSE_TAG)[0];
208
+ const branches = [...repairedIdentity.matchAll(/^[├└]─ (\S+)(.*)$/gm)];
209
+ assert.deepEqual(branches.map((line) => line[1]), ["root", "metadata-tail"]);
210
+ assert.equal(branches.some((line) => /\d+–/.test(line[2])), false, "repair must not invent seq ranges");
141
211
  assert.equal(captured.sent[1]?.message.customType, CONTINUATION_TYPE);
142
212
  assert.equal(noticesOf(ctx).length, 0, "repairing a reset tail is not a new reset");
143
213
  });
@@ -173,6 +243,39 @@ test("a marker tail that already carries a boot repairs only its missing continu
173
243
  assert.equal(captured.sent.length, 1, "a complete reset tail is idempotent");
174
244
  assert.equal(sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE).length, 1);
175
245
  });
246
+ test("repair draws a missing continuation from its marker's pool and never replaces a persisted one", async () => {
247
+ const random = Math.random;
248
+ Math.random = () => 0;
249
+ try {
250
+ const forced = manager(true);
251
+ forced.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:forced-tail", origin: "forced" });
252
+ const forcedCapture = makeExtension(forced);
253
+ await runHandlers(forcedCapture, "session_start", { reason: "startup" }, context(forced));
254
+ const repaired = forced.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
255
+ assert.ok(repaired?.type === "custom_message");
256
+ assert.equal(repaired.content, FORCED_CONTINUATIONS[0], "a repaired tail uses the origin its marker recorded");
257
+ const legacy = manager(true);
258
+ legacy.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:legacy-tail" });
259
+ const legacyCapture = makeExtension(legacy);
260
+ await runHandlers(legacyCapture, "session_start", { reason: "startup" }, context(legacy));
261
+ const legacyRepair = legacy.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
262
+ assert.ok(legacyRepair?.type === "custom_message");
263
+ assert.equal(legacyRepair.content, NORMAL_CONTINUATIONS[0], "a marker written before the fact defaults to normal");
264
+ const kept = manager(true);
265
+ kept.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:kept-tail", origin: "forced" });
266
+ kept.appendCustomMessageEntry(BOOT_TYPE, "already-persisted boot", false, { windowId: "pcw:kept-tail" });
267
+ kept.appendCustomMessageEntry(CONTINUATION_TYPE, NORMAL_CONTINUATIONS[1], false);
268
+ const keptCapture = makeExtension(kept);
269
+ await runHandlers(keptCapture, "session_start", { reason: "reload" }, context(kept));
270
+ assert.equal(keptCapture.sent.length, 0, "a complete tail is never touched");
271
+ const persisted = kept.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
272
+ assert.equal(persisted.length, 1);
273
+ assert.equal(persisted[0].content, NORMAL_CONTINUATIONS[1], "an existing handoff is never redrawn, even when its marker disagrees");
274
+ }
275
+ finally {
276
+ Math.random = random;
277
+ }
278
+ });
176
279
  test("a marker tail followed by real conversation is never repaired", async () => {
177
280
  const sessionManager = manager(true);
178
281
  const windowId = "pcw:unsafe-tail";
@@ -268,6 +371,14 @@ test("notesoup command toggles future work, /empty-brain schedules a turn-end re
268
371
  notices = await runCommand(captured, "notesoup", "", low);
269
372
  assert.match(notices[0]?.message ?? "", /on/);
270
373
  });
374
+ test("forced reset confirmation warns about overflow", async () => {
375
+ const sessionManager = manager();
376
+ const captured = makeExtension(sessionManager);
377
+ const ctx = context(sessionManager, undefined, { tokens: 199_000, contextWindow: 200_000, percent: 99.5 });
378
+ await commitTurnEndBoundary(captured, sessionManager, ctx);
379
+ await runHandlers(captured, "agent_settled", {}, ctx);
380
+ assert.deepEqual(noticesOf(ctx).filter((notice) => notice.message.includes("Brain emptied")), [{ message: "🥣 Brain emptied forcibly: overflow", type: "warning" }]);
381
+ });
271
382
  test("committed reset confirmation survives later work while repair refuses that suffix", async () => {
272
383
  const sessionManager = manager();
273
384
  const captured = makeExtension(sessionManager);
@@ -12,6 +12,7 @@ test("low-budget guidance and warning persist at turn_end, once per active windo
12
12
  const low = context(sessionManager, undefined, { tokens: 165_000, percent: 82.5, contextWindow: 200_000 });
13
13
  const guidance = await runContextHook(captured, low);
14
14
  assert.deepEqual(guidance?.messages.map((message) => message.customType), [GUIDANCE_TYPE], "guidance reaches the crossing request");
15
+ assert.match(String((guidance?.messages[0]).content), /About 18616 tokens of room left in your brain\./, "the reminder reports room to the reserve, not to the warning");
15
16
  assert.equal(captured.sent.length, 0, "guidance does not trigger a detached turn");
16
17
  const guidanceBoundary = await commitTurnEndBoundary(captured, sessionManager, low);
17
18
  assert.equal(guidanceBoundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === GUIDANCE_TYPE).length, 1);
@@ -25,7 +26,7 @@ test("low-budget guidance and warning persist at turn_end, once per active windo
25
26
  assert.equal(warningBoundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1);
26
27
  assert.equal(sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1);
27
28
  });
28
- test("early guidance stays silent and the committed final warning notifies once", async () => {
29
+ test("early guidance stays silent and the final warning notifies immediately once", async () => {
29
30
  const sm = manager();
30
31
  const captured = makeExtension(sm);
31
32
  const early = context(sm, undefined, { tokens: 165_000, percent: 82.5, contextWindow: 200_000 });
@@ -37,12 +38,14 @@ test("early guidance stays silent and the committed final warning notifies once"
37
38
  const final = context(sm, undefined, { tokens: 181_000, percent: 90.5, contextWindow: 200_000 });
38
39
  const warning = await runContextHook(captured, final);
39
40
  assert.equal(warning?.messages[0]?.customType, WARNING_TYPE);
41
+ assert.equal(noticesOf(final).filter((notice) => notice.message === "🥣 Brain almost full · taking notes").length, 1, "notify at injection, before any turn_end");
42
+ await runContextHook(captured, final);
40
43
  await commitTurnEndBoundary(captured, sm, final);
41
44
  await runHandlers(captured, "turn_start", {}, final);
42
45
  await runHandlers(captured, "agent_settled", {}, final);
43
- assert.equal(noticesOf(final).filter((notice) => notice.message === "🥣 Brain almost full · taking notes").length, 1, "only the committed final warning notifies, exactly once");
46
+ assert.equal(noticesOf(final).filter((notice) => notice.message === "🥣 Brain almost full · taking notes").length, 1, "repeated injection and commit do not notify again");
44
47
  });
45
- test("the visible countdown ends at the warning line, clamps at zero, and preserves unknown usage", async () => {
48
+ test("the reported room ends at the hard reserve, clamps at zero, and preserves unknown usage", async () => {
46
49
  const fixture = settingsFixture({
47
50
  reserveTokens: 16_384,
48
51
  project: { compaction: { reserveTokens: 32_768 } },
@@ -54,8 +57,9 @@ test("the visible countdown ends at the warning line, clamps at zero, and preser
54
57
  const ctx = context(sm, undefined, { tokens, contextWindow: 200_000, percent: tokens === null ? null : tokens / 2000 }, true, fixture.cwd, trusted);
55
58
  return resultJson(await call(captured, "get_context_remaining", {}, ctx)).remaining_tokens;
56
59
  };
57
- assert.equal(await readBudget(72_563), 78_285, "the reported 127437 physical tokens exclude reserve plus runway (49152)");
58
- assert.equal(await readBudget(167_232), 0, "inside the runway the countdown reads zero");
60
+ assert.equal(await readBudget(72_563), 94_669, "the reported room excludes only the project reserve (32768)");
61
+ assert.equal(await readBudget(150_848), 16_384, "the warning line still has the entire runway left");
62
+ assert.equal(await readBudget(167_232), 0, "the hard reserve reads zero");
59
63
  assert.equal(await readBudget(190_000), 0, "below the reserve, still zero");
60
64
  assert.equal(await readBudget(210_000), 0, "over the physical window");
61
65
  assert.equal(await readBudget(null), null, "unknown usage remains unknown");
@@ -63,7 +67,7 @@ test("the visible countdown ends at the warning line, clamps at zero, and preser
63
67
  assert.equal(resultJson(await call(captured, "get_context_remaining", {}, absent)).remaining_tokens, null);
64
68
  const untrusted = context(sm, undefined, { tokens: 72_563, contextWindow: 200_000, percent: 36.2815 }, true, fixture.cwd, false);
65
69
  await runHandlers(captured, "session_start", {}, untrusted);
66
- assert.equal(await readBudget(72_563, false), 94_669, "session start reloads the global reserve when the project is untrusted");
70
+ assert.equal(await readBudget(72_563, false), 111_053, "session start reloads the global reserve when the project is untrusted");
67
71
  });
68
72
  test("absent notesoup key or margins reproduce the default reminder threshold at Pi's default reserve", async () => {
69
73
  assert.equal(DEFAULT_RESERVE_TOKENS, 16_384);
@@ -0,0 +1 @@
1
+ export {};