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,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
+ });
@@ -38,7 +38,9 @@ test("default spellings stay local while explicit ** lists and searches each not
38
38
  }
39
39
  const rows = await notes.list({ glob: "**" });
40
40
  assert.deepEqual(addresses(rows), all);
41
+ assert.deepEqual(addresses(await notes.list({ glob: "*" })), all);
41
42
  assert.deepEqual(addresses(await notes.search(["needle"], { glob: "**" })), all);
43
+ assert.deepEqual(addresses(await notes.search(["needle"], { glob: "*" })), all);
42
44
  assert.equal(new Set(rows.map(row => row.address)).size, rows.length);
43
45
  for (const row of rows)
44
46
  assert.equal((await notes.read(row.address))?.body.startsWith("needle"), true, "every result is a real readable address");
@@ -48,14 +50,16 @@ test("default spellings stay local while explicit ** lists and searches each not
48
50
  assert.deepEqual(addresses(await notes.list({ glob: "@model/**" })), ["@model/shared.md"]);
49
51
  assert.deepEqual(addresses(await notes.list({ glob: `@projects/${identity.projectKey}/**` })), [`@projects/${identity.projectKey}/shared.md`], "explicit current project stays a named read-only address");
50
52
  });
51
- test("explicit patterns use canonical addresses, with bare-path matching only for the current session", async (t) => {
53
+ test("slashless patterns match filenames at any depth while slash-qualified bare paths match the current session", async (t) => {
52
54
  const { notes, identity, foreignIdentity, foreign, all } = await populate(t);
53
55
  await notes.write("deep/nested.md", "needle nested");
54
56
  await foreign.write("deep/nested.md", "needle elsewhere");
55
57
  await foreign.write("only-foreign.md", "needle foreign only");
56
- assert.deepEqual(addresses(await notes.list({ glob: "*.md" })), ["shared.md"]);
58
+ const everyNote = [...all, "deep/nested.md", `@sessions/${foreignIdentity.sessionId}/deep/nested.md`, `@sessions/${foreignIdentity.sessionId}/only-foreign.md`].sort();
59
+ assert.deepEqual(addresses(await notes.list({ glob: "*.md" })), everyNote);
60
+ assert.deepEqual(addresses(await notes.list({ glob: "nested.md" })), [`@sessions/${foreignIdentity.sessionId}/deep/nested.md`, "deep/nested.md"]);
57
61
  assert.deepEqual(addresses(await notes.list({ glob: "deep/**" })), ["deep/nested.md"]);
58
- assert.deepEqual(await notes.search(["needle"], { glob: "only-foreign.md" }), [], "foreign sessions get no implicit basename alias");
62
+ assert.deepEqual(addresses(await notes.search(["needle"], { glob: "only-foreign.md" })), [`@sessions/${foreignIdentity.sessionId}/only-foreign.md`]);
59
63
  assert.deepEqual(addresses(await notes.list({ glob: "**/shared.md" })), all);
60
64
  assert.deepEqual(addresses(await notes.list({ glob: "@*/**/shared.md" })), all, "a wildcard head is not mistaken for an unknown reserved head");
61
65
  assert.deepEqual(addresses(await notes.list({ glob: `@sessions/${identity.sessionId}/**` })), [
@@ -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";
@@ -153,7 +154,7 @@ test("notes_list is most-recently-updated first across merged scopes", async ()
153
154
  // A same-path pair in two scopes keeps both rows; equal timestamps tie-break by scope name.
154
155
  put("human", "a.md", base + 10);
155
156
  assert.deepEqual((await files({})).filter((file) => file.address.endsWith("a.md")).map((file) => file.address), ["@human/a.md", "a.md"], "equal timestamps tie-break by full address");
156
- assert.deepEqual((await files({ glob: "*.md" })).map((file) => file.address), ["a.md", "b.md"], "a bare glob narrows to the session notebook");
157
+ assert.deepEqual((await files({ glob: "*.md" })).map((file) => file.address), ["@human/e.md", "@human/a.md", "a.md", "b.md", "@project/c.md"], "a slashless glob matches filenames across notebooks");
157
158
  });
158
159
  test("notes are real files that persist across sessions and round-trip Unicode", async () => {
159
160
  const original = manager();
@@ -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" });
@@ -10,7 +10,7 @@ import { createNotesStore } from "../src/notes/index.js";
10
10
  import { assertAddress } from "../src/notes/address.js";
11
11
  import { normalizeRemote, projectKey } from "../src/notes/project-namespace.js";
12
12
  import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../src/tools/notes.js";
13
- import { success } from "../src/tools/result.js";
13
+ import { success } from "../src/result.js";
14
14
  import { notesToolContext } from "../src/tools/notes-context.js";
15
15
  const toolContext = (identity) => notesToolContext(identity, "/work/current");
16
16
  function fixture(t) {
@@ -11,14 +11,15 @@ notesoup uses Pi's session branch as the durable source of truth. It does not ma
11
11
  | `plugins/claude/src/` | Claude Code helper, live transcript/head binding and threshold derivation | Claude only; wire decoding is shared under `src/history/claude.ts` |
12
12
  | `notes/identity.ts`, `notes/store.ts`, `notes/address.ts`, `notes/paths.ts` | Explicit `NotesIdentity`, filesystem notebooks, metadata, addressing and mutations | Node filesystem, no SDK or host environment identity |
13
13
  | `boot/snapshot.ts` | Load each of the five notebooks once; isolate filesystem errno failures | Explicit identity, captured time and optional scope loader |
14
- | `boot/render.ts`, `boot/text.ts` | Render identity, protocol, maps and recent-note metadata | Explicit snapshot and logical tool-name bindings; no I/O or clock |
14
+ | `boot/render.ts`, `boot/text.ts` | Render window data separately from fixed protocol/maps teaching; retain a combined boot for other hosts | Explicit snapshot and logical tool-name bindings; no I/O or clock |
15
15
  | `history/history.ts` | Project decoded events and pair tool calls/results, preserving supplied addresses | Decoded items and branch visibility; never inference messages |
16
- | `history/query.ts` | Bounded paging, `from` selection, literal matching, folding and chronological cross-session hit merging | Query projection only; no native SDK/session traversal |
16
+ | `history/query.ts` | Bounded paging, `from` selection, literal matching, folding and chronological cross-session hit merging | Caller-supplied budget check and page-too-large facts; no tool dependencies or native SDK/session traversal |
17
17
  | `history/corpus.ts`, `history/local.ts` | Session selector resolution and read-only local discovery, with explicit roots/env | Lazy projections and canonical identities; DSH contributes service-backed descriptors |
18
18
  | `history/pi.ts`, `history/claude.ts`, `history/codex.ts`, `history/codex-transcript.ts` | Persisted wire decoding, stable seq allocation and recorded branch/lineage evidence | Node/structural data only; no SDK or plugin imports; shared by corpus and native adapter entries |
19
19
  | `budget/constants.ts`, `budget/policy.ts`, `budget/text.ts` | Pure thresholds, unknown/clamped countdown and reminder text | Values supplied by the caller; no settings reads or scheduling |
20
20
  | `tools/notes-context.ts` | Host base cwd plus default identity, and one per-call cwd resolver | Shared current-project selection; no host SDK or sticky cwd mutation |
21
- | `tools/notes.ts`, `tools/history.ts`, `tools/schema.ts`, `tools/result.ts`, `tools/output.ts` | Schema-derived outcomes, note/history operations, bounded result selection and pure text rendering | Explicit tool context/projection; one bounded result feeds both text and structured output |
21
+ | `result.ts`, `text-match.ts` | Shared outcome/error primitives, literal-query validation/matching and prefix fitting | No tool-layer dependencies |
22
+ | `tools/notes.ts`, `tools/history.ts`, `tools/schema.ts`, `tools/result.ts`, `tools/output.ts` | Tool schemas, note/history operations, output limits/refusal copy, bounded result selection and pure text rendering | Explicit tool context/projection; one bounded result feeds both text and structured output |
22
23
  | `settings.ts` | The `notesoup` settings key, the plain-object test and the per-key global/project merge | Raw records only; each host names and validates the fields it consumes |
23
24
  | `dream/settings.ts` | Dreamer-pattern validation over the merged record | Parsed values only; no SDK or I/O |
24
25
  | `dream/` | Jail, crumpled-only physical deletion, locks, gates, Git audit, doctor, playbook and result/report logic | Independent filesystem/policy functions; no reverse import into Pi |
@@ -35,7 +36,7 @@ notesoup uses Pi's session branch as the durable source of truth. It does not ma
35
36
 
36
37
  In the notes vocabulary a **namespace** is a note partition: a `Scope` plus its storage directory (`session`, `@project`, `@human`, `@self`, `@model`, or a named `@projects`/`@agents`/`@models` member). Pi's `ToolNamespace` in `plugins/pi/tool-result.ts` is a tool-registration group (`notes`, `history`) and is unrelated; the word "home" is reserved for the store root directory.
37
38
 
38
- Dependencies flow from a plugin into the core, never back. Core code under `src/` cannot import an SDK or anything under `plugins/`, and a plugin cannot import another plugin's modules or a foreign host SDK; a plugin reaches note storage only through `src/notes/index.ts`. Each plugin owns its host's words: the Pi-only pre-reset hints, the `last_word` nudge and the `/empty <prompt>` close-out live in `plugins/pi/text.ts`, and the Claude wipe, missing-history and warning prose in `plugins/claude/src/text.ts`. `test/dependencies.test.ts` uses TypeScript resolution and AST traversal over every core source and each plugin tree, and tests rejecting indirect, aliased, dynamic and import-type edges. Shared external packages must be declared in the package manifest. `typebox` is declared as a peer and development dependency rather than imported through Pi's SDK.
39
+ Dependencies flow from a plugin into the core, never back. Core code under `src/` cannot import an SDK or anything under `plugins/`, and a plugin cannot import another plugin's modules or a foreign host SDK; a plugin reaches note storage only through `src/notes/index.ts`. History under `src/history/` cannot reach `src/tools/` directly or transitively, including type-only edges through shared modules. Each plugin owns its host's words: the Pi-only pre-reset hints, the `last_word` nudge and the `/empty <prompt>` close-out live in `plugins/pi/text.ts`, and the Claude wipe, missing-history and warning prose in `plugins/claude/src/text.ts`. `test/dependencies.test.ts` uses TypeScript resolution and AST traversal over every core source and each plugin tree, and tests rejecting indirect, aliased, dynamic and import-type edges. Shared external packages must be declared in the package manifest. `typebox` is declared as a peer and development dependency rather than imported through Pi's SDK.
39
40
 
40
41
  The configured extension is `plugins/pi/index.ts`, loaded straight from TypeScript — no bundling step, so git installs work without a build. Its `pi-ai/utils/estimate` dependency is vendored in `plugins/pi/estimate.ts` because Pi's root-package aliases misresolve that public subpath on source loads; host-owned SDK APIs stay external. The package root `.` exports the host-neutral core, `./pi` the Pi plugin, `/notes` the standalone library, and `./dsh` plus `./dsh/engine` the Cordis rows. The CLI is `dist/plugins/pi/dream/cli.js`, and the Claude Code plugin is the self-contained `plugins/claude/` directory. Old internal bags, `NotesContext`, root history helpers and the deep-entry export alias are removed. This breaks source/import paths, not storage: the on-disk notes layout is unchanged and host-independent — `pi/session/<sessionId>/` is a historical directory name every host still writes to, not a Pi adapter choice, and nothing migrates it. Note notebooks, metadata, session paths and raw history remain intact. There is no universal Harness, host-event emulator, registry, daemon or speculative second backend. No `src/window` exists because the current window responsibilities are genuinely native.
41
42
 
@@ -53,19 +54,21 @@ Boot and reminder deduplication inspect the current branch-local window. Reloadi
53
54
 
54
55
  Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. Every command settles and stops unless separate human input arrives during close-out; command text is supplied only to the closing window for its notes. Tool, hard-reserve and overflow resets never replay input already submitted to a model request. Only withheld command-close-out input or native queued new messages cross into the fresh window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
55
56
 
56
- Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. `/empty` and `/fresh-window` acknowledge a new request with `🥣 Dumping Brain`. Normal reset completion is silent; only forced reset completion produces `🥣 Brain forcibly emptied: overflow` through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `plugins/pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
57
+ Pi's `before_agent_start` mutates the public `systemPromptOptions.sections`: `notesoup_protocol` contains only the existing fixed protocol and maps/pin-policy teaching (with Pi's tool bindings, pre-reset hints and live named/nameless variant), alongside `notesoup_tools`. It never replaces the whole system prompt or reads notes. Pi persists/diffs these named sections and retains them across native reset checkpoints; unchanged teaching produces no duplicate patch. Development and verification use the published Pi 1.5.0 family: `pi-coding-agent`, `pi-agent-core`, `pi-ai` and `pi-tui` are pinned together at 1.5.0 in npm's manifest/lock, with optional host peers requiring `^1.5.0`. TypeBox schemas come directly from `typebox`, not Pi AI's removed schema re-exports.
58
+
59
+ The Pi boot remains a fixed snapshot for its window, stored as a hidden extension custom message and converted to a user-role model message. It contains only the window identity/tree and notes index/pinned bodies: no note, including `@human`, becomes a system instruction, and readonly semantics are unchanged. On resume, provider projection removes only a recognized old boot's consecutive top-level identity -> protocol -> maps -> notes prefix teaching; tags or quotations inside note bodies and ordinary messages remain untouched. Persisted boot/history bytes are never rewritten. Claude, Codex and dsh retain the combined renderer and their existing injection paths. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. Boot injection is silent, including startup, reload, and boot repair. `/empty` and `/fresh-window` acknowledge a new request with `🥣 Dumping Brain`. Normal reset completion is silent; only forced reset completion produces `🥣 Brain forcibly emptied: overflow` through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `plugins/pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
57
60
 
58
61
  The Pi history adapter supplies the selected raw session branch on demand without a cache. Its shared wire decoder allocates stable seq values from the session's append-order entry list, then selects current-branch-only visibility, so navigation cannot expose a sibling's history. Shared history pairs and queries those decoded events; it neither traverses SessionReader nor reconstructs inference messages. Optional `session` targeting uses a lazy `HistoryContext`/`HistoryCorpus`; filesystem-only Pi/Claude/Codex wire decoders are shared under `src/history/`, while DSH contributes descriptors through its native query service. Omitted `session` retains the original result/header/recipe shapes; explicit selectors carry canonical session identity throughout, and wildcard search merges hits chronologically without cross-session seq cursors. See [cross-session history](history-sessions.md). The public stream combines each tool call with its result at the call seq; paired result slots are not public event addresses, and unpaired results retain their own seq. Summaries and injected messages project as `context`. List pages chronologically with seq anchors and an explicit `from`. Tool executions retain structured call/result facts and any native nested-call metadata. A deterministic event document supplies both query-match positions and read windows. Nested calls have no independent seq and never imply that unrecorded child outputs are available.
59
62
 
60
63
  The boot notes index in `boot/snapshot.ts` is a closed snapshot: the current session, project, human, agent, and model notebooks are each loaded at most once while constructing a boot. `boot/snapshot.ts` takes explicit `NotesIdentity`, captured `openedAt` and an optional notebook loader; `boot/render.ts` renders that snapshot and explicit tool bindings without reading the filesystem or consulting the clock. Pi supplies its unchanged tool names. MAP bodies and pocket metadata are derived from the same snapshot, so a boot cannot mix two filesystem reads. Note storage and notebook traversal use `node:fs/promises`; same-file operations queue by absolute physical filename across store instances in this process, without promising symlink/case-alias or cross-process locking. Known persisted metadata is camelCase. Old snake_case keys are unrecognized extras, not interpreted or migrated; startup does not migrate notes. A missing notebook (`ENOENT`) is normal. A real read failure omits only that notebook's index, preserves healthy notebooks, adds a model-facing `notes_list` recovery notice, and notifies the human once for that window. Boot/reset construction captures session, agent, and model identity before awaiting the snapshot, then checks lifecycle generation, active window, enabled state, and abort status before sending or returning artifacts; stale completions cannot commit into a switched or shut-down session. Boot acquisition uses listing and never updates access metadata. Explicit note reads update `lastAccessed` and `accessCount`; no fallback state is created.
61
64
 
62
- Notes remain in their filesystem-backed notebooks, unchanged by session branch navigation. Tool reads expose metadata separately from body windows; search/read code-point offsets are body-relative and do not depend on frontmatter serialization or access-counter changes.
65
+ Notes remain in their filesystem-backed notebooks, unchanged by session branch navigation. Tool reads expose metadata separately from body windows; search/read code-point offsets are body-relative and do not depend on frontmatter serialization or access-counter changes. A single effective per-note policy resolves optional `pinned`, `budget`, and `readonly` frontmatter: root CHEATSHEET/MAP default pinned, every page defaults to a 2048-code-point advisory budget, and readonly defaults false (a soft lock, not security). Storage serializes pin admission per notebook (five live pins) before file mutation; boot uses that metadata to inject full pinned bodies with budget warnings, visibly naming omitted pins in manually over-cap notebooks.
63
66
 
64
67
  Every notes tool accepts an optional per-call `cwd`. The host adapter supplies a `NotesToolContext` containing its base cwd and default `NotesIdentity`; shared tool code resolves a relative override against that base, requires an existing directory, and derives one override `projectKey` through the existing project resolver. Storage, addresses, globs, receipts, and new session-note ownership all consume that same resolved identity. The override neither mutates the context nor changes `NotesIdentity.home`; the standalone store still receives explicit identities and has no cwd-discovery behavior. Dream markers survive resolution, so an override cannot widen dream write permission.
65
68
 
66
69
  Notes/history operations return schema-derived `Outcome<T>` values, not host `content` objects. One bounded candidate is measured against both its complete structured serialization and its text renderer. Pi registers the outcome schema and packages that same value as `structuredContent`, derives `isError` from it and puts rendered text in `content`. Claude uses the same operations and renderers. Neither adapter parses text or independently chooses a page. Read continuation hints follow Pi's native trailing-notice style and are not part of the addressed text. See [tool results](tool-results.md) for the breaking protocol and coordinate contract.
67
70
 
68
- The `/fresh-window` command only waits for idle when the session is busy with non-agent work; during model output it arms the close-out and steers the checkpoint prompt into the running turn. While enabled, `/compact` is cancelled with an actionable `/fresh-window` notice. Disabling notesoup stops new automatic resets, but an existing native checkpoint/marker still excludes earlier history and native compaction is still cancelled on that marked branch; a fresh root may use native Pi semantics. Threshold and warning accounting use active-window provider usage rather than pre-reset global usage. Budget policy and staged prompts are instance-owned, so concurrent sessions cannot share reserve/enablement or uncommitted drafts; default file-backed policy is cached per instance, while injected policy is resolved live on each decision and model/session transitions reset the diagnostic lifecycle.
71
+ The `/fresh-window` command only waits for idle when the session is busy with non-agent work; during model output it arms the close-out and steers the checkpoint prompt into the running turn. While enabled, `/compact` is cancelled with an actionable `/fresh-window` notice. Disabling notesoup stops new automatic resets, but an existing native checkpoint/marker still excludes earlier history and native compaction is still cancelled on that marked branch; a fresh root may use native Pi semantics. Threshold and warning accounting use active-window provider usage rather than pre-reset global usage. Pre-send hard-reserve checks estimate the complete projected transcript, including real system sections and tool declarations; native provider usage remains authoritative once available, and post-checkpoint unknown usage stays unknown. Budget policy and staged prompts are instance-owned, so concurrent sessions cannot share reserve/enablement or uncommitted drafts; default file-backed policy is cached per instance, while injected policy is resolved live on each decision and model/session transitions reset the diagnostic lifecycle.
69
72
 
70
73
  ## Evidence and limits
71
74