notesoup 0.57.3 → 0.58.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 (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 +5 -18
  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 +8 -3
  41. package/dist/src/notes/store.js +64 -20
  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 +7 -6
  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-query-namespaces.test.js +7 -3
  72. package/dist/test/notes.integration.test.js +10 -10
  73. package/dist/test/notes.test.js +4 -4
  74. package/dist/test/pi-render.test.js +28 -1
  75. package/dist/test/project-namespace.test.js +1 -1
  76. package/docs/architecture.md +10 -7
  77. package/docs/dsh.md +1 -1
  78. package/docs/notes-library.md +20 -7
  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 +528 -422
  85. package/plugins/claude/hooks/register.ts +1 -10
  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 +5 -15
  91. package/plugins/codex/dist/codex/notesoup.js +520 -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 +66 -26
  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,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";
@@ -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
  });
@@ -492,7 +493,7 @@ test("Claude Mod hook delivers the helper's shared text, and marks only a refusa
492
493
  }
493
494
  const call = (tool, params) => handlers.get("tool.call")(host, { tool: `mcp__notesoup__${tool}`, tool_use_id: "hook-1", ...params }, async (event) => event);
494
495
  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");
496
+ assert.equal(written.result, "created hook.md | pinned false | budget 2048 | readonly false", "the hook hands back the shared text unchanged");
496
497
  assert.equal("isError" in written, false, "a success carries no discriminator at all, not a false one");
497
498
  const refused = await call("notes_read", { address: "absent.md" });
498
499
  assert.equal(refused.isError, true, "a refusal carries the literal the public ToolCallResult declares");
@@ -1177,7 +1178,7 @@ test("Claude session.end gives /clear, /resume and /branch a fresh boot and iden
1177
1178
  const run = host.process.run;
1178
1179
  host.process.run = async (argv, init) => { requests.push(JSON.parse(init.stdin)); return run(argv, init); };
1179
1180
  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");
1181
+ assert.equal(written.result, "created session.md | pinned false | budget 2048 | readonly false");
1181
1182
  assert.equal(requests[0].identity?.sessionId, `after-${action}`, "tools also use the new session notebook");
1182
1183
  });
1183
1184
  }
