notesoup 0.47.1 → 0.48.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 (78) hide show
  1. package/README.md +1 -1
  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 +59 -11
  6. package/dist/src/budget/text.d.ts +29 -9
  7. package/dist/src/budget/text.js +51 -10
  8. package/dist/src/claude/helper.d.ts +2 -3
  9. package/dist/src/claude/helper.js +45 -11
  10. package/dist/src/claude/history.d.ts +9 -0
  11. package/dist/src/claude/history.js +271 -0
  12. package/dist/src/dsh/engine.d.ts +2 -1
  13. package/dist/src/dsh/engine.js +18 -9
  14. package/dist/src/dsh/index.js +9 -4
  15. package/dist/src/dsh/window.d.ts +2 -1
  16. package/dist/src/dsh/window.js +14 -8
  17. package/dist/src/history/query.js +59 -81
  18. package/dist/src/notes/address.d.ts +5 -0
  19. package/dist/src/notes/address.js +20 -21
  20. package/dist/src/notes/store.js +12 -19
  21. package/dist/src/pi/boot.d.ts +1 -1
  22. package/dist/src/pi/boot.js +28 -5
  23. package/dist/src/pi/budget.d.ts +0 -2
  24. package/dist/src/pi/budget.js +13 -53
  25. package/dist/src/pi/entries.d.ts +0 -1
  26. package/dist/src/pi/entries.js +0 -1
  27. package/dist/src/pi/history.d.ts +3 -0
  28. package/dist/src/pi/history.js +4 -0
  29. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  30. package/dist/src/pi/reset/artifacts.js +16 -14
  31. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  32. package/dist/src/pi/reset/lifecycle.js +48 -72
  33. package/dist/src/pi/runtime.js +6 -6
  34. package/dist/src/pi/window.d.ts +12 -6
  35. package/dist/src/pi/window.js +7 -0
  36. package/dist/test/agent-loop.test.js +52 -29
  37. package/dist/test/boot.integration.test.js +114 -11
  38. package/dist/test/budget-settings.integration.test.js +4 -2
  39. package/dist/test/claude-history.test.d.ts +1 -0
  40. package/dist/test/claude-history.test.js +184 -0
  41. package/dist/test/claude-mod.test.js +236 -42
  42. package/dist/test/dsh.test.js +79 -2
  43. package/dist/test/helpers/extension.d.ts +3 -0
  44. package/dist/test/helpers/extension.js +33 -5
  45. package/dist/test/history.integration.test.js +66 -0
  46. package/dist/test/host-neutral.test.js +1 -1
  47. package/dist/test/model-facing-text.test.d.ts +1 -0
  48. package/dist/test/model-facing-text.test.js +181 -0
  49. package/dist/test/notes.integration.test.js +16 -18
  50. package/dist/test/reset-lifecycle.test.js +201 -46
  51. package/docs/architecture.md +3 -3
  52. package/docs/claude-code-mod.md +15 -3
  53. package/docs/dsh.md +1 -1
  54. package/docs/reset-lifecycle.md +32 -20
  55. package/docs/skills.md +1 -1
  56. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  57. package/mods/notesoup/dist/claude/helper.js +836 -92
  58. package/mods/notesoup/hooks/register.ts +140 -38
  59. package/package.json +1 -1
  60. package/src/boot/render.ts +41 -23
  61. package/src/boot/text.ts +68 -11
  62. package/src/budget/text.ts +61 -10
  63. package/src/claude/helper.ts +53 -22
  64. package/src/claude/history.ts +228 -0
  65. package/src/dsh/engine.ts +16 -9
  66. package/src/dsh/index.ts +8 -3
  67. package/src/dsh/window.ts +15 -9
  68. package/src/history/query.ts +57 -82
  69. package/src/notes/address.ts +19 -16
  70. package/src/notes/store.ts +9 -14
  71. package/src/pi/boot.ts +27 -5
  72. package/src/pi/budget.ts +13 -50
  73. package/src/pi/entries.ts +0 -1
  74. package/src/pi/history.ts +7 -2
  75. package/src/pi/reset/artifacts.ts +17 -14
  76. package/src/pi/reset/lifecycle.ts +56 -79
  77. package/src/pi/runtime.ts +6 -6
  78. 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
  });
@@ -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");
@@ -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";
@@ -25,7 +25,7 @@ test("low-budget guidance and warning persist at turn_end, once per active windo
25
25
  assert.equal(warningBoundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1);
26
26
  assert.equal(sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === WARNING_TYPE).length, 1);
