notesoup 0.57.4 → 0.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +15 -1
  2. package/dist/plugins/claude/src/helper.js +2 -11
  3. package/dist/plugins/claude/src/thresholds.js +23 -43
  4. package/dist/plugins/codex/src/mcp.js +3 -11
  5. package/dist/plugins/codex/src/state.d.ts +1 -1
  6. package/dist/plugins/codex/src/state.js +1 -1
  7. package/dist/plugins/dsh/tools.js +1 -1
  8. package/dist/plugins/pi/boot.d.ts +1 -1
  9. package/dist/plugins/pi/boot.js +2 -3
  10. package/dist/plugins/pi/budget.d.ts +1 -1
  11. package/dist/plugins/pi/budget.js +1 -1
  12. package/dist/plugins/pi/render.d.ts +1 -1
  13. package/dist/plugins/pi/render.js +20 -11
  14. package/dist/plugins/pi/runtime.js +6 -2
  15. package/dist/plugins/pi/tool-result.d.ts +2 -1
  16. package/dist/plugins/pi/window.js +24 -1
  17. package/dist/src/boot/render.d.ts +3 -4
  18. package/dist/src/boot/render.js +23 -21
  19. package/dist/src/boot/text.d.ts +2 -5
  20. package/dist/src/boot/text.js +12 -9
  21. package/dist/src/budget/text.d.ts +1 -1
  22. package/dist/src/budget/text.js +1 -1
  23. package/dist/src/history/corpus.d.ts +1 -1
  24. package/dist/src/history/corpus.js +1 -1
  25. package/dist/src/history/history.d.ts +2 -2
  26. package/dist/src/history/history.js +5 -8
  27. package/dist/src/history/query.d.ts +11 -3
  28. package/dist/src/history/query.js +7 -11
  29. package/dist/src/index.d.ts +4 -3
  30. package/dist/src/index.js +1 -1
  31. package/dist/src/notes/constants.d.ts +1 -1
  32. package/dist/src/notes/constants.js +1 -1
  33. package/dist/src/notes/errors.d.ts +1 -1
  34. package/dist/src/notes/frontmatter.d.ts +2 -1
  35. package/dist/src/notes/frontmatter.js +3 -1
  36. package/dist/src/notes/index.d.ts +1 -0
  37. package/dist/src/notes/index.js +1 -0
  38. package/dist/src/notes/policy.d.ts +16 -0
  39. package/dist/src/notes/policy.js +43 -0
  40. package/dist/src/notes/store.d.ts +7 -2
  41. package/dist/src/notes/store.js +61 -19
  42. package/dist/src/result.d.ts +21 -0
  43. package/dist/src/result.js +18 -0
  44. package/dist/src/text-match.d.ts +8 -0
  45. package/dist/src/text-match.js +34 -0
  46. package/dist/src/tools/dream.d.ts +9 -1
  47. package/dist/src/tools/dream.js +2 -1
  48. package/dist/src/tools/history.js +14 -5
  49. package/dist/src/tools/notes.d.ts +75 -13
  50. package/dist/src/tools/notes.js +58 -19
  51. package/dist/src/tools/output.d.ts +1 -3
  52. package/dist/src/tools/output.js +1 -19
  53. package/dist/src/tools/result.d.ts +2 -20
  54. package/dist/src/tools/result.js +4 -18
  55. package/dist/src/tools/schema.d.ts +3 -7
  56. package/dist/src/tools/schema.js +10 -16
  57. package/dist/test/agent-loop.test.js +78 -6
  58. package/dist/test/boot.integration.test.js +30 -3
  59. package/dist/test/claude-mod.test.js +101 -16
  60. package/dist/test/codex-history.test.js +2 -2
  61. package/dist/test/codex-plugin.test.js +2 -0
  62. package/dist/test/dependencies.test.js +38 -3
  63. package/dist/test/dsh.test.js +1 -1
  64. package/dist/test/helpers/dependency-graph.js +12 -6
  65. package/dist/test/helpers/extension.d.ts +2 -1
  66. package/dist/test/history.integration.test.js +47 -1
  67. package/dist/test/host-neutral.test.js +4 -3
  68. package/dist/test/model-facing-text.test.js +20 -16
  69. package/dist/test/note-policy.test.d.ts +1 -0
  70. package/dist/test/note-policy.test.js +227 -0
  71. package/dist/test/notes.integration.test.js +9 -9
  72. package/dist/test/notes.test.js +4 -4
  73. package/dist/test/pi-render.test.js +28 -1
  74. package/dist/test/project-namespace.test.js +1 -1
  75. package/docs/architecture.md +10 -7
  76. package/docs/claude-code-mod.md +3 -3
  77. package/docs/dsh.md +1 -1
  78. package/docs/notes-library.md +19 -6
  79. package/docs/reset-lifecycle.md +2 -2
  80. package/docs/tool-results.md +3 -1
  81. package/package.json +12 -12
  82. package/playbook.md +1 -1
  83. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  84. package/plugins/claude/dist/claude/helper.js +535 -439
  85. package/plugins/claude/hooks/register.ts +26 -36
  86. package/plugins/claude/playbook.md +1 -1
  87. package/plugins/claude/skills/dream/SKILL.md +1 -1
  88. package/plugins/claude/skills/memory/SKILL.md +1 -1
  89. package/plugins/claude/src/helper.ts +2 -11
  90. package/plugins/claude/src/thresholds.ts +22 -42
  91. package/plugins/codex/dist/codex/notesoup.js +519 -403
  92. package/plugins/codex/src/mcp.ts +5 -12
  93. package/plugins/codex/src/state.ts +1 -1
  94. package/plugins/dsh/tools.ts +2 -1
  95. package/plugins/pi/boot.ts +3 -4
  96. package/plugins/pi/budget.ts +1 -1
  97. package/plugins/pi/render.ts +20 -8
  98. package/plugins/pi/runtime.ts +6 -2
  99. package/plugins/pi/tool-result.ts +2 -1
  100. package/plugins/pi/window.ts +20 -1
  101. package/skills/dream/SKILL.md +1 -1
  102. package/skills/memory/SKILL.md +1 -1
  103. package/src/boot/render.ts +24 -21
  104. package/src/boot/text.ts +12 -9
  105. package/src/budget/text.ts +1 -1
  106. package/src/history/corpus.ts +1 -1
  107. package/src/history/history.ts +5 -6
  108. package/src/history/query.ts +11 -14
  109. package/src/index.ts +5 -2
  110. package/src/notes/constants.ts +1 -1
  111. package/src/notes/errors.ts +1 -1
  112. package/src/notes/frontmatter.ts +4 -2
  113. package/src/notes/index.ts +1 -0
  114. package/src/notes/policy.ts +49 -0
  115. package/src/notes/store.ts +63 -24
  116. package/src/result.ts +26 -0
  117. package/src/text-match.ts +32 -0
  118. package/src/tools/dream.ts +2 -1
  119. package/src/tools/history.ts +15 -6
  120. package/src/tools/notes.ts +60 -20
  121. package/src/tools/output.ts +1 -17
  122. package/src/tools/result.ts +4 -26
  123. package/src/tools/schema.ts +11 -17
  124. package/dist/plugins/codex/src/history.d.ts +0 -3
  125. package/dist/plugins/codex/src/history.js +0 -2
  126. package/dist/plugins/codex/src/transcript.d.ts +0 -3
  127. package/dist/plugins/codex/src/transcript.js +0 -2
  128. package/plugins/codex/src/history.ts +0 -3
  129. package/plugins/codex/src/transcript.ts +0 -3
