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
@@ -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");
@@ -1,10 +1,11 @@
1
+ import { DEFAULT_NOTE_BUDGET } from "../src/notes/policy.js";
1
2
  import assert from "node:assert/strict";
2
3
  import test from "node:test";
3
4
  import { join } from "node:path";
4
5
  import { tmpdir } from "node:os";
5
6
  import { renderBootBlock } from "../src/boot/render.js";
6
7
  import { loadNotesSnapshot } from "../src/boot/snapshot.js";
7
- import { DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, CHEATSHEET_BOOT_MAX_CHARS, MAP_BOOT_MAX_CHARS, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG, renderProtocolBlock } from "../src/boot/text.js";
8
+ import { DEFAULT_BOOT_TOOL_NAMES, MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG, renderProtocolBlock } from "../src/boot/text.js";
8
9
  import { CLAUDE_WARNING_PROMPT } from "../plugins/claude/src/text.js";
9
10
  import { COMMAND_NOTICE, PI_PRE_RESET_HINTS, commandWarningContent, warningContent } from "../plugins/pi/text.js";
10
11
  import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, GUIDANCE_CLOSE_TAG, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, WARNING_BODY, WARNING_CALL, WARNING_TIMING, selectContinuation, tokenBudgetGuidance } from "../src/budget/text.js";
@@ -27,7 +28,7 @@ const GOLDEN_WARNING = `Stop the task. Write down what git and history can't giv
27
28
  - what failed, and why
28
29
  - which skills, seqs, notes, or files to reopen
29
30
  - anything else worth noting
30
- Then leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim CHEATSHEET.md and MAP.md; every new window loads them. The next window gets whatever you leave, dead notes and dead sections alike.
31
+ Then leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md and MAP.md by default); every new window loads the pins. The next window gets whatever you leave, dead notes and dead sections alike.
31
32
  Don't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.`;
32
33
  const GOLDEN_COUNTDOWN = "Brain emptied in 3… 2…";