27
27
  });
28
- test("early guidance stays silent and the committed final warning notifies once", async () => {
28
+ test("early guidance stays silent and the final warning notifies immediately once", async () => {
29
29
  const sm = manager();
30
30
  const captured = makeExtension(sm);
31
31
  const early = context(sm, undefined, { tokens: 165_000, percent: 82.5, contextWindow: 200_000 });
@@ -37,10 +37,12 @@ test("early guidance stays silent and the committed final warning notifies once"
37
37
  const final = context(sm, undefined, { tokens: 181_000, percent: 90.5, contextWindow: 200_000 });
38
38
  const warning = await runContextHook(captured, final);
39
39
  assert.equal(warning?.messages[0]?.customType, WARNING_TYPE);
40
+ assert.equal(noticesOf(final).filter((notice) => notice.message === "🥣 Brain almost full · taking notes").length, 1, "notify at injection, before any turn_end");
41
+ await runContextHook(captured, final);
40
42
  await commitTurnEndBoundary(captured, sm, final);
41
43
  await runHandlers(captured, "turn_start", {}, final);
42
44
  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");
45
+ assert.equal(noticesOf(final).filter((notice) => notice.message === "🥣 Brain almost full · taking notes").length, 1, "repeated injection and commit do not notify again");
44
46
  });
45
47
  test("the visible countdown ends at the warning line, clamps at zero, and preserves unknown usage", async () => {
46
48
  const fixture = settingsFixture({
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,184 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { claudeHistoryFromJsonl, readClaudeHistory } from "../src/claude/history.js";
7
+ import { renderBootBlock } from "../src/boot/render.js";
8
+ import { unavailableNotesSnapshot } from "../src/boot/snapshot.js";
9
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
10
+ import { allItems, eventDocument } from "../src/history/history.js";
11
+ import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
12
+ import { dispatch } from "../src/claude/helper.js";
13
+ const sessionId = "synthetic-session";
14
+ function row(uuid, parentUuid, type, content, extra = {}) {
15
+ return { uuid, parentUuid, type, sessionId, timestamp: "2026-01-01T00:00:00Z", isSidechain: false,
16
+ ...(type === "system" ? { content } : { message: { role: type, content } }), ...extra };
17
+ }
18
+ const user = (uuid, parent, text) => row(uuid, parent, "user", text);
19
+ const assistant = (uuid, parent, content) => row(uuid, parent, "assistant", content);
20
+ const call = (id, name = "bash") => ({ type: "tool_use", id, name, input: { command: `echo ${id}` } });
21
+ const result = (id, text, error = false) => ({ type: "tool_result", tool_use_id: id, content: text, is_error: error });
22
+ const jsonl = (rows) => `${rows.map((row) => JSON.stringify(row)).join("\n")}\n`;
23
+ const project = (rows, headUuid) => claudeHistoryFromJsonl(jsonl(rows), { sessionId, headUuid });
24
+ // Complete boot shape, not a real/private transcript fixture. `context_window` is the pre-rename
25
+ // spelling that transcripts already on disk carry; both spellings must yield the same ordinal.
26
+ const bootText = (ordinal, spelling = "legacy") => spelling === "legacy"
27
+ ? `<context_window>\nAgent name: claude (brain: claude)\n\nclaude:${sessionId}\n</context_window>\n\n<context_window_protocol>\nSynthetic reset protocol\n</context_window_protocol>\nCurrent context window id: claude:${sessionId}:${ordinal}`
28
+ : `<notesoup:window_identity>\nAgent name: claude (brain: claude)\n\nclaude:${sessionId}\n</notesoup:window_identity>\n\n<notesoup:notes_protocol>\nSynthetic reset protocol\n</notesoup:notes_protocol>\nCurrent context window id: claude:${sessionId}:${ordinal}`;
29
+ function compact(uuid, logical, metadata = {}) {
30
+ return row(uuid, null, "system", "Conversation compacted", { subtype: "compact_boundary", logicalParentUuid: logical, compactMetadata: metadata });
31
+ }
32
+ test("Claude append and result arrival preserve call addresses and use the shared paired read", async () => {
33
+ const rows = [user("u", null, "run tools"), assistant("a", "u", [{ type: "thinking", thinking: "private thought" }, { type: "text", text: "working" }, call("one"), call("two")])];
34
+ const pending = project(rows, "a");
35
+ assert.equal(pending.highestSeq, 4);
36
+ assert.equal(allItems(pending).find((event) => event.seq === 3)?.execution?.status, "unfinished");
37
+ assert.doesNotMatch(allItems(pending).map(eventDocument).join("\n"), /private thought/);
38
+ rows.push(row("r", "a", "user", [result("two", "failure", true), result("one", [{ type: "text", text: "output one" }, { type: "thinking", thinking: "hidden result thinking" }])]));
39
+ const completed = project(rows, "r");
40
+ assert.equal(completed.highestSeq, 7);
41
+ const read = await historyRead.execute({ seq: 3 }, completed);
42
+ assert.ok(read.ok);
43
+ assert.equal(read.data.tool_status, "ok");
44
+ assert.match(read.data.text, /bash \{"command":"echo one"\}\n--- output ---\noutput one/);
45
+ assert.doesNotMatch(read.data.text, /hidden/);
46
+ assert.equal(allItems(completed).find((event) => event.seq === 4)?.execution?.status, "error");
47
+ const resultRead = await historyRead.execute({ seq: 7 }, completed);
48
+ assert.ok(!resultRead.ok);
49
+ assert.equal(resultRead.error.code, "not_an_event");
50
+ assert.match(resultRead.error.message, /read seq 3/);
51
+ const search = await historyList.execute({ query: "output one" }, completed);
52
+ assert.ok(search.ok);
53
+ assert.deepEqual(search.data.items.map((item) => "seq" in item ? item.seq : -1), [3]);
54
+ });
55
+ test("Claude duplicate UUID records do not allocate again or move addresses on reload", () => {
56
+ const u = user("u", null, "hello"), a = assistant("a", "u", [call("one")]);
57
+ const original = project([u, a], "a");
58
+ const repeated = [u, a, { ...u, cwd: "/new/provenance" }, { ...a, cwd: "/new/provenance" }];
59
+ const reloaded = project(repeated, "a");
60
+ assert.equal(reloaded.highestSeq, original.highestSeq);
61
+ assert.deepEqual(reloaded, original);
62
+ assert.deepEqual(project(repeated, "a"), reloaded);
63
+ });
64
+ test("Claude branch selection is bound to committed head, not append order or last-prompt", async () => {
65
+ const rows = [user("u", null, "root"), assistant("left", "u", [call("left-call")]), row("left-result", "left", "user", [result("left-call", "left output")]), assistant("right", "u", [{ type: "text", text: "right branch" }]), { type: "last-prompt", leafUuid: "right", sessionId }];
66
+ const left = project(rows, "left-result"), right = project(rows, "right");
67
+ assert.equal(left.highestSeq, right.highestSeq);
68
+ assert.ok(!allItems(left).some((event) => event.text === "right branch"));
69
+ assert.equal(left.pairedResults.get(5), 3);
70
+ assert.deepEqual(allItems(right).map((event) => event.seq), [1, 6]);
71
+ const offBranch = await historyRead.execute({ seq: 3 }, right);
72
+ assert.ok(!offBranch.ok);
73
+ assert.equal(offBranch.error.code, "not_on_branch");
74
+ assert.throws(() => claudeHistoryFromJsonl(jsonl(rows), { sessionId }), /no confirmed active head/);
75
+ assert.throws(() => project(rows, "not-written-yet"), /not persisted yet/);
76
+ });
77
+ test("a persisted boot yields its ordinal under both tag spellings", () => {
78
+ // Three boundaries but one boot: only a recognised boot explains the ordinal.
79
+ const rowsFor = (boot) => [user("u", null, "old request"), assistant("a", "u", [{ type: "text", text: "answered" }]), compact("boundary", "a"), row("boot", "boundary", "user", boot), user("after", "boot", "after reset")];
80
+ const legacy = project(rowsFor(bootText(3)), "after");
81
+ const current = project(rowsFor(bootText(3, "current")), "after");
82
+ assert.equal(allItems(legacy).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:3`, "an old-spelling boot numbers the window it opens");
83
+ assert.deepEqual(current.windows.map((window) => window.windowId), legacy.windows.map((window) => window.windowId));
84
+ const rendered = renderBootBlock({
85
+ agentName: "claude",
86
+ modelName: "claude",
87
+ tree: { trunk: `claude:${sessionId}`, windows: [{ shortName: "3", isCurrent: true }] },
88
+ notes: unavailableNotesSnapshot(Date.now()),
89
+ tools: DEFAULT_BOOT_TOOL_NAMES,
90
+ });
91
+ const real = project(rowsFor(`${rendered}\nCurrent context window id: claude:${sessionId}:3`), "after");
92
+ assert.deepEqual(real.windows.map((window) => window.windowId), current.windows.map((window) => window.windowId));
93
+ const partial = `<notesoup:window_identity>\nAgent name: claude (brain: claude)\n\nclaude:${sessionId}\n</notesoup:window_identity>\nCurrent context window id: claude:${sessionId}:3`;
94
+ assert.equal(allItems(project(rowsFor(partial), "after")).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:1`, "an identity line without the protocol block is not a trusted boot");
95
+ });
96
+ test("Claude native compaction and reset keep pre-reset history, preserved rewrites and matching boot windows", async () => {
97
+ const old = assistant("old", "u", [{ type: "text", text: "before first reset" }]);
98
+ const reset = row("boot", "boundary", "user", bootText(1));
99
+ const rows = [user("u", null, "old request"), old,
100
+ compact("boundary", "old", { preservedSegment: { headUuid: "old", tailUuid: "old", anchorUuid: "boot" }, preservedMessages: { allUuids: ["old", "virtual-unpersisted-attachment"] } }), reset,
101
+ { ...old, parentUuid: "boot" }, assistant("new", "old", [{ type: "text", text: "after first reset" }]),
102
+ compact("second", "new"), row("boot2", "second", "user", bootText(2)), user("latest", "boot2", "after second reset")];
103
+ const projection = project(rows, "latest");
104
+ assert.deepEqual(projection.windows.map((window) => window.windowId), [0, 1, 2].map((ordinal) => `claude:${sessionId}:${ordinal}`));
105
+ assert.equal(allItems(projection).filter((event) => event.text === "before first reset").length, 1);
106
+ assert.equal(allItems(projection).find((event) => event.text === "before first reset")?.windowId, `claude:${sessionId}:0`);
107
+ assert.equal(allItems(projection).find((event) => event.text === "after first reset")?.windowId, `claude:${sessionId}:1`);
108
+ assert.equal(projection.highestSeq, 8);
109
+ const previous = await historyList.execute({ window_id: "@previous", roles: ["assistant"] }, projection);
110
+ assert.ok(previous.ok);
111
+ assert.deepEqual(previous.data.items.map((item) => "content" in item ? item.content : ""), ["after first reset"]);
112
+ const windows = await historyWindows.execute({}, projection, sessionId);
113
+ assert.ok(windows.ok);
114
+ assert.equal(windows.data.windows[0]?.first_seq, 1);
115
+ assert.deepEqual(project(rows, "latest"), projection, "reload does not need an in-memory seq cache");
116
+ });
117
+ test("Claude reset crosses native turn_duration graph metadata with no message content", async () => {
118
+ const duration = { type: "system", subtype: "turn_duration", uuid: "duration", parentUuid: "old", sessionId, durationMs: 123, messageCount: 2 };
119
+ const rows = [user("u", null, "marker before reset"), assistant("old", "u", [{ type: "text", text: "finished turn" }]), duration,
120
+ compact("boundary", "duration"), row("boot", "boundary", "user", bootText(1)), user("continuation", "boot", "continue")];
121
+ const projection = project(rows, "continuation");
122
+ assert.equal(projection.highestSeq, 5, "duration metadata does not allocate a message address");
123
+ assert.equal(projection.windows.length, 2);
124
+ assert.ok(allItems(projection).some((event) => event.text === "marker before reset"));
125
+ assert.ok((await historyList.execute({ window_id: "@previous" }, projection)).ok);
126
+ assert.ok((await historyRead.execute({ seq: 2 }, projection)).ok);
127
+ assert.ok((await historyWindows.execute({}, projection, sessionId)).ok);
128
+ });
129
+ test("Claude resolves forward persisted ancestry without renumbering or using later rewritten parent versions", () => {
130
+ const notice = row("notice", "attachment", "system", "hook notice");
131
+ const attachment = { type: "attachment", uuid: "attachment", parentUuid: "u", sessionId };
132
+ const rows = [user("u", null, "root"), notice, attachment, compact("boundary", "notice"),
133
+ row("boot", "boundary", "user", bootText(1), { isCompactSummary: true }), { ...attachment, parentUuid: "boot" }, user("new", "attachment", "after reset")];
134
+ const projection = project(rows, "new");
135
+ assert.equal(projection.highestSeq, 6);
136
+ assert.equal(allItems(projection).find((event) => event.text === "hook notice")?.seq, 2);
137
+ assert.equal(allItems(projection).find((event) => event.text === "hook notice")?.windowId, `claude:${sessionId}:0`);
138
+ assert.equal(allItems(projection).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:1`);
139
+ assert.deepEqual(project(rows, "new"), projection);
140
+ assert.throws(() => project([notice], "notice"), /missing.*ancestor/);
141
+ assert.equal(project([user("u", null, bootText(9))], "u").windows.length, 1, "ordinary user text is not a trusted retained boot");
142
+ });
143
+ test("Claude attachments expose recorded renderings only and keep non-rendered nodes in ancestry", () => {
144
+ const rows = [user("u", null, "hi"), { type: "attachment", uuid: "raw", parentUuid: "u", sessionId, attachment: { type: "prompt_snapshot", content: "must not invent raw payload" } },
145
+ { type: "attachment", uuid: "rendered", parentUuid: "raw", sessionId, renderedRole: "user", rendered: [{ content: [{ type: "text", text: "visible injection" }] }] }];
146
+ const projection = project(rows, "rendered");
147
+ assert.deepEqual(allItems(projection).map((event) => event.seq), [1, 2, 3]);
148
+ assert.equal(allItems(projection).at(-1)?.role, "context");
149
+ assert.match(allItems(projection).map(eventDocument).join("\n"), /visible injection/);
150
+ assert.doesNotMatch(allItems(projection).map(eventDocument).join("\n"), /must not invent/);
151
+ });
152
+ test("Claude tolerates only the uncommitted JSONL tail, not malformed committed lines or unknown message shapes", () => {
153
+ const text = jsonl([user("u", null, "first")]);
154
+ assert.deepEqual(claudeHistoryFromJsonl(`${text}{\"type\":\"user\"`, { sessionId, headUuid: "u" }), project([user("u", null, "first")], "u"));
155
+ assert.equal(claudeHistoryFromJsonl(text.trimEnd(), { sessionId, headUuid: "u" }).highestSeq, 1);
156
+ assert.throws(() => claudeHistoryFromJsonl(`${text}{broken}\n`, { sessionId, headUuid: "u" }), /malformed.*line 2/);
157
+ assert.throws(() => project([user("u", null, "first"), { type: "new-message-schema", uuid: "unknown" }], "u"), /unsupported.*record type/);
158
+ assert.throws(() => project([row("u", null, "user", [{ type: "new-block-schema" }])], "u"), /unsupported.*content block/);
159
+ assert.throws(() => project([row("u", null, "user", { type: "text", text: "not an array" })], "u"), /message content/);
160
+ assert.throws(() => project([user("u", null, "first"), user("u", null, "conflict")], "u"), /conflicting.*duplicate UUID/);
161
+ assert.throws(() => project([{ ...user("u", null, "first"), isSidechain: true }], "u"), /only the main/);
162
+ assert.throws(() => project([{ ...user("u", null, "first"), sessionId: "another-session" }], "u"), /different session/);
163
+ });
164
+ test("Claude helper history tools reuse shared schemas, outcomes and text rendering from a supplied path", async (t) => {
165
+ const root = mkdtempSync(join(tmpdir(), "claude-history-"));
166
+ t.after(() => rmSync(root, { recursive: true, force: true }));
167
+ const transcriptPath = join(root, "transcript.jsonl"), rows = [user("u", null, "remember this"), assistant("a", "u", [call("one")]), row("r", "a", "user", [result("one", "recorded output")])];
168
+ writeFileSync(transcriptPath, jsonl(rows));
169
+ const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
170
+ const history = { sessionId, transcriptPath, headUuid: "r" };
171
+ const projection = await readClaudeHistory(history);
172
+ const operations = [historyList, historyRead, historyWindows];
173
+ for (const operation of operations) {
174
+ const params = operation.name === "history_read" ? { seq: 3 } : {};
175
+ const actual = await dispatch({ op: "tool", tool: operation.name, params, identity, history });
176
+ const expected = operation.name === "history_read" ? { text: historyRead.render(await historyRead.execute({ seq: 3 }, projection)), ok: true }
177
+ : operation.name === "history_list" ? { text: historyList.render(await historyList.execute({}, projection)), ok: true }
178
+ : { text: historyWindows.render(await historyWindows.execute({}, projection, sessionId)), ok: true };
179
+ assert.deepEqual(actual, expected);
180
+ }
181
+ assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 0 });
182
+ await assert.rejects(dispatch({ op: "tool", tool: "history_windows", params: {}, identity }), /transcript_path is unavailable/);
183
+ await assert.rejects(dispatch({ op: "tool", tool: "history_windows", params: {}, identity, history: { ...history, sessionId: "other" } }), /different session/);
184
+ });