notesoup 0.53.2 → 0.54.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 (131) hide show
  1. package/README.md +2 -2
  2. package/dist/plugins/claude/src/helper.js +2 -1
  3. package/dist/plugins/codex/src/hooks.js +1 -1
  4. package/dist/plugins/codex/src/identity.d.ts +1 -1
  5. package/dist/plugins/codex/src/identity.js +3 -3
  6. package/dist/plugins/codex/src/mcp.js +2 -1
  7. package/dist/plugins/codex/src/text.d.ts +1 -1
  8. package/dist/plugins/codex/src/text.js +2 -2
  9. package/dist/plugins/dsh/engine.js +2 -2
  10. package/dist/plugins/dsh/tools.js +8 -7
  11. package/dist/plugins/dsh/window.d.ts +1 -0
  12. package/dist/plugins/dsh/window.js +7 -3
  13. package/dist/plugins/pi/history-tools.d.ts +1 -1
  14. package/dist/plugins/pi/history-tools.js +4 -4
  15. package/dist/plugins/pi/notes/tools.js +8 -6
  16. package/dist/plugins/pi/render.js +7 -4
  17. package/dist/plugins/pi/runtime.js +2 -2
  18. package/dist/plugins/pi/window.js +21 -7
  19. package/dist/src/boot/render.js +7 -7
  20. package/dist/src/boot/snapshot.d.ts +7 -7
  21. package/dist/src/boot/snapshot.js +17 -17
  22. package/dist/src/boot/text.d.ts +2 -2
  23. package/dist/src/boot/text.js +7 -5
  24. package/dist/src/dream/git.d.ts +2 -11
  25. package/dist/src/dream/git.js +6 -23
  26. package/dist/src/dream/lock.d.ts +2 -2
  27. package/dist/src/dream/lock.js +3 -3
  28. package/dist/src/index.d.ts +2 -1
  29. package/dist/src/index.js +3 -2
  30. package/dist/src/notes/address.d.ts +8 -8
  31. package/dist/src/notes/address.js +13 -13
  32. package/dist/src/notes/errors.d.ts +1 -1
  33. package/dist/src/notes/frontmatter.js +2 -2
  34. package/dist/src/notes/index.d.ts +1 -1
  35. package/dist/src/notes/index.js +1 -1
  36. package/dist/src/notes/paths.d.ts +6 -6
  37. package/dist/src/notes/paths.js +9 -9
  38. package/dist/src/notes/{project-home.d.ts → project-namespace.d.ts} +7 -7
  39. package/dist/src/notes/{project-home.js → project-namespace.js} +67 -25
  40. package/dist/src/notes/store.d.ts +4 -4
  41. package/dist/src/notes/store.js +55 -52
  42. package/dist/src/tools/dream.d.ts +21 -3
  43. package/dist/src/tools/dream.js +54 -16
  44. package/dist/src/tools/notes-context.d.ts +10 -0
  45. package/dist/src/tools/notes-context.js +27 -0
  46. package/dist/src/tools/notes.d.ts +69 -20
  47. package/dist/src/tools/notes.js +40 -31
  48. package/dist/test/boot.integration.test.js +1 -1
  49. package/dist/test/claude-mod.test.js +89 -43
  50. package/dist/test/codex-plugin.test.js +18 -1
  51. package/dist/test/context-edit-budget.test.js +121 -0
  52. package/dist/test/dependencies.test.js +71 -4
  53. package/dist/test/dream-tools.test.js +153 -8
  54. package/dist/test/dsh.test.js +62 -15
  55. package/dist/test/helpers/dsh.d.ts +4 -1
  56. package/dist/test/helpers/dsh.js +20 -4
  57. package/dist/test/helpers/extension.d.ts +5 -0
  58. package/dist/test/helpers/extension.js +33 -2
  59. package/dist/test/host-neutral.test.js +17 -15
  60. package/dist/test/model-facing-text.test.js +12 -8
  61. package/dist/test/notes-cwd.test.js +114 -0
  62. package/dist/test/notes-library.test.js +4 -4
  63. package/dist/test/notes-query-namespaces.test.d.ts +1 -0
  64. package/dist/test/{notes-query-homes.test.js → notes-query-namespaces.test.js} +13 -13
  65. package/dist/test/notes.integration.test.js +72 -23
  66. package/dist/test/notes.test.js +50 -20
  67. package/dist/test/pi-render.test.js +33 -1
  68. package/dist/test/project-namespace.test.d.ts +1 -0
  69. package/dist/test/project-namespace.test.js +324 -0
  70. package/docs/architecture.md +12 -7
  71. package/docs/codex.md +4 -4
  72. package/docs/dsh.md +8 -8
  73. package/docs/notes-library.md +9 -5
  74. package/docs/skills.md +3 -3
  75. package/docs/tool-results.md +6 -2
  76. package/package.json +4 -6
  77. package/playbook.md +6 -6
  78. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  79. package/plugins/claude/dist/claude/helper.js +677 -615
  80. package/plugins/claude/hooks/register.ts +19 -11
  81. package/plugins/claude/playbook.md +6 -6
  82. package/plugins/claude/skills/memory/SKILL.md +4 -4
  83. package/plugins/claude/src/helper.ts +3 -2
  84. package/plugins/codex/README.md +1 -1
  85. package/plugins/codex/dist/codex/notesoup.js +877 -815
  86. package/plugins/codex/src/hooks.ts +1 -1
  87. package/plugins/codex/src/identity.ts +3 -3
  88. package/plugins/codex/src/mcp.ts +2 -1
  89. package/plugins/codex/src/text.ts +2 -2
  90. package/plugins/dsh/engine.ts +2 -2
  91. package/plugins/dsh/tools.ts +8 -7
  92. package/plugins/dsh/window.ts +8 -3
  93. package/plugins/paseo/OVERVIEW.md +4 -4
  94. package/plugins/paseo/README.md +1 -1
  95. package/plugins/paseo/client/brain-empty-card.tsx +3 -4
  96. package/plugins/paseo/client/markdown.tsx +179 -0
  97. package/plugins/paseo/client/notes-op-card.tsx +35 -34
  98. package/plugins/paseo/client/notes-op-transformer.ts +17 -68
  99. package/plugins/paseo/client/paper-card.tsx +8 -19
  100. package/plugins/paseo/client/paper-palette.ts +40 -0
  101. package/plugins/paseo/client/sticky-card.tsx +6 -4
  102. package/plugins/paseo/package.json +3 -0
  103. package/plugins/paseo/paseo-plugin.json +2 -2
  104. package/plugins/paseo/shared/notes-op.ts +13 -9
  105. package/plugins/paseo/test/notes-op.test.ts +52 -73
  106. package/plugins/paseo/test/paper-palette.test.ts +54 -0
  107. package/plugins/pi/history-tools.ts +4 -4
  108. package/plugins/pi/notes/tools.ts +8 -6
  109. package/plugins/pi/render.ts +6 -4
  110. package/plugins/pi/runtime.ts +2 -2
  111. package/plugins/pi/window.ts +22 -7
  112. package/skills/memory/SKILL.md +4 -4
  113. package/src/boot/render.ts +8 -8
  114. package/src/boot/snapshot.ts +20 -20
  115. package/src/boot/text.ts +7 -5
  116. package/src/dream/git.ts +7 -24
  117. package/src/dream/lock.ts +3 -3
  118. package/src/index.ts +4 -3
  119. package/src/notes/address.ts +13 -13
  120. package/src/notes/errors.ts +1 -1
  121. package/src/notes/frontmatter.ts +2 -2
  122. package/src/notes/index.ts +1 -1
  123. package/src/notes/paths.ts +9 -9
  124. package/src/notes/{project-home.ts → project-namespace.ts} +59 -28
  125. package/src/notes/store.ts +61 -58
  126. package/src/tools/dream.ts +63 -16
  127. package/src/tools/notes-context.ts +29 -0
  128. package/src/tools/notes.ts +39 -29
  129. package/dist/test/project-home.test.js +0 -134
  130. /package/dist/test/{notes-query-homes.test.d.ts → context-edit-budget.test.d.ts} +0 -0
  131. /package/dist/test/{project-home.test.d.ts → notes-cwd.test.d.ts} +0 -0