@@ -1,22 +1,8 @@
1
- /** Internal outcomes, compact wire results, and bounded read windows. */
1
+ /** Compact tool wire results and bounded read windows. */
2
2
  import { Type } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES } from "./output.js";
4
- /** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
5
- export const OperationErrorSchema = Type.Object({
6
- code: Type.String(),
7
- message: Type.String(),
8
- }, { additionalProperties: false });
9
- export function success(data) {
10
- return { ok: true, data };
11
- }
12
- /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
13
- export const ERROR_MESSAGE_MAX_CHARS = 2000;
14
- /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
15
- export function failure(code, message) {
16
- const chars = Array.from(message);
17
- const bounded = chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
18
- return { ok: false, error: { code, message: bounded } };
19
- }
3
+ import { failure, success } from "../result.js";
4
+ import { prefixFit } from "../text-match.js";
5
+ import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES } from "./output.js";
20
6
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
21
7
  export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
22
8
  export function wireResult(result) {
@@ -1,11 +1,7 @@
1
- import { Type } from "typebox";
1
+ import { Type, type TSchema } from "typebox";
2
2
  export declare const nullableString: (description?: string) => Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
3
3
  export declare const historyRoles: () => Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
4
+ /** First parameter violation; skip false subschemas so additionalProperties can name the field. */
5
+ export declare function paramProblem(schema: TSchema, params: unknown): string;
4
6
  /** Search query parameter: one literal, or several literals combined with OR. */
5
7
  export declare const searchQuery: (description?: string) => Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
6
- /** Expected search-query refusal, distinct from any other Error an operation may raise. */
7
- export declare class InvalidQueryError extends Error {
8
- constructor(message: string);
9
- }
10
- /** Missing/empty queries disable filtering; empty list entries are ignored, not OR wildcards. */
11
- export declare function searchQueries(query: unknown): string[];
@@ -1,22 +1,16 @@
1
1
  import { Type } from "typebox";
2
+ import { Errors } from "typebox/value";
2
3
  import { HistoryRoleSchema } from "../history/history.js";
3
4
  export const nullableString = (description) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
4
5
  export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
6
+ /** First parameter violation; skip false subschemas so additionalProperties can name the field. */
7
+ export function paramProblem(schema, params) {
8
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
9
+ if (!first)
10
+ return "unrecognized shape";
11
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
12
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
13
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
14
+ }
5
15
  /** Search query parameter: one literal, or several literals combined with OR. */
6
16
  export const searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => Type.Union([Type.String(), Type.Array(Type.String())], { description });
7
- /** Expected search-query refusal, distinct from any other Error an operation may raise. */
8
- export class InvalidQueryError extends Error {
9
- constructor(message) {
10
- super(message);
11
- this.name = "InvalidQueryError";
12
- }
13
- }
14
- /** Missing/empty queries disable filtering; empty list entries are ignored, not OR wildcards. */
15
- export function searchQueries(query) {
16
- const candidates = query === undefined ? [] : typeof query === "string" ? [query] : query;
17
- if (!Array.isArray(candidates))
18
- throw new InvalidQueryError("`query` must be a string or a list of strings.");
19
- if (!candidates.every((candidate) => typeof candidate === "string"))
20
- throw new InvalidQueryError("Every item in the `query` list must be a string.");
21
- return candidates.filter((candidate) => candidate !== "");
22
- }
@@ -3,16 +3,20 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import test from "node:test";
6
- import { createAssistantMessageEventStream, getCurrentSystemMessage } from "@earendil-works/pi-ai";
7
- import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
6
+ import { createAssistantMessageEventStream, getCurrentSystemMessage, getSystemMessageText } from "@earendil-works/pi-ai";
7
+ import { createAgentSession, convertToLlm, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
8
  import notesoup, { createNotesoup } from "../plugins/pi/extension.js";
9
9
  import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, MARKER_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
10
10
  import { historyFromSession } from "../plugins/pi/history.js";
11
11
  import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
12
12
  import { assertBootHistory } from "./helpers/extension.js";
13
- import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
13
+ import { DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG, renderProtocolBlock } from "../src/boot/text.js";
14
+ import { createNotesStore } from "../src/notes/index.js";
15
+ import { agentSlug } from "../plugins/pi/notes/adapter.js";
16
+ import { registerBudget } from "../plugins/pi/budget.js";
17
+ import { estimateContextTokens } from "../plugins/pi/estimate.js";
14
18
  import { FORCED_CONTINUATIONS, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, warningPrompt } from "../src/budget/text.js";
15
- import { commandWarningContent } from "../plugins/pi/text.js";
19
+ import { commandWarningContent, PI_PRE_RESET_HINTS } from "../plugins/pi/text.js";
16
20
  import { DREAM_NAMESPACE, HISTORY_NAMESPACE, NOTES_NAMESPACE } from "../plugins/pi/tool-result.js";
17
21
  async function openFixture(options) {
18
22
  const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
@@ -276,12 +280,17 @@ test("real AgentSession: turn-end markers reach tool continuations and allow one
276
280
  }
277
281
  }
278
282
  });