@@ -1254,7 +1255,7 @@ test("Claude serves every registered notes tool to subagents without leaking eve
1254
1255
  const call = (tool, params) => invoke("tool.call", {
1255
1256
  tool: `mcp__notesoup__${tool}`, tool_use_id: "child-call", agentId: "child", ...params,
1256
1257
  });
1257
- assert.equal((await call("notes_write", { address: "child.md", content: "child body" })).result, "created child.md");
1258
+ assert.equal((await call("notes_write", { address: "child.md", content: "child body" })).result, "created child.md | pinned false | budget 2048 | readonly false");
1258
1259
  assert.match((await call("notes_read", { address: "child.md" })).result, /child body/);
1259
1260
  assert.equal((await call("notes_update", { address: "child.md", edits: [{ oldText: "child body", newText: "updated body" }] })).isError, undefined);
1260
1261
  assert.match((await call("notes_list", {})).result, /child\.md/);
@@ -1276,7 +1277,7 @@ test("Claude identity uses the documented current model and cwd, with a safe mod
1276
1277
  return run(argv, init);
1277
1278
  };
1278
1279
  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");
1280
+ assert.equal((await write("@model/model.md", "opus")).result, "created @model/model.md | pinned false | budget 2048 | readonly false");
1280
1281
  assert.equal(seen.at(-1).identity.model, "claude-opus-4-6");
1281
1282
  assert.ok(readFileSync(join(home, "models/claude-opus-4-6/model.md"), "utf8").includes("opus"));
1282
1283
  model = "Claude Sonnet 4.6";
@@ -1312,7 +1313,7 @@ test("Claude current-cwd project resolution shares Pi's remote notebook across c
1312
1313
  cwd = second;
1313
1314
  const written = await call("notes_write", { address: "@project/shared", content: "Claude body" });
1314
1315
  assert.equal(written.isError, undefined);
1315
- assert.equal(written.result, "overwrote @project/shared.md (project api)");
1316
+ assert.equal(written.result, "overwrote @project/shared.md (project api) | pinned false | budget 2048 | readonly false");
1316
1317
  assert.equal((await createNotesStore(piIdentity).read("@project/shared"))?.body, "Claude body");
1317
1318
  assert.deepEqual(JSON.parse(readFileSync(join(home, "project/api/.project"), "utf8")), { id: "host/team/backend", path: second });
1318
1319
  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";
@@ -53,6 +53,8 @@ export function dependencyViolations(root, entries, options, runtimeDependencies
53
53
  const pluginRoot = resolve(root, "plugins");
54
54
  const notesRoot = resolve(sourceRoot, "notes");
55
55
  const notesEntry = resolve(sourceRoot, "notes/index.ts");
56
+ const historyRoot = resolve(sourceRoot, "history");
57
+ const toolsRoot = resolve(sourceRoot, "tools");
56
58
  const display = (path) => relative(root, path).split(sep).join("/");
57
59
  const local = (file) => file.startsWith(sourceRoot + sep) || file.startsWith(pluginRoot + sep);
58
60
  const adapter = (file) => {
@@ -60,16 +62,19 @@ export function dependencyViolations(root, entries, options, runtimeDependencies
60
62
  return /^plugins\/(pi|claude|dsh|codex)\//.exec(path)?.[1]
61
63
  ?? packageAdapter(file.split(sep).join("/").split("/node_modules/").at(-1));
62
64
  };
63
- const walk = (file, chain) => {
65
+ const walk = (file, chain, fromHistory = false) => {
64
66
  file = realpathSync(file);
65
- if (visited.has(file))
67
+ const history = fromHistory || file.startsWith(historyRoot + sep);
68
+ // A shared module may be legal on its own but forbidden when reached from history.
69
+ const key = `${history}:${file}`;
70
+ if (visited.has(key))
66
71
  return;
67
- visited.add(file);
72
+ visited.add(key);
68
73
  const here = [...chain, display(file)];
69
74
  const owner = adapter(file);
70
75
  const source = ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
71
76
  const emitted = new Set(local(file) ? moduleReferences(source, true) : []);
72
- if (local(file))
77
+ if (local(file) && !runtime.has(file))
73
78
  runtime.set(file, []);
74
79
  for (const specifier of moduleReferences(source)) {
75
80
  if (specifier.startsWith("node:") || builtins.has(specifier))
@@ -87,7 +92,8 @@ export function dependencyViolations(root, entries, options, runtimeDependencies
87
92
  }
88
93
  const target = realpathSync(resolution.resolvedFileName);
89
94
  const targetOwner = adapter(target);
90
- if ((targetOwner && targetOwner !== owner) ||
95
+ if ((history && target.startsWith(toolsRoot + sep)) ||
96
+ (targetOwner && targetOwner !== owner) ||
91
97
  (owner && target.startsWith(notesRoot + sep) && target !== notesEntry) ||
92
98
  (owner === "dsh" && target.startsWith(resolve(sourceRoot, "dream") + sep)) ||
93
99
  (!owner && target.startsWith(pluginRoot + sep))) {
@@ -101,7 +107,7 @@ export function dependencyViolations(root, entries, options, runtimeDependencies
101
107
  if (emitted.has(specifier) && local(target))
102
108
  runtime.get(file).push(target);
103
109
  if (!targetOwner || local(target))
104
- walk(target, here);
110
+ walk(target, here, history);
105
111
  }
106
112
  };
107
113
  for (const entry of entries)
@@ -1,7 +1,8 @@
1
1
  import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import { type ContextUsage, type ExtensionAPI, type ExtensionContext, type ExtensionToolContext, type RegisteredCommand, SessionManager, SettingsManager, type SessionBoundaryDraft, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
3
  import type { HistoryProjection } from "../../src/history/history.js";
4
- import { type OperationError, type TextWindow } from "../../src/tools/result.js";
4
+ import type { OperationError } from "../../src/result.js";
5
+ import { type TextWindow } from "../../src/tools/result.js";
5
6
  export type ExtensionTestEnvironment = {
6
7
  readonly cwd: string;
7
8
  readonly agentDir: string;
@@ -5,7 +5,7 @@ import { TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
5
5
  import { earliestMatchOffsetChars } from "../src/text-match.js";
6
6
  import { historyList, historyRead } from "../src/tools/history.js";
7
7
  import { historyDocument, projectHistory } from "../src/history/history.js";
8
- import { HistoryPageSchema, selectPage } from "../src/history/query.js";
8
+ import { CorpusCollector, HistoryPageSchema, selectPage } from "../src/history/query.js";
9
9
  import { appendText, assertWithinBudget, call, context, makeExtension, manager, resultData, resultError, resultRead, } from "./helpers/extension.js";
10
10
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
11
11
  import { isolateHistoryRoots, writePiTranscript } from "./helpers/history-corpus.js";
@@ -238,6 +238,52 @@ test("a one-row page budget admits the newest candidate first", () => {
238
238
  assert.deepEqual(keptSeqs(2), [2, 3], "a truncated prefix is the newest rows, delivered in chronological order");
239
239
  assert.deepEqual(keptSeqs(1, "oldest"), [1], "from oldest keeps the other end when the budget is short");
240
240
  });
241
+ test("query returns budget-failure facts while tools preserve single-session and corpus refusal text", async () => {
242
+ const projection = projectHistory([{ windowId: "w1", items: [{ seq: 1, windowId: "w1", role: "user", text: "message" }] }], 1, new Set([1]));
243
+ assert.deepEqual(selectPage(projection, {}, () => false, 100), { ok: false, pageTooLarge: { count: 1, multi: false } });
244
+ const collector = new CorpusCollector({});
245
+ collector.add("pi:budget", projection);
246
+ assert.deepEqual(collector.page(() => false, 100), { ok: false, pageTooLarge: { count: 1, multi: true } });
247
+ const context = {
248
+ current: () => projection,
249
+ corpus: { currentHarness: "pi", async sessions() {
250
+ return [{ harness: "pi", id: "budget", modifiedAt: 0, async load() { return { projection }; } }];
251
+ } },
252
+ };
253
+ const wrap = (text) => "x".repeat(TOOL_OUTPUT_MAX_BYTES + 1) + text;
254
+ for (const session of [undefined, "pi:budget", "*"]) {
255
+ const result = await historyList.execute({ session }, context, wrap);
256
+ const multi = session === "*";
257
+ const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
258
+ const message = `Even trimmed to their shortest, these 1 rows${multi ? "" : " and their folded runs"} fill the 32 KB a call can carry; ${narrow}.`;
259
+ assert.deepEqual(result, { ok: false, error: { code: "page_too_large", message } });
260
+ assert.equal(historyList.render(result), `error: page_too_large: ${message}`);
261
+ }
262
+ });
263
+ test("history page selection still charges host wrapping and session notices before delivering previews", async () => {
264
+ const text = `needle ${"😀".repeat(20_000)}`;
265
+ const projection = projectHistory([{ windowId: "w1", items: [{ seq: 1, windowId: "w1", role: "user", text }] }], 1, new Set([1]));
266
+ const notice = "notice ".repeat(100);
267
+ const context = {
268
+ current: () => projection,
269
+ corpus: { currentHarness: "pi", async sessions() {
270
+ return [{ harness: "pi", id: "wrapped", modifiedAt: 0, async load() { return { projection, notice }; } }];
271
+ } },
272
+ };
273
+ const wrap = (text) => "host ".repeat(200) + text;
274
+ for (const session of [undefined, "pi:wrapped", "*"]) {
275
+ const params = { session, query: "needle", max_chars_per_item: 50_000 };
276
+ const plain = await historyList.execute(params, context);
277
+ const wrapped = await historyList.execute(params, context, wrap);
278
+ assert.ok(plain.ok && wrapped.ok);
279
+ assert.ok(wrapped.data.items[0].content.length < plain.data.items[0].content.length);
280
+ assert.ok(text.startsWith(wrapped.data.items[0].content), "the preview is still verbatim");
281
+ if (session !== undefined)
282
+ assert.ok(wrapped.data.notice?.includes(notice));
283
+ assert.ok(Buffer.byteLength(wrap(historyList.render(wrapped)), "utf8") <= TOOL_OUTPUT_MAX_BYTES);
284
+ assert.ok(Buffer.byteLength(JSON.stringify(wrapped.data), "utf8") <= TOOL_OUTPUT_MAX_BYTES);
285
+ }
286
+ });
241
287
  test("conversation paging prepares ordered folds once, including during first-row shortening", () => {
242
288
  const windowId = "w1";
243
289
  const items = [
@@ -14,7 +14,8 @@ import { notesToolContext } from "../src/tools/notes-context.js";
14
14
  import { historyList, historyRead } from "../src/tools/history.js";
15
15
  import { historyRoles } from "../src/tools/schema.js";
16
16
  import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
17
- import { ERROR_MESSAGE_MAX_CHARS, failure, fitsResult, resultSchema, wireResult, readTextWindow, renderOutcome, renderTextWindow, success, structuredBytes, } from "../src/tools/result.js";
17
+ import { ERROR_MESSAGE_MAX_CHARS, failure, success } from "../src/result.js";
18
+ import { fitsResult, resultSchema, wireResult, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, } from "../src/tools/result.js";
18
19
  function identity(t) {
19
20
  const home = mkdtempSync(join(tmpdir(), "host-neutral-notes-"));
20
21
  t.after(() => rmSync(home, { recursive: true, force: true }));
@@ -193,7 +194,7 @@ test("shared note operations return canonical outcomes with a body-only read win
193
194
  }));
194
195
  assert.equal(observedKind, "body");
195
196
  assert.equal(updated.change_kind, "body");
196
- assert.equal(notesUpdate.render(success(updated)), `updated @project/test.md (project ${notesIdentity.projectKey})`);
197
+ assert.equal(notesUpdate.render(success(updated)), `updated @project/test.md (project ${notesIdentity.projectKey}) | pinned false | budget 2048 | readonly false`);
197
198
  await notesWrite.execute({ address: "owned.md", content: "first", origin: "user" }, toolContext);
198
199
  await notesWrite.execute({ address: "owned.md", content: "rewritten" }, toolContext);
199
200
  assert.equal(data(await notesRead.execute({ address: "owned.md" }, toolContext)).metadata.origin, "user", "tool overwrites preserve an omitted origin");
@@ -202,7 +203,7 @@ test("shared note operations return canonical outcomes with a body-only read win
202
203
  const moved = data(await notesUpdate.execute({ address: "owned.md", rename_to: "@project/renamed.md", edits: [{ oldText: "rewritten", newText: "final" }], origin: "external" }, toolContext));
203
204
  assert.equal(moved.change_kind, "moved");
204
205
  assert.equal(moved.rename_from, "owned.md");
205
- assert.equal(notesUpdate.render(success(moved)), "moved owned.md -> @project/renamed.md");
206
+ assert.equal(notesUpdate.render(success(moved)), "moved owned.md -> @project/renamed.md | pinned false | budget 2048 | readonly false");
206
207
  const renamed = data(await notesRead.execute({ address: moved.address }, toolContext));
207
208
  assert.equal(renamed.text, "final");
208
209
  assert.equal(renamed.metadata.origin, "external");