@@ -13,10 +13,19 @@ import { PROTOCOL_WIPE_SENTENCE, renderProtocolBlock } from "../src/boot/text.js
13
13
  import { CLAUDE_WARNING_PROMPT } from "../plugins/claude/src/text.js";
14
14
  import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, NORMAL_CONTINUATIONS, warningNotice } from "../src/budget/text.js";
15
15
  import { createNotesStore } from "../src/notes/index.js";
16
- import { resolveProjectHome } from "../src/notes/project-home.js";
16
+ import { resolveProjectNamespace } from "../src/notes/project-namespace.js";
17
17
  import { notesIdentityFromPi } from "../plugins/pi/notes/adapter.js";
18
18
  import { context, manager } from "./helpers/extension.js";
19
19
  const identity = { home: mkdtempSync(join(tmpdir(), "claude-mod-")), sessionId: "session", cwd: process.cwd(), agent: "claude", model: "claude" };
20
+ /** Every fake completion satisfies the host contract; success is explicit, never an omitted reason. */
21
+ function turnComplete(overrides = {}) {
22
+ const reason = overrides.reason ?? "answer";
23
+ return {
24
+ answer: reason === "answer" ? "done" : "", durationMs: 1, turnId: "turn-1",
25
+ ...overrides, reason, isAborted: reason === "aborted",
26
+ ...(reason === "refusal" ? { refusal: overrides.refusal ?? { category: null, explanation: null } } : {}),
27
+ };
28
+ }
20
29
  async function callTool(tool, params) {
21
30
  return await dispatch({ op: "tool", tool, identity, params });
22
31
  }
@@ -107,6 +116,20 @@ test("Claude helper delivers only shared rendered text and success", async () =>
107
116
  assert.deepEqual(Object.keys(missing).sort(), ["ok", "text"]);
108
117
  assert.match(missing.text, /^error: not_found: /, "the refusal renders as the shared error line");
109
118
  });