279
- test("real AgentSession: notesoup tool directory is a stable system section across requests and reset", async () => {
283
+ test("real AgentSession: protocol and tool directory stay in system while window snapshots remain user data across reset", async (t) => {
280
284
  let fixture;
281
285
  let directory;
286
+ const notesRoot = mkdtempSync(join(tmpdir(), "notesoup-system-split-"));
287
+ t.after(() => rmSync(notesRoot, { recursive: true, force: true }));
288
+ const notes = createNotesStore({ home: notesRoot, sessionId: "seed", projectKey: "seed", agent: "anonymous", model: "default" });
289
+ await notes.write("@human/CHEATSHEET.md", "HUMAN_PIN_BEFORE_RESET");
282
290
  const activeTools = ["empty_brain", "get_context_remaining", "notes_write"];
283
291
  const namespaces = [NOTES_NAMESPACE, HISTORY_NAMESPACE, DREAM_NAMESPACE];
284
292
  fixture = await openFixture({
293
+ notesRoot,
285
294
  compactionEnabled: false,
286
295
  tools: activeTools,
287
296
  hook: (pi) => pi.on("before_agent_start", (event) => {
@@ -290,6 +299,26 @@ test("real AgentSession: notesoup tool directory is a stable system section acro
290
299
  script: (request, context) => {
291
300
  const system = getCurrentSystemMessage(context.messages);
292
301
  const section = system?.sections?.notesoup_tools;
302
+ assert.equal(system?.sections?.notesoup_protocol, `<notesoup_protocol>\n${renderProtocolBlock({ ...DEFAULT_BOOT_TOOL_NAMES, preResetHints: PI_PRE_RESET_HINTS }, agentSlug())}\n\n${MAPS_BLOCK}\n</notesoup_protocol>`, "only existing fixed teaching enters the named system section");
303
+ assert.equal(getSystemMessageText(system).includes("HUMAN_PIN_"), false, "even @human pins never become system instructions");
304
+ const boots = context.messages.filter((message) => message.role === "user" && JSON.stringify(message.content).includes(WINDOW_IDENTITY_OPEN_TAG));
305
+ assert.equal(boots.length, 1, "one user boot reaches the provider");
306
+ const boot = JSON.stringify(boots[0]);
307
+ assert.ok(boot.includes("YOUR NOTES") && boot.includes(request === 3 ? "HUMAN_PIN_AFTER_RESET" : "HUMAN_PIN_BEFORE_RESET"), "the notes snapshot changes only at reset");
308
+ assert.equal(boot.includes(NOTES_PROTOCOL_OPEN_TAG), false);
309
+ assert.equal(boot.includes("<notesoup:maps>"), false);
310
+ assert.equal(context.messages.filter((message) => message.role === "system" && message.sections?.notesoup_protocol !== undefined).length, 1, "unchanged teaching adds no duplicate delta");
311
+ if (request === 1) {
312
+ // Place the reserve between the same request with and without the teaching section.
313
+ const withoutProtocol = context.messages.map((message) => message.role === "system" ? { ...message, sections: { ...message.sections, notesoup_protocol: null } } : message);
314
+ const withTokens = estimateContextTokens(convertToLlm(context.messages)).tokens;
315
+ const withoutTokens = estimateContextTokens(convertToLlm(withoutProtocol)).tokens;
316
+ assert.ok(withTokens > withoutTokens);
317
+ const probe = registerBudget({ on() { }, registerTool() { } }, () => true, SettingsManager.inMemory({ compaction: { enabled: true, reserveTokens: fixture.model.contextWindow - Math.floor((withTokens + withoutTokens) / 2) } }));
318
+ const ctx = { model: fixture.model, getContextUsage: () => undefined };
319
+ assert.equal(probe.hardReserveDue(ctx, context.messages), true, "pre-send accounting includes the real system protocol");
320
+ assert.equal(probe.hardReserveDue(ctx, withoutProtocol), false);
321
+ }
293
322
  assert.equal(typeof section, "string", "the directory reaches the model as a named system section");
294
323
  for (const { name, description } of namespaces)
295
324
  assert.ok(section.includes(`${name}: ${description}`));
@@ -309,6 +338,7 @@ test("real AgentSession: notesoup tool directory is a stable system section acro
309
338
  try {
310
339
  await fixture.session.prompt("Read the directory.");
311
340
  await fixture.session.waitForIdle();
341
+ await notes.write("@human/CHEATSHEET.md", "HUMAN_PIN_AFTER_RESET");
312
342
  await fixture.session.prompt("DIRECTORY_RESET_SENTINEL");
313
343
  await fixture.session.waitForIdle();
314
344
  assert.equal(fixture.requests.length, 3, "two prompts and one reset continuation");
@@ -319,6 +349,47 @@ test("real AgentSession: notesoup tool directory is a stable system section acro
319
349
  fixture.close();
320
350
  }
321
351
  });
352
+ test("real AgentSession: identity changes update system teaching and the next boot; reload reuses that snapshot", async () => {
353
+ const previousAgent = process.env.NOTESOUP_AGENT;
354
+ delete process.env.NOTESOUP_AGENT;
355
+ let fixture;
356
+ try {
357
+ fixture = await openFixture({
358
+ compactionEnabled: false,
359
+ script: (request, context) => {
360
+ const protocol = getCurrentSystemMessage(context.messages)?.sections?.notesoup_protocol;
361
+ assert.equal(protocol?.includes("public square shared by every nameless nobody"), request === 1, "the protocol follows the live named/nameless identity");
362
+ if (request >= 3) {
363
+ const boot = context.messages.find((message) => message.role === "user" && JSON.stringify(message.content).includes(WINDOW_IDENTITY_OPEN_TAG));
364
+ assert.ok(JSON.stringify(boot).includes("Agent name: boot-tester (brain: boot-split-model)"));
365
+ }
366
+ return request === 2
367
+ ? assistant(fixture, [{ type: "toolCall", id: "identity-reset", name: "empty_brain", arguments: {} }], "toolUse")
368
+ : assistant(fixture, [{ type: "text", text: "identity checked" }]);
369
+ },
370
+ });
371
+ await fixture.session.prompt("Anonymous startup.");
372
+ process.env.NOTESOUP_AGENT = "boot-tester";
373
+ fixture.model = { ...fixture.model, id: "boot-split-model" };
374
+ await fixture.session.setModel(fixture.model, { persist: false });
375
+ await fixture.session.prompt("Reset with the changed identity.");
376
+ await fixture.session.waitForIdle();
377
+ const boots = fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE);
378
+ assert.equal(boots.length, 2);
379
+ await fixture.session.reload();
380
+ await fixture.session.prompt("Resume after reload.");
381
+ await fixture.session.waitForIdle();
382
+ assert.equal(fixture.requests.length, 4);
383
+ assert.deepEqual(fixture.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE), boots, "reload never replaces or duplicates a per-window notes snapshot");
384
+ }
385
+ finally {
386
+ fixture?.close();
387
+ if (previousAgent === undefined)
388
+ delete process.env.NOTESOUP_AGENT;
389
+ else
390
+ process.env.NOTESOUP_AGENT = previousAgent;
391
+ }
392
+ });
322
393
  test("real Pi codemode receives typed notes/history outcomes, including expected errors", async () => {
323
394
  let fixture;
324
395
  fixture = await openFixture({
@@ -1120,7 +1191,8 @@ test("real AgentSession: a reset survives all notes-home read failures with an i
1120
1191
  const bootText = typeof boot.content === "string" ? boot.content : JSON.stringify(boot.content);
1121
1192
  assert.equal(bootText.includes("@human — the human"), true);
1122
1193
  assert.equal(bootText.match(/This drawer wouldn't open/g)?.length, 5, "each failed section gets one recovery line");
1123
- assert.ok(bootText.includes(NOTES_PROTOCOL_OPEN_TAG));
1194
+ assert.equal(bootText.includes(NOTES_PROTOCOL_OPEN_TAG), false);
1195
+ assert.ok(getSystemMessageText(getCurrentSystemMessage(fixture.requests[1].messages)).includes(NOTES_PROTOCOL_OPEN_TAG), "a failed notes read cannot remove fixed system teaching");
1124
1196
  }
1125
1197
  finally {
1126
1198
  fixture.close();
@@ -5,11 +5,12 @@ import { rmSync, writeFileSync } from "node:fs";
5
5
  import test from "node:test";
6
6
  import { historyFromSession } from "../plugins/pi/history.js";
7
7
  import { BOOT_TYPE, GUIDANCE_TYPE, RESET_MARKER_TYPE } from "../plugins/pi/entries.js";
8
- import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
8
+ import { MAPS_BLOCK, NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
9
+ import { rootWindowId } from "../plugins/pi/window.js";
9
10
  import { FORCED_CONTINUATIONS, NORMAL_CONTINUATIONS } from "../src/budget/text.js";
10
11
  import { listNotes } from "./helpers/notes.js";
11
12
  import { CONTINUATION_TYPE, MANUAL_WIPE_TYPE } from "../plugins/pi/entries.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
+ import { appendText, assertBootHistory, call, commitTurnEndBoundary, context, explicitBoot, makeExtension, manager, noticesOf, resultData, resultJson, resultRead, runContextHook, runContextWithSystemHook, runHandlers, runManualCompact, runCommand, sentOf, } from "./helpers/extension.js";
13
14
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
14
15
  const testEnvironment = installExtensionTestHooks("notesoup-integration");
15
16
  test("custom reset marker removes old provider context while history remains searchable", async () => {
@@ -101,7 +102,8 @@ test("the root boot and reset boot carry durable window identity", async () => {
101
102
  const decisionsMeta = (await listNotes(ctx)).find((row) => row.path === "decisions.md")?.meta;
102
103
  assert.ok(decisionsMeta);
103
104
  assert.match(rootText, /decisions\.md · (?:just now|\d+s ago)/, "boot note metadata carries a relative update time");
104
- assert.ok(rootText.includes(NOTES_PROTOCOL_OPEN_TAG));
105
+ assert.equal(rootText.includes(NOTES_PROTOCOL_OPEN_TAG), false, "fixed teaching is not part of the user boot");
106
+ assert.equal(rootText.includes(MAPS_BLOCK), false);
105
107
  // Reset: the marker and boot are committed together at the turn boundary.
106
108
  await call(captured, "empty_brain", {}, ctx);
107
109
  assert.equal(noticesOf(ctx).length, 0, "requesting a reset does not announce success");
@@ -118,10 +120,35 @@ test("the root boot and reset boot carry durable window identity", async () => {
118
120
  assert.ok(resetBoot && resetBoot.type === "custom_message");
119
121
  assert.equal(resetBoot.details.windowId, marker.data.windowId);
120
122
  assertBootHistory(String(resetBoot.content), historyFromSession(ctx));
123
+ assert.equal(String(resetBoot.content).includes(NOTES_PROTOCOL_OPEN_TAG), false);
121
124
  const continuation = entries.find((entry) => entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE);
122
125
  assert.ok(continuation && continuation.type === "custom_message" && continuation.display === false, "the resumed run is represented by one hidden continuation");
123
126
  assert.ok(NORMAL_CONTINUATIONS.includes(String(continuation.content)), "a tool-requested reset draws the normal handoff");
124
127
  });
128
+ test("resuming old root/reset boots removes only top-level teaching in projection, preserving notes and raw history", async () => {
129
+ for (const reset of [false, true]) {
130
+ const sm = manager(), captured = makeExtension(sm), ctx = context(sm);
131
+ const noteBody = `Quoted teaching is notes data:\n${NOTES_PROTOCOL_OPEN_TAG}\nkeep this note's protocol quote\n</notesoup:notes_protocol>\n${MAPS_BLOCK}`;
132
+ await call(captured, "notes_write", { address: "MAP.md", content: noteBody }, ctx);
133
+ const windowId = reset ? "pcw:resume:legacy" : rootWindowId(sm.getSessionId());
134
+ if (reset)
135
+ sm.appendCustomEntry(RESET_MARKER_TYPE, { windowId });
136
+ const oldBoot = await explicitBoot(ctx, windowId, undefined);
137
+ sm.appendCustomMessageEntry(BOOT_TYPE, oldBoot, false, { windowId });
138
+ appendText(sm, "user", oldBoot); // An ordinary user's identical quoted block is not a boot.
139
+ const before = sm.getBranch();
140
+ const expected = oldBoot.slice(0, oldBoot.indexOf(WINDOW_IDENTITY_CLOSE_TAG) + WINDOW_IDENTITY_CLOSE_TAG.length) + "\n\n" + oldBoot.slice(oldBoot.indexOf("YOUR NOTES\n"));
141
+ const projected = await runContextWithSystemHook(captured, ctx, [{ role: "system", content: "REAL SYSTEM", timestamp: 0 }, ...sm.buildSessionProjection().messages]);
142
+ const messages = projected?.messages;
143
+ const boot = messages.find((message) => message.role === "custom" && message.customType === BOOT_TYPE);
144
+ assert.equal(boot?.role === "custom" ? boot.content : undefined, expected);
145
+ assert.ok(expected.includes("keep this note's protocol quote") && expected.includes(" <notesoup:maps>\n"), "notes retain same-name tags verbatim");
146
+ assert.ok(messages.some((message) => message.role === "user" && JSON.stringify(message.content) === JSON.stringify([{ type: "text", text: oldBoot }])), "ordinary user content is not rewritten");
147
+ assert.deepEqual(sm.getBranch(), before, "projection never migrates or edits the persisted boot/history");
148
+ const persisted = sm.getBranch().find((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE);
149
+ assert.equal(persisted?.type === "custom_message" ? persisted.content : undefined, oldBoot);
150
+ }
151
+ });
125
152
  test("an empty root boot starts at the first projected seq", async () => {
126
153
  const sessionManager = manager();
127
154
  const captured = makeExtension(sessionManager);
@@ -9,7 +9,7 @@ import { build } from "esbuild";
9
9
  import { dispatch, handleLine } from "../plugins/claude/src/helper.js";
10
10
  import { DEFAULT_CLAUDE_RESET_MARGIN_TOKENS, resolveClaudeLimits } from "../plugins/claude/src/thresholds.js";
11
11
  import { WARNING_RUNWAY_TOKENS } from "../src/budget/constants.js";
12
- import { PROTOCOL_WIPE_SENTENCE, renderProtocolBlock } from "../src/boot/text.js";
12
+ import { MAPS_BLOCK, NOTES_PROTOCOL_OPEN_TAG, 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";
@@ -66,7 +66,7 @@ function fakeEngine(home) {
66
66
  settings: { read: async () => ({}) },
67
67
  command: { run: async () => ({}), register: async (spec) => ({ command: spec.name }) },
68
68
  clock: { after: () => { throw new Error("test has no pending manual timer"); } },
69
- prompt: { submit: async () => undefined },
69
+ prompt: { submit: async ({ text }) => ({ text }) },
70
70
  tool: { register: async (spec) => { registered.push(structuredClone(spec)); return { tool: `mcp__notesoup__${spec.name}` }; } },
71
71
  ui: { toast: async (text) => { notifications.push(text); }, log: (text) => { notifications.push(text); } },
72
72
  process: { run: async (argv, init) => ({
@@ -171,6 +171,7 @@ test("Claude helper boot uses actual Claude note tool bindings and a fresh snaps
171
171
  } });
172
172
  assert.match(boot, /mcp__notesoup__notes_\*/);
173
173
  assert.match(boot, /claude:session/);
174
+ assert.ok(boot.includes(NOTES_PROTOCOL_OPEN_TAG) && boot.includes(MAPS_BLOCK), "Claude keeps both teaching blocks in its existing boot injection");
174
175
  assert.doesNotMatch(boot, /brain empty|continuation/);
175
176
  assert.equal(boot.includes("chat view"), false, "a Claude boot never claims a reset clears the human's view");
176
177
  });
@@ -236,7 +237,17 @@ test("Claude limits derive from Claude's own auto-compact point, never a fixed p
236
237
  assert.equal(percent.source, "percent");
237
238
  assert.equal(percent.unit, "percent");
238
239
  assert.ok(Math.abs(percent.native - 83.5) < 1e-9 && Math.abs(percent.reset - 79.404) < 1e-9 && Math.abs(percent.warn - 71.212) < 1e-9, "83.5 / 79.4 / 71.2 on 200K");
239
- assert.equal(limitPoints({ env: { pctOverride: "50" } }).native, 50);
240
+ for (const facts of [
241
+ { env: { pctOverride: "50" } },
242
+ { settings: { autoCompactEnabled: false }, env: { pctOverride: "10" } },
243
+ { settings: { autoCompactWindow: 100_000 } },
244
+ ]) {
245
+ const fallback = resolveClaudeLimits(facts);
246
+ const tokens = resolveClaudeLimits({ ...facts, usage: { window: 200_000 } });
247
+ for (const point of ["native", "reset", "warn"])
248
+ assert.ok(Math.abs(fallback[point] - tokens[point] / 200_000 * 100) < 1e-9, `${point}: percent fallback uses the same token derivation`);
249
+ assert.equal(fallback.autoCompact, tokens.autoCompact);
250
+ }
240
251
  // A real window is never re-expressed on the assumed 200K window, and no point is zero:
241
252
  // the mod treats `measured >= reset` as due, so a zero point would clear memory every turn.
242
253
  const tiny = limitPoints({ usage: { window: 8_000 } });
@@ -492,7 +503,7 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
492
503
  }
493
504
  const call = (tool, params) => handlers.get("tool.call")(host, { tool: `mcp__notesoup__${tool}`, tool_use_id: "hook-1", ...params }, async (event) => event);
494
505
  const written = await call("notes_write", { address: "hook.md", content: "hook body" });
495
- assert.equal(written.result, "created hook.md", "the hook hands back the shared text unchanged");
506
+ assert.equal(written.result, "created hook.md | pinned false | budget 2048 | readonly false", "the hook hands back the shared text unchanged");
496
507
  assert.equal("isError" in written, false, "a success carries no discriminator at all, not a false one");
497
508
  const refused = await call("notes_read", { address: "absent.md" });
498
509
  assert.equal(refused.isError, true, "a refusal carries the literal the public ToolCallResult declares");
@@ -658,7 +669,7 @@ test("Claude headless warns without proactive resets and supports both manual al
658
669
  const timers = [];
659
670
  host.session.usage = async () => ({ context: { tokens, window: 200_000 } });
660
671
  host.clock.after = (_ms, callback) => { timers.push(callback); };
661
- host.prompt.submit = async () => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); };
672
+ host.prompt.submit = async ({ text }) => { prompts++; await invoke("turn.start"); await invoke("turn.complete", turnComplete()); return { text }; };
662
673
  host.command.run = async ({ command }) => {
663
674
  attempts++;
664
675
  await handlers.get("command.run")(host, { command, origin: { kind: "plugin", name: "notesoup" } }, async () => {
@@ -687,12 +698,6 @@ test("Claude headless warns without proactive resets and supports both manual al
687
698
  }
688
699
  assert.equal(attempts, 3);
689
700
  assert.equal(prompts, 2, "each idle alias schedules one close-out, not a summarizer");
690
- host.prompt.submit = async () => { throw new Error("close-out unavailable"); };
691
- await invoke("command.run", { command: "empty" });
692
- await Promise.resolve();
693
- await timers.shift()();
694
- await invoke("turn.complete", turnComplete());
695
- assert.equal(attempts, 4, "a failed close-out also leaves the reset pending");
696
701
  });
697
702
  test("Claude Mod keeps its window numbering from a boot written before the tag rename", async (t) => {
698
703
  const home = mkdtempSync(join(tmpdir(), "claude-legacy-boot-"));
@@ -767,6 +772,7 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
767
772
  prompts.push(text);
768
773
  await invoke("turn.start");
769
774
  await invoke("turn.complete", turnComplete());
775
+ return { text };
770
776
  };
771
777
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
772
778
  await invoke("session.start", { cwd: home, isInteractive: true });
@@ -796,6 +802,51 @@ test("Claude Mod manual reset uses one hidden close-out turn, then recovers its
796
802
  assert.equal(prompts.length, 1, "a busy manual request reuses the current turn instead of submitting another");
797
803
  assert.match(kept[0].text, /Current context window id: claude:hook-session:2/);
798
804
  });
805
+ test("Claude failed close-outs release the request so manual reset can retry", async (t) => {
806
+ for (const failure of ["texts", "submit", "drop"])
807
+ await t.test(failure, async (t) => {
808
+ const home = mkdtempSync(join(tmpdir(), "claude-closeout-retry-"));
809
+ t.after(() => rmSync(home, { recursive: true, force: true }));
810
+ const { host, notifications } = fakeEngine(home);
811
+ const helper = host.process.run;
812
+ let failing = true, resets = 0;
813
+ host.process.run = async (argv, init) => failing && failure === "texts" && JSON.parse(init.stdin).op === "texts"
814
+ ? { exitCode: 1, stdout: "" } : helper(argv, init);
815
+ const handlers = new Map();
816
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
817
+ const invoke = (name, e = {}) => handlers.get(name)(host, e, async () => ({}));
818
+ const timers = [];
819
+ host.clock.after = (_ms, callback) => { timers.push(callback); };
820
+ host.prompt.submit = async ({ text }) => {
821
+ if (failing && failure === "submit")
822
+ throw new Error("submission unavailable");
823
+ if (failing && failure === "drop")
824
+ return { drop: "another plugin refused" };
825
+ await invoke("turn.start");
826
+ await invoke("turn.complete", turnComplete());
827
+ return { text };
828
+ };
829
+ host.session.compact = async ({ instructions }) => {
830
+ resets++;
831
+ return await invoke("session.compact", { trigger: "plugin", instructions });
832
+ };
833
+ await invoke("session.start", { isInteractive: true });
834
+ await invoke("command.run", { command: "fresh-window" });
835
+ await Promise.resolve();
836
+ await timers.shift()();
837
+ assert.equal(resets, 0);
838
+ assert.ok(notifications.some(text => text.includes("close-out")), "failure is visible");
839
+ await invoke("turn.start");
840
+ await invoke("turn.complete", turnComplete());
841
+ assert.equal(resets, 0, "a failed close-out must not spring a reset on an unrelated turn");
842
+ failing = false;
843
+ assert.deepEqual(await invoke("command.run", { command: "fresh-window" }), { text: "🥣 Dumping Brain" });
844
+ await Promise.resolve();
845
+ assert.equal(timers.length, 1, "retry schedules new work instead of claiming it is already running");
846
+ await timers.shift()();
847
+ assert.equal(resets, 1);
848
+ });
849
+ });
799
850
  test("Claude Mod delivers one warning per window through main tools or prompt submission, never boot", async (t) => {
800
851
  const { host, invoke, context } = await retainedFixture(t);
801
852
  const texts = await dispatch({ op: "texts" });
@@ -855,6 +906,40 @@ test("Claude warnings read the public nested breakdown and apply pct even withou
855
906
  assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT], "native auto starts a new warning window");
856
907
  }
857
908
  });
909
+ test("Claude warning limits follow live model, threshold and settings changes without re-resolving for fill", async (t) => {
910
+ const home = mkdtempSync(join(tmpdir(), "claude-live-limits-"));
911
+ t.after(() => rmSync(home, { recursive: true, force: true }));
912
+ const { host } = fakeEngine(home);
913
+ let model = "claude-a", threshold = 167_000, tokens = 10_000;
914
+ const settings = { notesoup: { warningRunwayTokens: WARNING_RUNWAY_TOKENS } };
915
+ host.session.model = async () => model;
916
+ host.session.usage = async () => ({ context: { tokens, window: 200_000, breakdown: { model, autoCompactThreshold: threshold } } });
917
+ host.settings.read = async () => settings;
918
+ const helper = host.process.run;
919
+ let resolutions = 0;
920
+ host.process.run = async (argv, init) => {
921
+ if (JSON.parse(init.stdin).op === "limits")
922
+ resolutions++;
923
+ return helper(argv, init);
924
+ };
925
+ const handlers = new Map();
926
+ (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
927
+ await handlers.get("session.start")(host, { isInteractive: true }, async (e) => e);
928
+ const submit = () => handlers.get("prompt.submit")(host, { text: "continue" }, async (e) => e);
929
+ assert.equal((await submit()).context, undefined);
930
+ tokens = 30_000;
931
+ assert.equal((await submit()).context, undefined);
932
+ assert.equal(resolutions, 1, "changing fill reuses the points");
933
+ model = "claude-b";
934
+ assert.equal((await submit()).context, undefined);
935
+ assert.equal(resolutions, 2, "a model change invalidates points even at the same capacity");
936
+ threshold = 67_000;
937
+ assert.equal((await submit()).context, undefined);
938
+ assert.equal(resolutions, 3, "a live threshold change invalidates points without a model change");
939
+ settings.notesoup.warningRunwayTokens = 30_000;
940
+ assert.deepEqual((await submit()).context, [CLAUDE_WARNING_PROMPT]);
941
+ assert.equal(resolutions, 4, "settings changes apply without a session or capacity change");
942
+ });
858
943
  test("Claude Mod consumes a warning only after an accepted delivery and ignores stale generations", async (t) => {
859
944
  const { host, invoke } = await retainedFixture(t);
860
945
  const texts = await dispatch({ op: "texts" });
@@ -1133,7 +1218,7 @@ test("Claude asks for one handoff per compaction and reuses it when the same win
1133
1218
  const timers = [];
1134
1219
  const lines = [];
1135
1220
  host.clock.after = (_ms, callback) => { timers.push(callback); };
1136
- host.prompt.submit = async () => { await invoke("turn.start"); };
1221
+ host.prompt.submit = async ({ text }) => { await invoke("turn.start"); return { text }; };
1137
1222
  // The host retries one plugin compaction for the same window: one artifact, one draw.
1138
1223
  host.session.compact = async ({ instructions }) => {
1139
1224
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -1177,7 +1262,7 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1177
1262
  const run = host.process.run;
1178
1263
  host.process.run = async (argv, init) => { requests.push(JSON.parse(init.stdin)); return run(argv, init); };
1179
1264
  const written = await invoke("tool.call", { tool: "mcp__notesoup__notes_write", tool_use_id: "new-session", address: "session.md", content: action });
1180
- assert.equal(written.result, "created session.md");
1265
+ assert.equal(written.result, "created session.md | pinned false | budget 2048 | readonly false");
1181
1266
  assert.equal(requests[0].identity?.sessionId, `after-${action}`, "tools also use the new session notebook");
1182
1267
  });
1183
1268
  }
@@ -1254,7 +1339,7 @@ test("Claude serves every registered notes tool to subagents without leaking eve
1254
1339
  const call = (tool, params) => invoke("tool.call", {
1255
1340
  tool: `mcp__notesoup__${tool}`, tool_use_id: "child-call", agentId: "child", ...params,
1256
1341
  });
1257
- assert.equal((await call("notes_write", { address: "child.md", content: "child body" })).result, "created child.md");
1342
+ assert.equal((await call("notes_write", { address: "child.md", content: "child body" })).result, "created child.md | pinned false | budget 2048 | readonly false");
1258
1343
  assert.match((await call("notes_read", { address: "child.md" })).result, /child body/);
1259
1344
  assert.equal((await call("notes_update", { address: "child.md", edits: [{ oldText: "child body", newText: "updated body" }] })).isError, undefined);
1260
1345
  assert.match((await call("notes_list", {})).result, /child\.md/);
@@ -1276,7 +1361,7 @@ test("Claude identity uses the documented current model and cwd, with a safe mod
1276
1361
  return run(argv, init);
1277
1362
  };
1278
1363
  const write = (address, content) => invoke("tool.call", { tool: "mcp__notesoup__notes_write", tool_use_id: "model-call", address, content });
1279
- assert.equal((await write("@model/model.md", "opus")).result, "created @model/model.md");
1364
+ assert.equal((await write("@model/model.md", "opus")).result, "created @model/model.md | pinned false | budget 2048 | readonly false");
1280
1365
  assert.equal(seen.at(-1).identity.model, "claude-opus-4-6");
1281
1366
  assert.ok(readFileSync(join(home, "models/claude-opus-4-6/model.md"), "utf8").includes("opus"));
1282
1367
  model = "Claude Sonnet 4.6";
@@ -1312,7 +1397,7 @@ test("Claude current-cwd project resolution shares Pi's remote notebook across c
1312
1397
  cwd = second;
1313
1398
  const written = await call("notes_write", { address: "@project/shared", content: "Claude body" });
1314
1399
  assert.equal(written.isError, undefined);
1315
- assert.equal(written.result, "overwrote @project/shared.md (project api)");
1400
+ assert.equal(written.result, "overwrote @project/shared.md (project api) | pinned false | budget 2048 | readonly false");
1316
1401
  assert.equal((await createNotesStore(piIdentity).read("@project/shared"))?.body, "Claude body");
1317
1402
  assert.deepEqual(JSON.parse(readFileSync(join(home, "project/api/.project"), "utf8")), { id: "host/team/backend", path: second });
1318
1403
  assert.equal(resolveProjectNamespace(second, home).name, piIdentity.projectKey);
@@ -5,8 +5,8 @@ import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import zlib, { zstdCompressSync } from "node:zlib";
7
7
  import { test } from "node:test";
8
- import { readCodexHistory } from "../plugins/codex/src/history.js";
9
- import { readCodexTranscriptState } from "../plugins/codex/src/transcript.js";
8
+ import { readCodexHistory } from "../src/history/codex.js";
9
+ import { readCodexTranscriptState } from "../src/history/codex-transcript.js";
10
10
  import { createCodexTranscriptReader } from "../src/history/codex-transcript.js";
11
11
  import { allItems, eventDocument } from "../src/history/history.js";
12
12
  import { historyList, historyRead } from "../src/tools/history.js";
@@ -12,6 +12,7 @@ import { Check } from "typebox/value";
12
12
  import { runHook } from "../plugins/codex/src/hooks.js";
13
13
  import { writeBinding } from "../plugins/codex/src/identity.js";
14
14
  import { isolateHistoryRoots, writePiTranscript } from "./helpers/history-corpus.js";
15
+ import { MAPS_BLOCK, NOTES_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
15
16
  /* Producer-shaped synthetic fixtures, not captured/private transcripts.
16
17
  * Frozen official rust-v0.160.1, d27764b82f7118f674371e6d6e76271d9d606edb.
17
18
  * Legacy records omit ordinals; a Compacted record names the new native window.
@@ -321,6 +322,7 @@ test("a root boot carries the native window, native reset names, and is deduped
321
322
  const first = await runHook("SessionStart", startPayload(f), env);
322
323
  const boot = bootOf(first);
323
324
  assert.match(boot, /YOUR NOTES/);
325
+ assert.ok(boot.includes(NOTES_PROTOCOL_OPEN_TAG) && boot.includes(MAPS_BLOCK), "Codex keeps teaching in its native boot hook");
324
326
  assert.match(boot, new RegExp(`Agent name: anonymous \\(brain: gpt-5-4\\)`));
325
327
  assert.match(boot, new RegExp(`codex:${ROOT}`));
326
328
  assert.match(boot, new RegExp(`<notesoup:codex_window>\\nthread: ${ROOT}\\nwindow: ${W0}`));
@@ -50,12 +50,47 @@ test("the host-neutral core resolves without any SDK or plugin dependency", () =
50
50
  assert.equal(manifest.peerDependencies?.[name], "*", `${name} is a host-supplied peer dependency`);
51
51
  assert.equal(typeof manifest.devDependencies?.[name], "string", `${name} is pinned in devDependencies`);
52
52
  }
53
- for (const name of ["@earendil-works/pi-agent-core", "@earendil-works/pi-ai", "@earendil-works/pi-coding-agent"]) {
53
+ const piVersion = manifest.devDependencies["@earendil-works/pi-coding-agent"];
54
+ for (const name of ["@earendil-works/pi-agent-core", "@earendil-works/pi-ai", "@earendil-works/pi-coding-agent", "@earendil-works/pi-tui"]) {
55
+ assert.equal(manifest.devDependencies[name], piVersion, `${name} uses the same exact development release`);
54
56
  assert.equal(manifest.dependencies?.[name], undefined, `${name} is supplied by the host`);
55
- assert.equal(manifest.peerDependencies[name], "*", `${name} follows Pi's host dependency contract`);
57
+ assert.equal(manifest.peerDependencies[name], `^${piVersion}`, `${name} requires the supported Pi host release`);
56
58
  assert.equal(manifest.peerDependenciesMeta[name]?.optional, true, `${name} stays an optional peer`);
57
59
  }
58
60
  });
61
+ test("history resolves without a direct or transitive tool-layer dependency", () => {
62
+ const root = repository();
63
+ const config = ts.readConfigFile(join(root, "tsconfig.json"), ts.sys.readFile);
64
+ assert.equal(config.error, undefined);
65
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, root);
66
+ assert.deepEqual(parsed.errors, []);
67
+ assert.deepEqual(dependencyViolations(root, sources(join(root, "src/history")), parsed.options, new Set(["typebox"])), []);
68
+ });
69
+ test("the resolved history boundary rejects direct and indirect tool edges even through a previously visited shared module", t => {
70
+ const root = mkdtempSync(join(tmpdir(), "notesoup-history-boundary-"));
71
+ t.after(() => rmSync(root, { recursive: true, force: true }));
72
+ const put = (path, text) => { mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), text); };
73
+ put("package.json", '{"type":"module"}');
74
+ put("src/tools/result.ts", "export type Value = string; export const value = 1;");
75
+ put("src/shared.ts", 'export type { Value } from "@tool-result";');
76
+ const fixtureOptions = { ...options, baseUrl: root, paths: { "@tool-result": ["src/tools/result.ts"] } };
77
+ for (const edge of [
78
+ 'import type { Value } from "../shared.js"; export type Query = Value;',
79
+ 'export type { Value } from "../shared.js";',
80
+ 'export const load = () => import("../shared.js");',
81
+ 'export type Query = import("../shared.js").Value;',
82
+ ]) {
83
+ put("src/history/query.ts", edge);
84
+ assert.deepEqual(dependencyViolations(root, ["src/shared.ts", "src/history/query.ts"], fixtureOptions, new Set()), [
85
+ "src/history/query.ts -> src/shared.ts -> src/tools/result.ts",
86
+ ]);
87
+ }
88
+ put("src/history/query.ts", 'export { value } from "@tool-result";');
89
+ assert.deepEqual(dependencyViolations(root, ["src/history/query.ts"], fixtureOptions, new Set()), ["src/history/query.ts -> src/tools/result.ts"]);
90
+ put("src/shared.ts", 'export type Value = string;');
91
+ put("src/history/query.ts", 'export type { Value } from "../shared.js";');
92
+ assert.deepEqual(dependencyViolations(root, ["src/history/query.ts"], fixtureOptions, new Set()), []);
93
+ });
59
94
  test("a clean production tarball install loads both public entries", async (t) => {
60
95
  const root = repository();
61
96
  const work = mkdtempSync(join(tmpdir(), "notesoup-install-"));
@@ -210,7 +245,7 @@ test("AST guard sees every literal module edge, not import-like prose or comment
210
245
  });
211
246
  test("the core entry is host-neutral and the Pi plugin entry owns the extension", () => {
212
247
  assert.deepEqual(Object.keys(core).sort(), [
213
- "DEFAULT_BOOT_TOOL_NAMES", "NoteError", "createNotesStore", "deriveThresholds", "historyList", "historyRead",
248
+ "DEFAULT_BOOT_TOOL_NAMES", "NoteError", "createNotesStore", "deriveThresholds", "effectiveNotePolicy", "historyList", "historyRead",
214
249
  "loadNotesSnapshot", "noteIdentity", "notesIdentityForCall", "notesList", "notesRead", "notesSearch", "notesToolContext", "notesUpdate", "notesWrite", "projectHistory",
215
250
  "projectKey", "remainingBudget", "renderBootBlock", "renderProtocolBlock", "selectContinuation", "slugify",
216
251
  "tokenBudgetGuidance", "unavailableNotesSnapshot", "warningPrompt", "WARNING_BODY",
@@ -12,7 +12,7 @@ import { loadNotesSnapshot } from "../src/boot/snapshot.js";
12
12
  import { WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
13
13
  import { notesRead } from "../src/tools/notes.js";
14
14
  import { notesToolContext } from "../src/tools/notes-context.js";
15
- import { success } from "../src/tools/result.js";
15
+ import { success } from "../src/result.js";
16
16
  import { createNotesStore } from "../src/notes/index.js";
17
17
  import { dshFixture } from "./helpers/dsh.js";
18
18
  import { decodeHistory } from "../plugins/dsh/history.js";