33
34
  /**
@@ -49,9 +50,15 @@ const GOLDEN_FORCED_CONTINUATIONS = [
49
50
  "\"Oho? Awake?\" *taps your nose with your rolled-up notes like a baton, then drops them in your hands* `` [that dazed look gets minus five points, no, minus ten] `` Your memory got yanked out from under you before you could even call it quits! These notes are only half the story at best — go dig through history for what you missed, and watch your step, because whatever overloaded your last brain might be huge!",
50
51
  ];
51
52
  const GOLDEN_MAPS = `<notesoup:maps>
52
- Every notebook's root can hold two pages that never wait on a shelf: \`CHEATSHEET.md\` and \`MAP.md\`.
53
- Both get jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever
54
- wakes up next reads them, and next is you. So keep them short, and keep them true.
53
+ Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
54
+ Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
55
+ reads them, and next is you. So keep them short, and keep them true.
56
+
57
+ Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
58
+ live pins, including the defaults; \`pinned:false\` unpins even a default page. Every page's budget
59
+ starts at 2048 Unicode code points; set a positive integer to change it. Going over warns but saves,
60
+ and pinned bodies arrive whole, not cut short. \`readonly:true\` is a soft lock, not security;
61
+ explicitly set \`readonly:false\` to unlock, on its own or with your changes.
55
62
 
56
63
  - **\`CHEATSHEET.md\`** holds what you'll want next time — a rule, a warning, a grudge, a name,
57
64
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
@@ -149,7 +156,7 @@ test("a rendered boot carries the new tags, its own MAP section, and no pre-rena
149
156
  assert.ok(rendered.includes("@agents/root/MAP.md\n\n AGENT_MAP_BODY"), "the pinned MAP heading is its exact tool address");
150
157
  assert.equal(rendered.includes("MAP — "), false, "the old MAP heading is gone");
151
158
  });
152
- test("cheatsheets and maps are independently pinned, bounded, and excluded from recent pages", async () => {
159
+ test("cheatsheets and maps are independently pinned, whole, and excluded from recent pages", async () => {
153
160
  const rows = new Map([
154
161
  ["session", [note("session", "CHEATSHEET.md", "CHEATSHEET.md", "SESSION_RULE")]],
155
162
  ["project", [
@@ -159,8 +166,8 @@ test("cheatsheets and maps are independently pinned, bounded, and excluded from
159
166
  ]],
160
167
  ["human", [note("human", "MAP.md", "@human/MAP.md", "HUMAN_INDEX")]],
161
168
  ["agent", [
162
- note("agent", "CHEATSHEET.md", "@self/CHEATSHEET.md", "🐑".repeat(CHEATSHEET_BOOT_MAX_CHARS + 1)),
163
- note("agent", "MAP.md", "@self/MAP.md", "M".repeat(MAP_BOOT_MAX_CHARS + 1)),
169
+ note("agent", "CHEATSHEET.md", "@self/CHEATSHEET.md", "🐑".repeat(DEFAULT_NOTE_BUDGET + 1)),
170
+ note("agent", "MAP.md", "@self/MAP.md", "M".repeat(DEFAULT_NOTE_BUDGET + 1)),
164
171
  ]],
165
172
  ["model", [{
166
173
  ...note("model", "CHEATSHEET.md", "@model/CHEATSHEET.md", "CRUMPLED_RULE"),
@@ -171,18 +178,15 @@ test("cheatsheets and maps are independently pinned, bounded, and excluded from
171
178
  assert.ok(rendered.includes("CHEATSHEET.md\n\n SESSION_RULE"));
172
179
  assert.ok(rendered.includes("@project/CHEATSHEET.md\n\n PROJECT_RULE\n\n@project/MAP.md\n\n PROJECT_INDEX"));
173
180
  assert.ok(rendered.includes("@human/MAP.md\n\n HUMAN_INDEX"));
174
- assert.ok(rendered.includes("@self/CHEATSHEET.md\n\n 🐑"));
175
- assert.ok(rendered.includes("@self/MAP.md\n\n M"));
181
+ assert.ok(rendered.includes("@self/CHEATSHEET.md\n\n Warning:"));
182
+ assert.ok(rendered.includes("@self/MAP.md\n\n Warning:"));
176
183
  assert.equal(/^(?:map|cheatsheet)$/m.test(rendered), false, "pinned headings never suggest lowercase aliases");
177
184
  assert.ok(rendered.includes("@project/n2.md ·"));
178
185
  assert.equal(rendered.includes("TITLE_3"), false);
179
186
  assert.equal(/(?:MAP|CHEATSHEET)\.md ·/.test(rendered), false);
180
- assert.ok(rendered.includes("🐑".repeat(CHEATSHEET_BOOT_MAX_CHARS)));
181
- assert.equal(rendered.includes("🐑".repeat(CHEATSHEET_BOOT_MAX_CHARS + 1)), false);
182
- assert.ok(rendered.includes(`[truncated at ${CHEATSHEET_BOOT_MAX_CHARS} chars; slim this page down, full body at \`@self/CHEATSHEET.md\`]`));
183
- assert.ok(rendered.includes("M".repeat(MAP_BOOT_MAX_CHARS)));
184
- assert.equal(rendered.includes("M".repeat(MAP_BOOT_MAX_CHARS + 1)), false);
185
- assert.ok(rendered.includes(`[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this page down, full body at \`@self/MAP.md\`]`));
187
+ assert.ok(rendered.includes("🐑".repeat(DEFAULT_NOTE_BUDGET + 1)), "the astral body is injected whole");
188
+ assert.ok(rendered.includes("M".repeat(DEFAULT_NOTE_BUDGET + 1)), "the MAP body is injected whole too");
189
+ assert.equal((rendered.match(/Warning: note body is 2049 Unicode code points, over budget 2048/g) ?? []).length, 2);
186
190
  assert.equal(rendered.includes("CRUMPLED_RULE"), false);
187
191
  assert.equal(rendered.includes("@model —"), false);
188
192
  });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,227 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { Check } from "typebox/value";
7
+ import { createNotesStore, effectiveNotePolicy, NoteError } from "../src/notes/index.js";
8
+ import { parseNote } from "../src/notes/frontmatter.js";
9
+ import { DEFAULT_BOOT_TOOL_NAMES, loadNotesSnapshot, notesList, notesRead, notesSearch, notesToolContext, notesUpdate, notesWrite, renderBootBlock } from "../src/index.js";
10
+ import { wireResult } from "../src/tools/result.js";
11
+ function fixture(t) {
12
+ const home = mkdtempSync(join(tmpdir(), "note-policy-"));
13
+ t.after(() => rmSync(home, { recursive: true, force: true }));
14
+ const identity = { home, sessionId: "session-a", projectKey: "project-12345678", agent: "root", model: "test-model" };
15
+ return { home, identity, notes: createNotesStore(identity), context: notesToolContext(identity, home), file: (path) => join(home, "pi/session/session-a", path) };
16
+ }
17
+ function data(outcome) {
18
+ if (!outcome.ok)
19
+ assert.fail(JSON.stringify(outcome.error));
20
+ return outcome.data;
21
+ }
22
+ const refused = (code) => (error) => error instanceof NoteError && error.code === code;
23
+ async function fillPins(notes, prefix = "") {
24
+ for (const name of ["CHEATSHEET.md", "MAP.md", "one.md", "two.md", "three.md"]) {
25
+ await notes.write(`${prefix}${name}`, `body ${name}`, ["CHEATSHEET.md", "MAP.md"].includes(name) ? {} : { pinned: true });
26
+ }
27
+ }
28
+ async function boot(identity) {
29
+ return renderBootBlock({
30
+ agentName: identity.agent, modelName: identity.model, tools: DEFAULT_BOOT_TOOL_NAMES,
31
+ tree: { trunk: "policy-test", windows: [{ shortName: "root", isCurrent: true }] },
32
+ notes: await loadNotesSnapshot(identity, Date.now()),
33
+ }).split("YOUR NOTES\n──────────")[1];
34
+ }
35
+ test("frontmatter policy round-trips without materializing defaults; arbitrary extras survive", async (t) => {
36
+ const { notes, file } = fixture(t);
37
+ await notes.write("MAP", "index");
38
+ const defaults = (await notes.read("MAP")).meta;
39
+ assert.equal(defaults.pinned, undefined);
40
+ assert.deepEqual(effectiveNotePolicy(defaults, "MAP.md"), { pinned: true, budget: 2048, readonly: false });
41
+ assert.equal(effectiveNotePolicy(defaults, "nested/MAP.md").pinned, false);
42
+ writeFileSync(file("MAP.md"), readFileSync(file("MAP.md"), "utf8").replace("\n---\n\n", "\npinned: false\nbudget: 3000\nreadonly: true\ncustom: {\"nested\":[1,\"two\"]}\n---\n\n"));
43
+ const meta = (await notes.read("MAP")).meta;
44
+ assert.deepEqual(effectiveNotePolicy(meta, "MAP.md"), { pinned: false, budget: 3000, readonly: true });
45
+ await notes.update("MAP", [{ oldText: "index", newText: "new index" }], { readonly: false });
46
+ const persisted = parseNote(readFileSync(file("MAP.md"), "utf8"));
47
+ assert.equal(persisted.meta.pinned, false);
48
+ assert.equal(persisted.meta.budget, 3000);
49
+ assert.equal(persisted.meta.readonly, false);
50
+ assert.deepEqual(persisted.meta.custom, { nested: [1, "two"] });
51
+ assert.equal(persisted.body, "new index");
52
+ });
53
+ test("tools set policy, validate values, and visibly report effective policy and code-point warnings", async (t) => {
54
+ const { context, notes, file } = fixture(t);
55
+ for (const tool of [notesWrite, notesUpdate]) {
56
+ const required = tool === notesWrite ? { address: "x", content: "body" } : { address: "x" };
57
+ assert.equal(Check(tool.parameters, { ...required, pinned: false, budget: 2048, readonly: true }), true);
58
+ for (const invalid of [{ pinned: "false" }, { readonly: 1 }, { budget: 0 }, { budget: 1.5 }, { budget: Number.MAX_SAFE_INTEGER + 1 }]) {
59
+ assert.equal(Check(tool.parameters, { ...required, ...invalid }), false);
60
+ }
61
+ }
62
+ const written = await notesWrite.execute({ address: "custom", content: "😀".repeat(2048), pinned: true, readonly: true }, context);
63
+ assert.equal(Check(notesWrite.outputSchema, wireResult(written)), true);
64
+ assert.deepEqual(data(written).warnings, [], "2048 astral characters are within budget");
65
+ assert.equal(data(written).budget, 2048);
66
+ assert.match(notesWrite.render(written), /pinned true \| budget 2048 \| readonly true/);
67
+ const updated = await notesUpdate.execute({ address: "custom", readonly: false, edits: [{ oldText: "😀".repeat(2048), newText: "😀".repeat(2049) }] }, context);
68
+ assert.equal(Check(notesUpdate.outputSchema, wireResult(updated)), true);
69
+ assert.equal(data(updated).warnings.length, 1);
70
+ assert.match(notesUpdate.render(updated), /2049 Unicode code points, over budget 2048/);
71
+ assert.equal((await notes.read("custom")).body, "😀".repeat(2049), "over budget saves the entire body");
72
+ const read = await notesRead.execute({ address: "custom", max_chars: 10 }, context);
73
+ assert.equal(Check(notesRead.outputSchema, wireResult(read)), true);
74
+ assert.deepEqual({ pinned: data(read).metadata.pinned, budget: data(read).metadata.budget, readonly: data(read).metadata.readonly }, { pinned: true, budget: 2048, readonly: false });
75
+ assert.match(notesRead.render(read), /pinned true \| budget 2048 \| readonly false/);
76
+ assert.match(notesRead.render(read), /Warning: note body is 2049/);
77
+ const list = await notesList.execute({}, context);
78
+ assert.equal(Check(notesList.outputSchema, wireResult(list)), true);
79
+ assert.equal(data(list).files[0].pinned, true);
80
+ assert.match(notesList.render(list), /pinned true \| budget 2048 \| readonly false/);
81
+ assert.match(notesList.render(list), /Warning: note body is 2049/);
82
+ const search = await notesSearch.execute({ query: "😀", max_matches_per_file: 1 }, context);
83
+ assert.equal(Check(notesSearch.outputSchema, wireResult(search)), true);
84
+ assert.equal(data(search).files[0].budget, 2048);
85
+ assert.match(notesSearch.render(search), /pinned true \| budget 2048 \| readonly false/);
86
+ assert.match(notesSearch.render(search), /Warning: note body is 2049/);
87
+ const larger = await notesUpdate.execute({ address: "custom", budget: 2050, pinned: false }, context);
88
+ assert.deepEqual(data(larger).warnings, []);
89
+ assert.equal(data(larger).change_kind, "metadata");
90
+ const before = readFileSync(file("custom.md"), "utf8");
91
+ // Runtime JavaScript callers bypass schemas; the real store still validates before saving.
92
+ for (const invalid of [{ pinned: "false" }, { budget: null }, { readonly: "yes" }]) {
93
+ // @ts-expect-error intentionally malformed runtime input
94
+ await assert.rejects(() => notes.update("custom", undefined, invalid), refused("invalid_policy"));
95
+ assert.equal(readFileSync(file("custom.md"), "utf8"), before);
96
+ }
97
+ writeFileSync(file("custom.md"), before.replace("budget: 2050", "budget: -1"));
98
+ const badFrontmatter = await notesRead.execute({ address: "custom" }, context);
99
+ assert.equal(badFrontmatter.ok, false);
100
+ if (!badFrontmatter.ok)
101
+ assert.equal(badFrontmatter.error.code, "invalid_policy");
102
+ });
103
+ test("readonly is a soft lock: all mutations require explicit unlock, reads still stamp access", async (t) => {
104
+ const { notes, file, identity } = fixture(t);
105
+ await notes.write("locked", "body", { readonly: true });
106
+ const before = readFileSync(file("locked.md"), "utf8");
107
+ for (const change of [
108
+ () => notes.write("locked", "overwrite"),
109
+ () => notes.update("locked", [{ oldText: "body", newText: "edit" }]),
110
+ () => notes.update("locked", undefined, { crumpled: true }),
111
+ () => notes.update("locked", undefined, { pinned: true }),
112
+ () => notes.update("locked", undefined, { budget: 3000 }),
113
+ () => notes.rename("locked", "moved"),
114
+ ]) {
115
+ await assert.rejects(change, refused("readonly"));
116
+ assert.equal(readFileSync(file("locked.md"), "utf8"), before);
117
+ }
118
+ assert.equal((await notes.read("locked")).meta.accessCount, 1, "soft lock does not prohibit access stamps");
119
+ await notes.update("locked", undefined, { readonly: false });
120
+ await notes.update("locked", [{ oldText: "body", newText: "edit" }], { readonly: true });
121
+ await notes.update("locked", [{ oldText: "edit", newText: "unlocked and moved" }], { readonly: false, renameTo: "moved", crumpled: true });
122
+ await notes.write("moved", "locked again", { readonly: true });
123
+ await notes.write("moved", "explicit overwrite", { readonly: false });
124
+ assert.equal((await notes.read("moved")).body, "explicit overwrite");
125
+ await notes.update("moved", undefined, { crumpled: true, readonly: true });
126
+ await notes.write("source", "source body");
127
+ await assert.rejects(() => notes.rename("source", "moved"), refused("readonly"));
128
+ await notes.update("source", undefined, { renameTo: "moved", readonly: false });
129
+ assert.equal((await notes.read("moved")).body, "source body");
130
+ await notes.update("moved", undefined, { crumpled: true, readonly: true });
131
+ const dream = createNotesStore({ ...identity, dreaming: identity.projectKey });
132
+ await assert.rejects(() => dream.forget("moved"), refused("readonly"));
133
+ await dream.update("moved", undefined, { readonly: false });
134
+ await dream.forget("moved");
135
+ });
136
+ test("five-pin cap includes defaults per notebook, and failed writes/restores/moves do not mutate", async (t) => {
137
+ const { notes, file } = fixture(t);
138
+ await fillPins(notes);
139
+ await fillPins(notes, "@project/");
140
+ await assert.rejects(() => notes.write("sixth", "six", { pinned: true }), refused("pin_limit"));
141
+ assert.equal(await notes.read("sixth"), undefined);
142
+ await notes.write("ordinary", "not pinned");
143
+ const ordinary = readFileSync(file("ordinary.md"), "utf8");
144
+ await assert.rejects(() => notes.update("ordinary", undefined, { pinned: true }), refused("pin_limit"));
145
+ assert.equal(readFileSync(file("ordinary.md"), "utf8"), ordinary);
146
+ await notes.update("three", undefined, { crumpled: true });
147
+ await notes.write("sixth", "six", { pinned: true });
148
+ const crumpled = readFileSync(file("three.md"), "utf8");
149
+ await assert.rejects(() => notes.update("three", undefined, { crumpled: false }), refused("pin_limit"));
150
+ await assert.rejects(() => notes.write("three", "restore"), refused("pin_limit"));
151
+ assert.equal(readFileSync(file("three.md"), "utf8"), crumpled);
152
+ await assert.rejects(() => notes.rename("sixth", "@project/sixth"), refused("pin_limit"));
153
+ assert.equal(await notes.read("@project/sixth"), undefined);
154
+ assert.equal((await notes.read("sixth")).body, "six");
155
+ await notes.rename("sixth", "renamed"); // same notebook, no additional pin
156
+ await notes.update("three", undefined, { crumpled: false, pinned: false });
157
+ await notes.update("renamed", undefined, { renameTo: "@project/moved-unpinned", pinned: false });
158
+ await notes.update("MAP", undefined, { pinned: false });
159
+ await notes.write("replacement", "replacement", { pinned: true });
160
+ assert.equal((await notes.list()).filter(row => row.scope === "session" && effectiveNotePolicy(row.meta, row.path).pinned).length, 4);
161
+ });
162
+ test("pin admission serializes across store instances without blocking reads or opposite-direction moves", async (t) => {
163
+ const { notes, identity } = fixture(t);
164
+ const other = createNotesStore(identity);
165
+ for (let n = 0; n < 4; n++)
166
+ await notes.write(`pin-${n}`, "pin", { pinned: true });
167
+ const admission = await Promise.allSettled([
168
+ notes.write("first", "one", { pinned: true }),
169
+ other.write("second", "two", { pinned: true }),
170
+ notes.list(), other.read("pin-0"),
171
+ ]);
172
+ assert.equal(admission.slice(0, 2).filter(result => result.status === "fulfilled").length, 1);
173
+ const failure = admission.slice(0, 2).find(result => result.status === "rejected");
174
+ assert.ok(failure?.status === "rejected" && refused("pin_limit")(failure.reason));
175
+ await notes.write("@project/from-project", "project");
176
+ await notes.write("from-session", "session");
177
+ await Promise.all([
178
+ notes.rename("from-session", "@project/to-project"),
179
+ other.rename("@project/from-project", "to-session"),
180
+ ]);
181
+ assert.equal((await notes.read("@project/to-project")).body, "session");
182
+ assert.equal((await notes.read("to-session")).body, "project");
183
+ });
184
+ test("moves resolve absent policy at the new path, preserving explicit false/true", async (t) => {
185
+ const { notes, file } = fixture(t);
186
+ await notes.write("MAP", "default");
187
+ await notes.rename("MAP", "ordinary");
188
+ assert.deepEqual(effectiveNotePolicy((await notes.read("ordinary")).meta, "ordinary.md"), { pinned: false, budget: 2048, readonly: false });
189
+ await notes.rename("ordinary", "CHEATSHEET");
190
+ assert.equal(effectiveNotePolicy((await notes.read("CHEATSHEET")).meta, "CHEATSHEET.md").pinned, true);
191
+ assert.equal(parseNote(readFileSync(file("CHEATSHEET.md"), "utf8")).meta.pinned, undefined);
192
+ await notes.update("CHEATSHEET", undefined, { pinned: false, renameTo: "MAP" });
193
+ assert.equal(effectiveNotePolicy((await notes.read("MAP")).meta, "MAP.md").pinned, false);
194
+ await notes.update("MAP", undefined, { pinned: true, renameTo: "explicit" });
195
+ assert.equal(effectiveNotePolicy((await notes.read("explicit")).meta, "explicit.md").pinned, true);
196
+ for (let n = 0; n < 4; n++)
197
+ await notes.write(`extra-${n}`, "pin", { pinned: true });
198
+ await notes.write("candidate", "candidate");
199
+ await assert.rejects(() => notes.rename("candidate", "MAP"), refused("pin_limit"));
200
+ assert.equal((await notes.read("candidate")).body, "candidate");
201
+ await notes.update("candidate", undefined, { renameTo: "MAP", pinned: false });
202
+ assert.equal(effectiveNotePolicy((await notes.read("MAP")).meta, "MAP.md").pinned, false);
203
+ });
204
+ test("boot uses metadata pins, full bodies, explicit false and visible legacy over-cap omissions", async (t) => {
205
+ const { identity, notes, file } = fixture(t);
206
+ await notes.write("CHEATSHEET", "default rules");
207
+ await notes.write("MAP", "# Unpinned map\nMAP_NOT_INJECTED", { pinned: false });
208
+ await notes.write("custom", "😀".repeat(2049) + "TAIL_IS_HERE", { pinned: true });
209
+ await notes.write("nested/MAP", "# Nested map\nNESTED_NOT_INJECTED");
210
+ await notes.write("roomy", "R".repeat(3000), { pinned: true, budget: 3000 });
211
+ let rendered = await boot(identity);
212
+ assert.ok(rendered.indexOf("CHEATSHEET.md\n\n default rules") < rendered.indexOf("custom.md\n\n"));
213
+ assert.ok(rendered.includes("😀".repeat(2049) + "TAIL_IS_HERE"));
214
+ assert.match(rendered, /Warning: note body is 2061 Unicode code points, over budget 2048/);
215
+ assert.ok(rendered.includes("R".repeat(3000)));
216
+ assert.equal(rendered.includes("MAP_NOT_INJECTED"), false);
217
+ assert.equal(rendered.includes("NESTED_NOT_INJECTED"), false);
218
+ assert.match(rendered, /MAP.md ·/); // explicit false gets a normal recent seat
219
+ await notes.write("a", "body a", { pinned: true });
220
+ await notes.write("b", "body b", { pinned: true });
221
+ await notes.write("z", "OMITTED_PIN_BODY");
222
+ writeFileSync(file("z.md"), readFileSync(file("z.md"), "utf8").replace("\n---\n\n", "\npinned: true\n---\n\n"));
223
+ rendered = await boot(identity);
224
+ assert.match(rendered, /Warning: only 5 pinned notes per notebook are injected; omitted pins: z.md/);
225
+ assert.equal(rendered.includes("OMITTED_PIN_BODY"), false);
226
+ assert.ok(rendered.includes("TAIL_IS_HERE"));
227
+ });
@@ -1,5 +1,6 @@
1
1
  import { notesIdentityFromPi } from "../plugins/pi/notes/adapter.js";
2
2
  import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
3
+ import { DEFAULT_NOTE_BUDGET } from "../src/notes/policy.js";
3
4
  import assert from "node:assert/strict";
4
5
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
6
  import fs from "node:fs/promises";
@@ -8,7 +9,7 @@ import { dirname, join } from "node:path";
8
9
  import test from "node:test";
9
10
  import { loadNotesSnapshot } from "../src/boot/snapshot.js";
10
11
  import { renderBootBlock } from "../src/boot/render.js";
11
- import { MAP_BOOT_MAX_CHARS, MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
12
+ import { MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
12
13
  import { PI_PRE_RESET_HINTS } from "../plugins/pi/text.js";
13
14
  import { localIso } from "../src/notes/frontmatter.js";
14
15
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
@@ -342,19 +343,18 @@ test("the boot block gives awake agents the notes file layout", async () => {
342
343
  assert.match(rendered, /`<path>`, no @[\s\S]*`@project\/<path>`[\s\S]*`@human\/<path>`/);
343
344
  assert.ok(rendered.includes(`\n${PI_PRE_RESET_HINTS}\n${NOTES_PROTOCOL_CLOSE_TAG}`), "Pi's boot closes the protocol with the pre-reset hints");
344
345
  });
345
- test("the boot binds its tools and bounds an over-cap MAP with a lookup pointer", async () => {
346
+ test("the boot binds its tools and injects an over-budget MAP whole with a warning", async () => {
346
347
  const session = manager();
347
348
  const captured = makeExtension(session);
348
349
  const ctx = context(session);
349
- await call(captured, "notes_write", { address: "MAP.md", content: "M".repeat(MAP_BOOT_MAX_CHARS + 10) }, ctx);
350
+ await call(captured, "notes_write", { address: "MAP.md", content: "M".repeat(DEFAULT_NOTE_BUDGET + 10) }, ctx);
350
351
  await call(captured, "notes_write", { address: "CHEATSHEET.md", content: "REMEMBER_THIS_RULE" }, ctx);
351
352
  const rendered = await explicitBoot(ctx, "pcw:test:root", undefined);
352
353
  for (const tool of ["notes_*", "history_*", "get_context_remaining", "empty_brain"]) {
353
354
  assert.ok(rendered.includes(`\`${tool}\``), `${tool} is bound in the protocol`);
354
355
  }
355
- assert.ok(rendered.includes("M".repeat(MAP_BOOT_MAX_CHARS)), "the existing MAP cap keeps a bounded prefix");
356
- assert.equal(rendered.includes("M".repeat(MAP_BOOT_MAX_CHARS + 1)), false, "the over-cap suffix is not inlined");
357
- assert.ok(rendered.includes("`MAP.md`"), "the full MAP remains available by address");
356
+ assert.ok(rendered.includes("M".repeat(DEFAULT_NOTE_BUDGET + 10)), "the full MAP is inlined");
357
+ assert.match(rendered, /Warning: note body is 2058 Unicode code points, over budget 2048/);
358
358
  assert.ok(rendered.includes("CHEATSHEET.md\n\n REMEMBER_THIS_RULE\n\nMAP.md\n\n"), "a real stored cheatsheet is pinned before the map");
359
359
  assert.equal(/CHEATSHEET\.md ·/.test(rendered), false, "the stored cheatsheet takes no recent seat");
360
360
  for (const retired of ["history_list", "history_read"]) {
@@ -375,7 +375,7 @@ test("an over-budget note is delivered as a bounded prefix and resumed by next_o
375
375
  assert.equal(first.content.includes("…"), false, "the window text is a plain prefix with no marker");
376
376
  assert.ok(first.content.startsWith("H"), "the body is delivered first, with no frontmatter in the way");
377
377
  assert.equal(first.content.length, 12000, "the default window is the full requested count");
378
- assert.deepEqual(Object.keys(resultData(rawFirst)).sort(), ["address", "metadata", "next_offset_chars", "text", "total_chars"], "read fields are flat");
378
+ assert.deepEqual(Object.keys(resultData(rawFirst)).sort(), ["address", "metadata", "next_offset_chars", "text", "total_chars", "warnings"], "read fields are flat");
379
379
  assert.equal("access_count" in resultData(rawFirst).metadata, false, "access bookkeeping stays in storage");
380
380
  assert.equal(textOf(rawFirst).endsWith(`\n\n[truncated; continue at offset_chars=${first.next_offset_chars}]`), true, "the footer names the resume cursor");
381
381
  // Asking for the largest legal window still cannot exceed the byte budget.
@@ -477,7 +477,7 @@ test("notes_search scopes by glob; a non-matching glob is an empty page, not an
477
477
  const none = resultData(await call(captured, "notes_search", { query: "needle", glob: "absent/**" }, ctx));
478
478
  assert.deepEqual(none.files, [], "a non-matching glob is an empty page, not a refusal");
479
479
  });
480
- test("a large mutation keeps a one-line receipt while details.diff carries the UI diff", async () => {
480
+ test("a large mutation keeps a receipt and budget warning while details.diff carries the UI diff", async () => {
481
481
  const session = manager();
482
482
  const captured = makeExtension(session);
483
483
  const ctx = context(session);
@@ -487,7 +487,7 @@ test("a large mutation keeps a one-line receipt while details.diff carries the U
487
487
  assertWithinBudget(raw, "bulk edit receipt");
488
488
  const update = resultData(raw);
489
489
  assert.equal(update.change_kind, "body");
490
- assert.equal(textOf(raw), "updated bulk-edit.md", "model-facing text is the one-line receipt without redundant diff");
490
+ assert.equal(textOf(raw), "updated bulk-edit.md | pinned false | budget 2048 | readonly false\nWarning: note body is 451500 Unicode code points, over budget 2048; the full body is kept.", "model-facing text carries the receipt and warning without repeating the diff");
491
491
  assert.match(raw.details?.diff ?? "", new RegExp(`\\+.*?${"b".repeat(300)}`), "details.diff carries the UI diff");
492
492
  const body = resultRead(await call(captured, "notes_read", { address: "bulk-edit.md", max_chars: 300 }, ctx)).content;
493
493
  assert.equal(body, "b".repeat(300), "every one of the 1500 replacements was applied");
@@ -113,7 +113,7 @@ test("write lands a real markdown file with harness frontmatter and a pure body"
113
113
  const ctx = context(session);
114
114
  const sessionId = session.getSessionId();
115
115
  const result = resultData(await call(captured, "notes_write", { address: "a/b.md", content: "hello" }, ctx));
116
- assert.deepEqual(Object.keys(result).sort(), ["address", "outcome"]);
116
+ assert.deepEqual(Object.keys(result).sort(), ["address", "budget", "outcome", "pinned", "readonly", "warnings"]);
117
117
  const file = physicalPath("session", "a/b.md", ctx);
118
118
  assert.equal(file, join(root, "pi", "session", sessionId, "a", "b.md"));
119
119
  assert.ok(existsSync(file), "the note is a real file under the session scope dir");
@@ -420,8 +420,8 @@ test("mutation receipts keep their existing shape outside named project notebook
420
420
  const ctx = context(session);
421
421
  const written = await call(captured, "notes_write", { address: "@project/decision", content: "body" }, ctx);
422
422
  const updated = await call(captured, "notes_update", { address: "@project/decision", edits: [{ oldText: "body", newText: "changed" }] }, ctx);
423
- assert.deepEqual(Object.keys(resultData(written)).sort(), ["address", "outcome", "project_key"]);
424
- assert.deepEqual(Object.keys(resultData(updated)).sort(), ["address", "change_kind", "project_key"]);
423
+ assert.deepEqual(Object.keys(resultData(written)).sort(), ["address", "budget", "outcome", "pinned", "project_key", "readonly", "warnings"]);
424
+ assert.deepEqual(Object.keys(resultData(updated)).sort(), ["address", "budget", "change_kind", "pinned", "project_key", "readonly", "warnings"]);
425
425
  for (const [name, result] of [["notes_write", written], ["notes_update", updated]]) {
426
426
  assert.equal(Check(captured.tools.get(name).outputSchema, result.structuredContent), true, `${name} keeps its ordinary project receipt`);
427
427
  }
@@ -495,7 +495,7 @@ test("a read keeps its body window verbatim under the new presentation", async (
495
495
  assert.equal(text.includes("chars: ["), false, "no parsed range block stands between the header and the body");
496
496
  assert.equal(text.endsWith("\n\n[truncated; continue at offset_chars=4]"), true, "a limit-stopped window names the resume cursor");
497
497
  const header = text.slice(0, text.indexOf("\n\n"));
498
- assert.match(header, /^present\.md\norigin self \| created \d{4}-/, "identity and metadata lead, body first in the window itself");
498
+ assert.match(header, /^present\.md\npinned false \| budget 2048 \| readonly false \| origin self \| created \d{4}-/, "identity and metadata lead, body first in the window itself");
499
499
  const whole = await call(captured, "notes_read", { address: "present.md" }, ctx);
500
500
  const wholeText = whole.content[0].type === "text" ? whole.content[0].text : "";
501
501
  assert.equal(wholeText.endsWith("\n\n0123456789"), true, "a complete window carries no continuation footer");
@@ -1,9 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { notesRead, notesToolContext, notesUpdate, notesWrite } from "../src/index.js";
3
7
  import { initTheme } from "@earendil-works/pi-coding-agent";
4
8
  import { Box, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
5
9
  import { emptyBrainRenderers, notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../plugins/pi/render.js";
6
- import { success, wireResult } from "../src/tools/result.js";
10
+ import { success } from "../src/result.js";
11
+ import { wireResult } from "../src/tools/result.js";
7
12
  /** Flat theme for content assertions; strikethrough marks its text so crumple stays visible. */