119
+ test("Claude resolves relative cwd against the request identity, not the helper process", async (t) => {
120
+ const base = join(identity.home, "base"), other = join(identity.home, "other");
121
+ mkdirSync(base);
122
+ mkdirSync(other);
123
+ t.after(() => { rmSync(base, { recursive: true, force: true }); rmSync(other, { recursive: true, force: true }); });
124
+ const requestIdentity = { ...identity, cwd: base };
125
+ const written = await dispatch({ op: "tool", tool: "notes_write", identity: requestIdentity, params: { address: "@project/selected", content: "from Claude", cwd: "../other" } });
126
+ assert.equal(written.ok, true, written.text);
127
+ const project = resolveProjectNamespace(other, identity.home);
128
+ assert.match(readFileSync(join(project.dir, "selected.md"), "utf8"), /from Claude/);
129
+ const read = await dispatch({ op: "tool", tool: "notes_read", identity: requestIdentity, params: { address: "@project/selected", cwd: "../other" } });
130
+ assert.equal(read.ok, true, read.text);
131
+ assert.match(read.text, /from Claude/);
132
+ });
110
133
  test("Claude helper rejects malformed or unknown requests", async () => {
111
134
  const malformed = JSON.parse(await handleLine("not json"));
112
135
  assert.equal(malformed.ok, false);
@@ -360,7 +383,7 @@ test("Claude Mod with NOTESOUP_DISABLED registers nothing and passes every event
360
383
  const native = { skip: "engine default" };
361
384
  const compact = await handlers.get("session.compact")(host, { trigger: "auto" }, async () => native);
362
385
  assert.equal(compact, native, "native compaction runs exactly as if the mod were absent");
363
- const completed = await handlers.get("turn.complete")(host, {}, async () => ({ done: true }));
386
+ const completed = await handlers.get("turn.complete")(host, turnComplete(), async () => ({ done: true }));
364
387
  assert.deepEqual(completed, { done: true }, "turn.complete passes through without a reset");
365
388
  assert.equal(handlers.has("session.measure"), false, "measure has no reset hook");
366
389
  assert.equal(helperCalls, 0, "the helper never runs while disabled");
@@ -512,30 +535,30 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
512
535
  assert.equal(initial.blocks.length, 1, "below the warn point no warning joins the boot");
513
536
  assert.match(initial.blocks[0].text, /Current context window id: claude:hook-session:0/);
514
537
  await invoke("turn.start");
515
- await invoke("turn.complete");
538
+ await invoke("turn.complete", turnComplete());
516
539
  assert.equal(compactions, 0, "140000 is below every resolved point");
517
540
  host.session.usage = async () => { throw new Error("usage unavailable"); };
518
- await invoke("turn.complete");
541
+ await invoke("turn.complete", turnComplete());
519
542
  await invoke("tool.call", { tool: "Read" });
520
543
  assert.equal(notifications.filter((text) => text.includes("Brain fullness unknown")).length, 1, "warning usage failure logs once per session");
521
544
  host.session.usage = async () => measured();
522
545
  await dispatch({ op: "tool", tool: "notes_write", identity: { ...identity, home, cwd: home, sessionId: "hook-session" }, params: { address: "@human/MAP.md", content: "FRESH_NOTES_AT_RESET" } });
523
546
  await invoke("turn.start");
524
547
  tokens = 158_807;
525
- await invoke("turn.complete");
548
+ await invoke("turn.complete", turnComplete());
526
549
  assert.equal(compactions, 0, "one token below the resolved reset point");
527
550
  await invoke("turn.start");
528
551
  tokens = 158_808;
529
552
  assert.equal(compactions, 0, "measure cannot compact under a running turn");
530
- assert.deepEqual(await invoke("turn.complete"), { sentinel: "turn.complete" });
553
+ assert.deepEqual(await invoke("turn.complete", turnComplete()), { sentinel: "turn.complete" });
531
554
  assert.equal(compactions, 0, "the old reset point no longer clears at turn completion");
532
555
  tokens = 190_000;
533
556
  await invoke("turn.start");
534
- await invoke("turn.complete");
557
+ await invoke("turn.complete", turnComplete());
535
558
  assert.equal(compactions, 0, "even beyond the native threshold, only a native auto event or explicit request resets");
536
559
  await invoke("turn.start");
537
560
  await invoke("command.run", { command: "empty" });
538
- await invoke("turn.complete");
561
+ await invoke("turn.complete", turnComplete());
539
562
  assert.equal(compactions, 1);
540
563
  assert.equal(kept.length, 2, "the reset is the notes boot followed by the one reset message");
541
564
  assert.equal(kept[0].role, "user");
@@ -548,6 +571,29 @@ test("Claude Mod crosses old reset thresholds without clearing and retains one f
548
571
  const upstream = { blocks: [{ name: "unrelated", text: "leave this alone" }], sentinel: "kept" };
549
572
  assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => upstream), upstream, "the retained boot is not injected a second time");
550
573
  });
574
+ test("Claude Mod preserves context and cancels a queued reset after an unsuccessful turn", async (t) => {
575
+ for (const reason of ["aborted", "error", "refusal"]) {
576
+ await t.test(reason, async (t) => {
577
+ const home = mkdtempSync(join(tmpdir(), `claude-reset-${reason}-`));
578
+ t.after(() => rmSync(home, { recursive: true, force: true }));
579
+ const { host, notifications } = fakeEngine(home);
580
+ const handlers = new Map();
581
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
582
+ const invoke = (name, event = {}) => handlers.get(name)(host, event, async () => ({ sentinel: name }));
583
+ let compactions = 0;
584
+ host.session.compact = async () => { compactions++; return { skip: "reset must not run" }; };
585
+ await invoke("session.start", { cwd: home, isInteractive: true });
586
+ await invoke("turn.start");
587
+ await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: `reset-${reason}`, last_word: "DO_NOT_KEEP" });
588
+ await invoke("turn.complete", turnComplete({ reason }));
589
+ assert.equal(compactions, 0, `${reason} never submits the queued reset`);
590
+ assert.ok(notifications.some(text => text.includes("cancelled") && text.includes(reason)), `${reason} reports that its request was cancelled`);
591
+ await invoke("turn.start");
592
+ await invoke("turn.complete", turnComplete());
593
+ assert.equal(compactions, 0, `${reason} leaves no pending reset for a later successful turn`);
594
+ });
595
+ }
596
+ });
551
597
  test("Claude headless resets through its own manual command, retries failure and keeps user compact vetoed", async (t) => {
552
598
  const home = mkdtempSync(join(tmpdir(), "claude-headless-home-"));
553
599
  t.after(() => rmSync(home, { recursive: true, force: true }));
@@ -571,11 +617,11 @@ test("Claude headless resets through its own manual command, retries failure and
571
617
  await invoke("session.start", { cwd: home, isInteractive: false });
572
618
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
573
619
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", last_word: "STICKY", tool_use_id: "reset" });
574
- await invoke("turn.complete");
620
+ await invoke("turn.complete", turnComplete());
575
621
  assert.equal(attempts, 1);
576
622
  assert.ok(notifications.some(x => x.includes("command unavailable")));
577
623
  reject = false;
578
- await invoke("turn.complete");
624
+ await invoke("turn.complete", turnComplete());
579
625
  assert.equal(attempts, 2, "failed requests remain pending");
580
626
  assert.ok(notifications.some(x => x.includes("Brain not emptied")));
581
627
  // Core dispatches the admitted manual event within our command hook.
@@ -589,14 +635,14 @@ test("Claude headless resets through its own manual command, retries failure and
589
635
  });
590
636
  return {};
591
637
  };
592
- await invoke("turn.complete");
638
+ await invoke("turn.complete", turnComplete());
593
639
  assert.match(kept[0].text, /claude:hook-session:1/);
594
640
  assert.equal(kept[2].text, "*You peel a sticky note off your forehead.*\nSTICKY");
595
- await invoke("turn.complete");
641
+ await invoke("turn.complete", turnComplete());
596
642
  assert.equal(attempts, 3, "success clears pending exactly once");
597
643
  assert.match(JSON.stringify(await invoke("session.compact", { trigger: "manual" })), /use \/fresh-window/);
598
644
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "reset2" });
599
- await invoke("turn.complete");
645
+ await invoke("turn.complete", turnComplete());
600
646
  assert.match(kept[0].text, /claude:hook-session:2/);
601
647
  assert.equal(kept.length, 2, "sticky is consumed once");
602
648
  });
@@ -612,7 +658,7 @@ test("Claude headless warns without proactive resets and supports both manual al
612
658
  const timers = [];
613
659
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
614
660
  host.clock.after = (_ms, callback) => { timers.push(callback); };
615
- host.prompt.submit = async () => { prompts++; await invoke("turn.start"); await invoke("turn.complete"); };
661
+ host.prompt.submit = async () => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); };
616
662
  host.command.run = async ({ command }) => {
617
663
  attempts++;
618
664
  await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
@@ -629,10 +675,10 @@ test("Claude headless warns without proactive resets and supports both manual al
629
675
  tokens = CLAUDE_200K.reset;
630
676
  await invoke("turn.start");
631
677
  assert.equal(attempts, 0);
632
- await invoke("turn.complete");
678
+ await invoke("turn.complete", turnComplete());
633
679
  assert.equal(attempts, 0, "the old reset threshold and turn completion do not clear");
634
680
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
635
- await invoke("turn.complete");
681
+ await invoke("turn.complete", turnComplete());
636
682
  assert.equal(attempts, 1);
637
683
  for (const command of ["empty", "fresh-window"]) {
638
684
  assert.deepEqual(await invoke("command.run", { command }), { text: "🥣 Dumping Brain" });
@@ -645,7 +691,7 @@ test("Claude headless warns without proactive resets and supports both manual al
645
691
  await invoke("command.run", { command: "empty" });
646
692
  await Promise.resolve();
647
693
  await timers.shift()();
648
- await invoke("turn.complete");
694
+ await invoke("turn.complete", turnComplete());
649
695
  assert.equal(attempts, 4, "a failed close-out also leaves the reset pending");
650
696
  });
651
697
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
@@ -687,12 +733,12 @@ test("Claude Mod refuses to wipe on boot failure and can retry without advancing
687
733
  host.session.compact = async ({ instructions }) => result = await invoke("session.compact", { trigger: "plugin", instructions });
688
734
  await invoke("turn.start");
689
735
  await invoke("command.run", { command: "empty" });
690
- await invoke("turn.complete");
736
+ await invoke("turn.complete", turnComplete());
691
737
  assert.match(result.skip, /notes didn't load/);
692
738
  assert.equal(result.messages, undefined, "a failed builder must veto rather than fall through to summary");
693
739
  failBoot = false;
694
740
  await invoke("turn.start");
695
- await invoke("turn.complete");
741
+ await invoke("turn.complete", turnComplete());
696
742
  assert.equal(result.skip, undefined);
697
743
  assert.equal(result.messages.length, 2);
698
744
  assert.match(result.messages[0].text, /Current context window id: claude:hook-session:1/, "a failed reset never consumes a window ordinal");
@@ -720,7 +766,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
720
766
  host.prompt.submit = async ({ text }) => {
721
767
  prompts.push(text);
722
768
  await invoke("turn.start");
723
- await invoke("turn.complete");
769
+ await invoke("turn.complete", turnComplete());
724
770
  };
725
771
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
726
772
  await invoke("session.start", { cwd: home, isInteractive: true });
@@ -746,7 +792,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
746
792
  assert.deepEqual(await handlers.get("prompt.context")(host, {}, async () => ({ blocks: [] })), { blocks: [] }, "reload does not duplicate the already-retained boot");
747
793
  await invoke("turn.start");
748
794
  await invoke("command.run", { command: "empty" });
749
- await invoke("turn.complete");
795
+ await invoke("turn.complete", turnComplete());
750
796
  assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
751
797
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
752
798
  });
@@ -803,7 +849,7 @@ test("Claude warnings read the public nested breakdown and apply pct even withou
803
849
  tokens++;
804
850
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
805
851
  assert.equal((await submit()).context, undefined, "one warning per window");
806
- await invoke("turn.complete");
852
+ await invoke("turn.complete", turnComplete());
807
853
  assert.equal(resets, 0, "warning and turn completion never proactively clear");
808
854
  assert.equal((await invoke("session.compact", { trigger: "auto" })).messages.length, 2);
809
855
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "native auto starts a new warning window");
@@ -854,7 +900,7 @@ test("Claude Mod keeps warning timing when auto-compact is off without clearing
854
900
  host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
855
901
  await invoke("session.start", { cwd: home, isInteractive: true });
856
902
  await invoke("turn.start");
857
- await invoke("turn.complete");
903
+ await invoke("turn.complete", turnComplete());
858
904
  const submit = () => handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
859
905
  assert.equal((await submit()).context, undefined);
860
906
  tokens = 155_424;
@@ -862,7 +908,7 @@ test("Claude Mod keeps warning timing when auto-compact is off without clearing
862
908
  assert.equal(compactions, 0);
863
909
  await invoke("turn.start");
864
910
  tokens = 171_808;
865
- await invoke("turn.complete");
911
+ await invoke("turn.complete", turnComplete());
866
912
  assert.equal(compactions, 0, "the former 200000 - 20000 - 8192 reset point is not a clear trigger");
867
913
  assert.deepEqual(notifications.filter((text) => text.includes("unavailable") || text.includes("Couldn't")), [], "a resolvable configuration logs no failure");
868
914
  });
@@ -889,7 +935,7 @@ test("Claude Mod suppresses warnings and explicit reset requests under DISABLE_C
889
935
  assert.match(tool.result, /DISABLE_COMPACT/);
890
936
  assert.equal(timers.length, 0, "no close-out turn is queued");
891
937
  await invoke("turn.start");
892
- await invoke("turn.complete");
938
+ await invoke("turn.complete", turnComplete());
893
939
  assert.equal(compactions, 0, "disabled reset requests never run");
894
940
  assert.equal(notifications.length, 1, "detection logs once, not per turn");
895
941
  const upstream = { result: "upstream", context: ["other plugin"] };
@@ -908,7 +954,7 @@ test("Claude Mod skips the warning when thresholds cannot be resolved", async (t
908
954
  host.session.compact = async () => { compactions++; return {}; };
909
955
  await invoke("session.start", { cwd: home, isInteractive: true });
910
956
  await invoke("turn.start");
911
- await invoke("turn.complete");
957
+ await invoke("turn.complete", turnComplete());
912
958
  await invoke("tool.call", { tool: "Read" });
913
959
  assert.equal(compactions, 0, "an unresolvable point never resets");
914
960
  assert.equal(notifications.filter((text) => text.includes("Brain size unknown")).length, 1, "one line, not one per turn");
@@ -935,9 +981,9 @@ test("Claude Mod keeps the turn latch through subagent turns", async (t) => {
935
981
  await invoke("turn.start");
936
982
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
937
983
  await invoke("turn.start", { agentId: "sub-1" });
938
- await invoke("turn.complete", { agentId: "sub-1" });
984
+ await invoke("turn.complete", turnComplete({ agentId: "sub-1" }));
939
985
  assert.equal(compactions, 0, "a subagent turn cannot release the main turn's latch");
940
- await invoke("turn.complete");
986
+ await invoke("turn.complete", turnComplete());
941
987
  assert.equal(compactions, 1, "the main turn still resets at its own end");
942
988
  });
943
989
  test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
@@ -955,7 +1001,7 @@ test("Claude Mod treats DISABLE_COMPACT=off as not disabled", async (t) => {
955
1001
  assert.deepEqual(notifications.filter((text) => text.includes("DISABLE_COMPACT")), [], "an explicit off is not a disable");
956
1002
  await invoke("turn.start");
957
1003
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "explicit" });
958
- await invoke("turn.complete");
1004
+ await invoke("turn.complete", turnComplete());
959
1005
  assert.equal(compactions, 1, "the explicit reset still runs");
960
1006
  });
961
1007
  test("Claude Mod retries an unresolvable warning threshold inside the same window", async (t) => {
@@ -978,12 +1024,12 @@ test("Claude Mod retries an unresolvable warning threshold inside the same windo
978
1024
  host.session.compact = async ({ instructions }) => { compactions++; return await invoke("session.compact", { trigger: "plugin", instructions }); };
979
1025
  await invoke("session.start", { cwd: home, isInteractive: true });
980
1026
  await invoke("turn.start");
981
- await invoke("turn.complete");
1027
+ await invoke("turn.complete", turnComplete());
982
1028
  await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
983
1029
  assert.equal(limitsCalls, 1, "the first limits round trip failed");
984
1030
  assert.equal(compactions, 0, "one failed resolution does not disable the window");
985
1031
  await invoke("turn.start");
986
- await invoke("turn.complete");
1032
+ await invoke("turn.complete", turnComplete());
987
1033
  const retried = await handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
988
1034
  assert.deepEqual(retried.context, [CLAUDE_WARNING_PROMPT]);
989
1035
  assert.equal(limitsCalls, 2, "the retry runs in the same window");
@@ -1030,16 +1076,16 @@ test("Claude empty_brain defers until main turn completion, carries last_word, a
1030
1076
  assert.equal(accepted.isError, undefined);
1031
1077
  assert.match(accepted.result, /End your turn now/);
1032
1078
  await call({ last_word: "must not replace the first request" });
1033
- await invoke("turn.complete", { agentId: "child" });
1079
+ await invoke("turn.complete", turnComplete({ agentId: "child" }));
1034
1080
  assert.equal(resets.length, 0, "neither tool execution nor a child completion resets a running main turn");
1035
- await invoke("turn.complete");
1081
+ await invoke("turn.complete", turnComplete());
1036
1082
  assert.equal(resets.length, 1, "the tool requests a reset even far below the budget threshold");
1037
1083
  assert.deepEqual(origins, ["normal"]);
1038
1084
  assert.ok(NORMAL_CONTINUATIONS.includes(resets[0].messages[1].text));
1039
1085
  assert.deepEqual(resets[0].messages.slice(2).map((row) => row.text), ["*You peel a sticky note off your forehead.*\nnext move: test"]);
1040
1086
  assert.match(resets[0].messages[0].text, /mcp__notesoup__empty_brain/);
1041
1087
  await invoke("turn.start");
1042
- await invoke("turn.complete");
1088
+ await invoke("turn.complete", turnComplete());
1043
1089
  assert.equal(resets.length, 1, "the successful tool request does not leak into the next window");
1044
1090
  const forced = await invoke("session.compact", { trigger: "auto" });
1045
1091
  assert.deepEqual(origins, ["normal", "forced"]);
@@ -1066,7 +1112,7 @@ test("Claude empty_brain refuses unsupported calls without queuing a reset", asy
1066
1112
  assert.equal(refused.isError, true);
1067
1113
  assert.match(refused.result, reason);
1068
1114
  }
1069
- await invoke("turn.complete");
1115
+ await invoke("turn.complete", turnComplete());
1070
1116
  assert.equal(resets, 0);
1071
1117
  });
1072
1118
  test("Claude asks for one handoff per compaction and reuses it when the same window retries", async (t) => {
@@ -1082,7 +1128,7 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
1082
1128
  // Every read path stays pure: no boot, warning, context, or measure draws a handoff.
1083
1129
  await invoke("prompt.context", {}, { blocks: [] });
1084
1130
  await invoke("turn.start");
1085
- await invoke("turn.complete");
1131
+ await invoke("turn.complete", turnComplete());
1086
1132
  assert.equal(draws.length, 0, "only a reset draws, never a read");
1087
1133
  const timers = [];
1088
1134
  const lines = [];
@@ -1099,7 +1145,7 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
1099
1145
  assert.equal((await invoke("command.run", { command: "fresh-window", args: "" })).text, "🥣 Dumping Brain");
1100
1146
  await Promise.resolve();
1101
1147
  await timers.shift()();
1102
- await invoke("turn.complete");
1148
+ await invoke("turn.complete", turnComplete());
1103
1149
  assert.equal(draws.length, 1, "a retried compaction adds no second draw");
1104
1150
  assert.equal(lines.length, 2, "both attempts returned a handoff");
1105
1151
  assert.equal(lines[0], lines[1], "both attempts carry the same artifact's paragraph");
@@ -1120,7 +1166,7 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1120
1166
  // Clear the old running-turn and queued-reset state, not just the retained boot.
1121
1167
  let compactions = 0;
1122
1168
  host.session.compact = async () => { compactions++; return {}; };
1123
- await invoke("turn.complete");
1169
+ await invoke("turn.complete", turnComplete());
1124
1170
  assert.equal(compactions, 0, "the old queued reset cannot spill into the new session");
1125
1171
  const fresh = await context();
1126
1172
  assert.deepEqual(fresh.blocks.map((block) => block.name), ["notesoup:boot"]);
@@ -1132,7 +1178,7 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1132
1178
  host.process.run = async (argv, init) => { requests.push(JSON.parse(init.stdin)); return run(argv, init); };
1133
1179
  const written = await invoke("tool.call", { tool: "mcp__notesoup__notes_write", tool_use_id: "new-session", address: "session.md", content: action });
1134
1180
  assert.equal(written.result, "created session.md");
1135
- assert.equal(requests[0].identity?.sessionId, `after-${action}`, "tools also use the new session home");
1181
+ assert.equal(requests[0].identity?.sessionId, `after-${action}`, "tools also use the new session notebook");
1136
1182
  });
1137
1183
  }
1138
1184
  });
@@ -1244,9 +1290,9 @@ test("Claude identity uses the documented current model and cwd, with a safe mod
1244
1290
  await write("@model/model.md", "fallback");
1245
1291
  assert.equal(seen.at(-1).identity.model, "claude");
1246
1292
  });
1247
- test("Claude current-cwd project resolution shares Pi's remote home across checkout spellings", async (t) => {
1293
+ test("Claude current-cwd project resolution shares Pi's remote notebook across checkout spellings", async (t) => {
1248
1294
  const { host, home, invoke } = await retainedFixture(t);
1249
- const root = realpathSync(mkdtempSync(join(tmpdir(), "claude-project-home-")));
1295
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "claude-project-notebook-")));
1250
1296
  t.after(() => rmSync(root, { recursive: true, force: true }));
1251
1297
  const first = join(root, "api");
1252
1298
  const second = join(root, "renamed");
@@ -1269,7 +1315,7 @@ test("Claude current-cwd project resolution shares Pi's remote home across check
1269
1315
  assert.equal(written.result, "overwrote @project/shared.md (project api)");
1270
1316
  assert.equal((await createNotesStore(piIdentity).read("@project/shared"))?.body, "Claude body");
1271
1317
  assert.deepEqual(JSON.parse(readFileSync(join(home, "project/api/.project"), "utf8")), { id: "host/team/backend", path: second });
1272
- assert.equal(resolveProjectHome(second, home).name, piIdentity.projectKey);
1318
+ assert.equal(resolveProjectNamespace(second, home).name, piIdentity.projectKey);
1273
1319
  });
1274
1320
  test("Claude session.end cannot be undone by an in-flight old reset", async (t) => {
1275
1321
  const { host, invoke, context } = await retainedFixture(t);
@@ -1285,7 +1331,7 @@ test("Claude session.end cannot be undone by an in-flight old reset", async (t)
1285
1331
  return result;
1286
1332
  };
1287
1333
  await invoke("tool.call", { tool: "mcp__notesoup__empty_brain", tool_use_id: "in-flight" });
1288
- const finishing = invoke("turn.complete");
1334
+ const finishing = invoke("turn.complete", turnComplete());
1289
1335
  await ready;
1290
1336
  await invoke("session.end", { reason: "clear", sessionId: "hook-session" });
1291
1337
  host.session.id = async () => "after-flight";
@@ -162,7 +162,7 @@ test("a copied plugin without src or node_modules still initializes and lists al
162
162
  assert.match(refusal, /child post-compact boot/);
163
163
  });
164
164
  /* ---------------------------------------------------------------- MCP tools */
165
- test("notes tools use the hook thread as the session home and the current turn model as @model", async (t) => {
165
+ test("notes tools use the hook thread as the session notebook and the current turn model as @model", async (t) => {
166
166
  const f = await fixture(t);
167
167
  await writeFile(f.transcript, jsonl([row("session_meta", sessionMeta())]));
168
168
  await bind(f.data, { threadId: ROOT, rootSessionId: ROOT, home: f.home, cwd: f.cwd, transcriptPath: f.transcript });
@@ -185,6 +185,23 @@ test("notes tools use the hook thread as the session home and the current turn m
185
185
  const listed = await call(client, { name: "notes_list", arguments: { glob: "@model/**" }, _meta: meta });
186
186
  assert.match(textOf(listed), /@model\/model\.md/);
187
187
  });
188
+ test("Codex resolves relative cwd against the verified binding, not the MCP process", async (t) => {
189
+ const f = await fixture(t);
190
+ await writeFile(f.transcript, jsonl([row("session_meta", sessionMeta())]));
191
+ const base = join(f.home, "base"), other = join(f.home, "other");
192
+ await mkdir(base);
193
+ await mkdir(other);
194
+ await bind(f.data, { threadId: ROOT, rootSessionId: ROOT, home: f.home, cwd: base, transcriptPath: f.transcript });
195
+ const client = await connect(t, f.data, CLI, f.home);
196
+ const meta = metaFor(ROOT, ROOT);
197
+ const written = await call(client, { name: "notes_write", arguments: { address: "@project/selected", content: "from Codex", cwd: "../other" }, _meta: meta });
198
+ assert.equal(written.isError, undefined, textOf(written));
199
+ assert.equal(written.structuredContent.project_key, "other");
200
+ assert.match(readFileSync(join(f.home, "project", "other", "selected.md"), "utf8"), /from Codex/);
201
+ const read = await call(client, { name: "notes_read", arguments: { address: "@project/selected", cwd: "../other" }, _meta: meta });
202
+ assert.equal(read.isError, undefined, textOf(read));
203
+ assert.equal(read.structuredContent.text, "from Codex");
204
+ });
188
205
  test("refusals precede reads and writes: unknown thread, stale root, bad model, bad params", async (t) => {
189
206
  const f = await fixture(t);
190
207
  await writeFile(f.transcript, jsonl([row("session_meta", sessionMeta())]));
@@ -0,0 +1,121 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { SettingsManager } from "@earendil-works/pi-coding-agent";
4
+ import { registerBudget } from "../plugins/pi/budget.js";
5
+ import { BOOT_TYPE, RESET_MARKER_TYPE } from "../plugins/pi/entries.js";
6
+ import { currentReset, isCheckpointBackedReset, windowUsage } from "../plugins/pi/window.js";
7
+ import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, nativeUsageContext, resultJson, runHandlers, } from "./helpers/extension.js";
8
+ import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
9
+ installExtensionTestHooks("notesoup-context-edit");
10
+ function appendUsage(sm, tokens, timestamp = Date.now()) {
11
+ const message = {
12
+ role: "assistant", content: [{ type: "text", text: "response" }],
13
+ api: "openai-responses", provider: "openai", model: "usage-fixture",
14
+ stopReason: "stop", timestamp,
15
+ usage: {
16
+ input: tokens, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: tokens,
17
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
18
+ },
19
+ };
20
+ return sm.appendMessage(message);
21
+ }
22
+ function appendWindow(sm, checkpoint) {
23
+ if (checkpoint)
24
+ sm.appendCompaction("", null, 0);
25
+ sm.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:edited" });
26
+ sm.appendCustomMessageEntry(BOOT_TYPE, "boot", false, { windowId: "pcw:edited" });
27
+ }
28
+ for (const kind of ["root", "checkpoint", "legacy"]) {
29
+ test(`${kind} budget rejects assistant usage invalidated by a real context edit`, async (t) => {
30
+ const sm = manager();
31
+ if (kind !== "root")
32
+ appendWindow(sm, kind === "checkpoint");
33
+ const target = appendText(sm, "user", "long context ".repeat(25_000));
34
+ appendUsage(sm, 100_000);
35
+ const settings = SettingsManager.inMemory({ compaction: { enabled: true, reserveTokens: 16_384 } });
36
+ const native = await nativeUsageContext(sm, settings);
37
+ t.after(native.dispose);
38
+ const { ctx } = native;
39
+ const captured = makeExtension(sm, settings);
40
+ const budget = registerBudget({ on() { }, registerTool() { } }, () => true, settings);
41
+ assert.equal(budget.hardReserveDue(ctx), true, "the original provider usage really reaches hard reserve");
42
+ sm.appendContextEdit(target, { content: "short" });
43
+ const leaf = sm.getLeafId();
44
+ const rawEntries = sm.getBranch();
45
+ const nativeUsage = ctx.getContextUsage();
46
+ const usage = windowUsage(ctx);
47
+ assert.ok(nativeUsage && nativeUsage.tokens !== null && usage && usage.tokens !== null);
48
+ if (kind === "legacy") {
49
+ // Legacy uses the vendored chars/3.5 estimator; native Pi uses chars/4.
50
+ assert.ok(usage.tokens >= nativeUsage.tokens);
51
+ assert.ok(usage.tokens <= Math.ceil(nativeUsage.tokens * 4 / 3.5) + sm.buildSessionProjection().messages.length);
52
+ }
53
+ else {
54
+ assert.deepEqual(usage, nativeUsage, "native projection remains the usage authority");
55
+ }
56
+ assert.equal(budget.hardReserveDue(ctx), false);
57
+ const room = resultJson(await call(captured, "get_context_remaining", {}, ctx)).remaining_tokens;
58
+ assert.equal(room, usage.contextWindow - usage.tokens - settings.getCompactionSettings().reserveTokens);
59
+ assert.ok(room !== null && room > 0, "shrinking the transcript restores spendable budget");
60
+ assert.equal(sm.getLeafId(), leaf, "accounting never repairs itself by resetting");
61
+ assert.deepEqual(sm.getBranch(), rawEntries, "usage selection does not mutate persisted history");
62
+ const boundary = await commitTurnEndBoundary(captured, sm, ctx);
63
+ assert.deepEqual(boundary.entries, [], "the real registered turn-end hook does not trigger a hard wipe");
64
+ assert.equal(sm.getLeafId(), leaf);
65
+ assert.equal(isCheckpointBackedReset(ctx), kind === "checkpoint");
66
+ });
67
+ }
68
+ test("legacy estimation excludes prior windows and trusts only usage appended after the edit", async (t) => {
69
+ const sm = manager();
70
+ appendText(sm, "user", "old window ".repeat(40_000));
71
+ appendUsage(sm, 300_000);
72
+ appendWindow(sm, false);
73
+ const target = appendText(sm, "user", "long current window ".repeat(15_000));
74
+ appendUsage(sm, 100_000);
75
+ const settings = SettingsManager.inMemory();
76
+ const native = await nativeUsageContext(sm, settings);
77
+ t.after(native.dispose);
78
+ const { ctx } = native;
79
+ sm.appendContextEdit(target, { content: "short" });
80
+ const usage = windowUsage(ctx);
81
+ assert.ok(usage && usage.tokens !== null);
82
+ assert.equal(usage.tokens, ["boot", "short", "response"].reduce((sum, text) => sum + Math.ceil(text.length / 3.5), 0));
83
+ assert.ok(ctx.getContextUsage().tokens > usage.tokens, "native legacy projection still contains the old window");
84
+ const freshTokens = 42_000;
85
+ appendUsage(sm, freshTokens, Date.now() + 1);
86
+ assert.equal(windowUsage(ctx)?.tokens, freshTokens, "fresh usage is not discarded with the stale responses");
87
+ sm.appendContextEdit(target, { content: "tiny" });
88
+ assert.ok(windowUsage(ctx).tokens < freshTokens, "a second edit invalidates that usage too");
89
+ });
90
+ test("checkpoint usage preserves native unknown/unavailable values; legacy retains context-window fallback", async (t) => {
91
+ const sm = manager();
92
+ appendUsage(sm, 100_000);
93
+ appendWindow(sm, true);
94
+ const native = await nativeUsageContext(sm, SettingsManager.inMemory());
95
+ t.after(native.dispose);
96
+ assert.equal(native.ctx.getContextUsage()?.tokens, null, "Pi has no post-compaction provider usage yet");
97
+ assert.deepEqual(windowUsage(native.ctx), native.ctx.getContextUsage(), "unknown is not replaced with a made-up estimate");
98
+ const captured = makeExtension(sm, SettingsManager.inMemory());
99
+ assert.equal(resultJson(await call(captured, "get_context_remaining", {}, native.ctx)).remaining_tokens, null);
100
+ native.ctx.getContextUsage = () => undefined;
101
+ assert.equal(windowUsage(native.ctx), undefined, "even a known model window cannot invent native usage");
102
+ const legacy = manager();
103
+ appendWindow(legacy, false);
104
+ const fallback = context(legacy, undefined, { tokens: null, percent: null, contextWindow: 100_000 });
105
+ assert.equal(windowUsage(fallback)?.contextWindow, 100_000, "legacy can read the window size without a model");
106
+ fallback.getContextUsage = () => undefined;
107
+ assert.equal(windowUsage(fallback), undefined, "without either window size, legacy usage stays unavailable");
108
+ });
109
+ test("an incomplete legacy reset remains unknown until the existing startup repair supplies its boot", async () => {
110
+ const sm = manager();
111
+ appendUsage(sm, 100_000);
112
+ sm.appendCustomEntry(RESET_MARKER_TYPE, { windowId: "pcw:partial" });
113
+ const ctx = context(sm, undefined, { tokens: 100_000, percent: 100, contextWindow: 100_000 });
114
+ const marker = currentReset(ctx)?.id;
115
+ assert.equal(windowUsage(ctx), undefined);
116
+ const captured = makeExtension(sm, SettingsManager.inMemory());
117
+ await runHandlers(captured, "session_start", { reason: "startup" }, ctx);
118
+ assert.equal(currentReset(ctx)?.id, marker, "repair does not create a replacement reset");
119
+ const usage = windowUsage(ctx);
120
+ assert.ok(usage && usage.tokens !== null && usage.tokens < usage.contextWindow);
121
+ });