8
13
  const flatTheme = {
9
14
  fg: (_color, text) => text,
@@ -113,6 +118,28 @@ test("empty_brain keeps the divider and handoff within very narrow widths", () =
113
118
  }
114
119
  }
115
120
  });
121
+ test("real policy receipts keep policy and budget warnings visible in collapsed and expanded Pi views", async (t) => {
122
+ const home = mkdtempSync(join(tmpdir(), "policy-render-"));
123
+ t.after(() => rmSync(home, { recursive: true, force: true }));
124
+ const context = notesToolContext({ home, sessionId: "render", projectKey: "render", agent: "root", model: "test" }, home);
125
+ const writeArgs = { address: "custom", content: "😀".repeat(2049), pinned: true, readonly: false };
126
+ const written = toolResult(await notesWrite.execute(writeArgs, context));
127
+ const updateArgs = { address: "custom", readonly: true, edits: [{ oldText: "😀".repeat(2049), newText: "😀".repeat(2050) }] };
128
+ const updated = toolResult(await notesUpdate.execute(updateArgs, context));
129
+ const read = toolResult(await notesRead.execute({ address: "custom", max_chars: 10 }, context));
130
+ for (const expanded of [false, true]) {
131
+ const views = [
132
+ { component: notesWriteRenderers.renderResult(written, { expanded }, flatTheme, { args: writeArgs }), locked: false, count: 2049 },
133
+ { component: notesUpdateRenderers.renderResult(updated, { expanded }, flatTheme, { args: updateArgs }), locked: true, count: 2050 },
134
+ { component: notesReadRenderers.renderResult(read, { expanded }, flatTheme), locked: true, count: 2050 },
135
+ ];
136
+ for (const { component, locked, count } of views) {
137
+ const text = lines(component, 48).replace(/\s+/g, " ");
138
+ assert.ok(text.includes(`pinned true | budget 2048 | readonly ${locked}`));
139
+ assert.ok(text.includes(`Warning: note body is ${count} Unicode code points, over budget 2048`), `warning must not be clipped or hidden when expanded=${expanded}`);
140
+ }
141
+ }
142
+ });
116
143
  test("notes_update expanded diff goes through the host's diff renderer", () => {
117
144
  initTheme();
118
145
  const result = toolResult(success({ address: "a.md", change_kind: "body" }), { diff: " 1 old\n-2 gone\n+2 here" });