notesoup 0.58.2 โ†’ 0.59.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 (62) hide show
  1. package/README.md +2 -1
  2. package/dist/plugins/claude/src/helper.js +13 -0
  3. package/dist/plugins/claude/src/thresholds.js +17 -12
  4. package/dist/plugins/pi/budget.d.ts +3 -0
  5. package/dist/plugins/pi/budget.js +22 -11
  6. package/dist/plugins/pi/runtime.js +22 -6
  7. package/dist/src/boot/text.d.ts +1 -1
  8. package/dist/src/boot/text.js +5 -4
  9. package/dist/src/budget/cap.d.ts +2 -0
  10. package/dist/src/budget/cap.js +11 -0
  11. package/dist/src/notes/policy.d.ts +1 -1
  12. package/dist/src/notes/policy.js +4 -3
  13. package/dist/src/tools/notes.js +1 -1
  14. package/dist/test/agent-loop.test.js +13 -39
  15. package/dist/test/boot.integration.test.js +20 -18
  16. package/dist/test/budget-settings.integration.test.js +63 -14
  17. package/dist/test/claude-history.test.js +1 -2
  18. package/dist/test/claude-mod.test.js +96 -29
  19. package/dist/test/codex-history.test.js +9 -6
  20. package/dist/test/codex-plugin.test.js +4 -8
  21. package/dist/test/dream-skill.test.js +6 -10
  22. package/dist/test/dsh-cli.test.js +2 -3
  23. package/dist/test/dsh.test.js +1 -7
  24. package/dist/test/helpers/extension.js +3 -1
  25. package/dist/test/history-corpus.test.js +2 -3
  26. package/dist/test/history-prefilter.test.js +33 -40
  27. package/dist/test/history-summary-cache.test.js +1 -1
  28. package/dist/test/history.integration.test.js +11 -37
  29. package/dist/test/host-neutral.test.js +2 -2
  30. package/dist/test/marker.test.js +1 -2
  31. package/dist/test/model-facing-text.test.js +20 -187
  32. package/dist/test/note-policy.test.js +40 -22
  33. package/dist/test/notes-library.test.js +2 -2
  34. package/dist/test/notes.integration.test.js +36 -149
  35. package/dist/test/notes.test.js +13 -61
  36. package/dist/test/pi-render.test.js +23 -62
  37. package/dist/test/reset-lifecycle.test.js +4 -9
  38. package/docs/architecture.md +1 -1
  39. package/docs/claude-code-mod.md +5 -3
  40. package/docs/dsh.md +1 -1
  41. package/docs/notes-library.md +1 -1
  42. package/docs/reset-lifecycle.md +3 -1
  43. package/docs/tool-results.md +1 -1
  44. package/package.json +1 -1
  45. package/playbook.md +1 -1
  46. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  47. package/plugins/claude/dist/claude/helper.js +47 -17
  48. package/plugins/claude/hooks/register.ts +51 -5
  49. package/plugins/claude/playbook.md +1 -1
  50. package/plugins/claude/skills/dream/SKILL.md +1 -1
  51. package/plugins/claude/skills/memory/SKILL.md +1 -1
  52. package/plugins/claude/src/helper.ts +11 -0
  53. package/plugins/claude/src/thresholds.ts +18 -11
  54. package/plugins/codex/dist/codex/notesoup.js +10 -8
  55. package/plugins/pi/budget.ts +21 -11
  56. package/plugins/pi/runtime.ts +18 -6
  57. package/skills/dream/SKILL.md +1 -1
  58. package/skills/memory/SKILL.md +1 -1
  59. package/src/boot/text.ts +5 -4
  60. package/src/budget/cap.ts +9 -0
  61. package/src/notes/policy.ts +4 -3
  62. package/src/tools/notes.ts +1 -1
@@ -1,6 +1,5 @@
1
1
  import { notesIdentityFromPi } from "../plugins/pi/notes/adapter.js";
2
- import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
3
- import { DEFAULT_NOTE_BUDGET } from "../src/notes/policy.js";
2
+ import { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "../src/boot/text.js";
4
3
  import assert from "node:assert/strict";
5
4
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
5
  import fs from "node:fs/promises";
@@ -9,14 +8,13 @@ import { dirname, join } from "node:path";
9
8
  import test from "node:test";
10
9
  import { loadNotesSnapshot } from "../src/boot/snapshot.js";
11
10
  import { renderBootBlock } from "../src/boot/render.js";
12
- import { MAPS_BLOCK, NOTES_PROTOCOL_CLOSE_TAG, NOTES_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
13
- import { PI_PRE_RESET_HINTS } from "../plugins/pi/text.js";
14
11
  import { localIso } from "../src/notes/frontmatter.js";
12
+ import { createNotesStore } from "../src/notes/index.js";
15
13
  import { listNotes, physicalPath, scopeDir } from "./helpers/notes.js";
16
14
  import { MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
17
15
  import { notesUpdate } from "../src/tools/notes.js";
18
16
  import { notesToolContext } from "../src/tools/notes-context.js";
19
- import { assertWithinBudget, call, context, explicitBoot, makeExtension, manager, resultData, resultError, resultRead, runHandlers, } from "./helpers/extension.js";
17
+ import { assertWithinBudget, call, context, makeExtension, manager, resultData, resultError, resultRead, runHandlers, } from "./helpers/extension.js";
20
18
  import { installExtensionTestHooks } from "./helpers/extension-test-environment.js";
21
19
  const testEnvironment = installExtensionTestHooks("notesoup-integration");
22
20
  /** The model-facing text of one tool result. */
@@ -219,146 +217,30 @@ test("the filesystem notes loader treats an absent notebook as empty but surface
219
217
  writeFileSync(blockedHome, "not a directory");
220
218
  await assert.rejects(() => listNotes(ctx, { glob: "@human/**" }), (error) => error.code === "ENOTDIR", "a non-ENOENT directory failure is not swallowed as an empty notebook");
221
219
  });
222
- test("boot note acquisition is one closed snapshot and isolates one or all failed notebooks", async () => {
223
- const sm = manager();
224
- const ctx = context(sm);
225
- const updated = Date.now();
226
- const note = (scope, path, address, body) => ({
227
- address,
228
- scope,
229
- path,
230
- body,
231
- sizeBytes: Buffer.byteLength(body, "utf8"),
232
- meta: {
233
- scope,
234
- origin: "self",
235
- createdAt: updated,
236
- updatedAt: updated,
237
- lastAccessed: updated,
238
- accessCount: 0,
239
- },
240
- });
241
- const rows = new Map([
242
- ["session", [note("session", "MAP.md", "MAP.md", "SESSION_MAP_BODY"), note("session", "session.md", "session.md", "# Session note\n\nSESSION_POCKET_BODY")]],
243
- ["project", [note("project", "MAP.md", "@project/MAP.md", "PROJECT_MAP_BODY")]],
244
- ["human", [note("human", "MAP.md", "@human/MAP.md", "HUMAN_MAP_BODY"), note("human", "human.md", "@human/human.md", "# Human note\n\nHUMAN_POCKET_BODY")]],
245
- ["agent", [note("agent", "MAP.md", "@agents/root/MAP.md", "AGENT_MAP_BODY")]],
246
- ["model", [note("model", "model.md", "@models/default/model.md", "# Model note\n\nMODEL_POCKET_BODY")]],
247
- ]);
248
- const calls = new Map();
249
- const snapshot = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
250
- calls.set(scope, (calls.get(scope) ?? 0) + 1);
251
- return rows.get(scope) ?? [];
252
- });
253
- assert.deepEqual([...calls.entries()], [["session", 1], ["project", 1], ["human", 1], ["agent", 1], ["model", 1]], "each selected notebook is loaded exactly once");
254
- const renderData = {
255
- tools: DEFAULT_BOOT_TOOL_NAMES,
256
- agentName: "root",
257
- modelName: "default",
258
- tree: { trunk: "pcw:test", windows: [{ shortName: "root", isCurrent: false }, { shortName: "next", isCurrent: true }] },
259
- notes: snapshot,
260
- };
261
- const rendered = renderBootBlock(renderData);
262
- assert.equal(renderBootBlock(renderData), rendered, "rendering the same boot data twice is deterministic");
263
- assert.ok(rendered.includes("HUMAN_MAP_BODY") && rendered.includes("PROJECT_MAP_BODY") && rendered.includes("AGENT_MAP_BODY") && rendered.includes("SESSION_MAP_BODY"), "all notebook maps, including session, are pinned");
264
- assert.ok(rendered.includes("session.md") && rendered.includes("@human/human.md"), "the fresh page carries rows from every notebook");
265
- assert.equal(rendered.includes("SESSION_POCKET_BODY"), false, "fresh-page bodies stay excluded");
266
- assert.equal(rendered.includes("- MAP.md"), false, "a pinned session map does not take a feed seat");
267
- assert.match(rendered, / {2}Session note\n {2}session\.md ยท (?:just now|\d+s ago)/, "a feed entry is the note's own title over its locator");
268
- assert.equal(rendered.includes("UTF-8 bytes"), false, "fresh rows omit implementation-oriented byte counts");
269
- assert.ok(rendered.indexOf(NOTES_PROTOCOL_OPEN_TAG) < rendered.indexOf("YOUR NOTES"), "the protocol explains the notes before presenting them");
270
- assert.ok(rendered.indexOf(MAPS_BLOCK) < rendered.indexOf("YOUR NOTES"), "the MAP block sits between the protocol and the notes index");
271
- assert.ok(rendered.indexOf(NOTES_PROTOCOL_CLOSE_TAG) < rendered.indexOf(MAPS_BLOCK), "the MAP block follows the protocol block");
272
- assert.match(rendered, /@project โ€” this project\nโ”€+/, "shelves carry underlined headers");
273
- assert.ok(rendered.includes("recent"), "shelves label their fresh pages");
274
- assert.ok(rendered.indexOf("no @ โ€” this session") < rendered.indexOf("recent"), "the first shelf opens the index");
275
- const headings = ["no @ โ€” this session", "@project โ€” this project", "@self โ€” root only", "@model โ€” default only", "@human โ€” the human"];
276
- for (let i = 1; i < headings.length; i++)
277
- assert.ok(rendered.indexOf(headings[i - 1]) < rendered.indexOf(headings[i]), "shelves proceed from current hands to durable");
278
- const expanded = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
279
- if (scope === "project" || scope === "human" || scope === "agent" || scope === "model") {
280
- return Array.from({ length: 6 }, (_, i) => note(scope, `note-${i}.md`, `@${scope === "agent" ? "agents/root" : scope === "model" ? "models/default" : scope}/note-${i}.md`, `body ${i}`));
281
- }
282
- return rows.get(scope) ?? [];
283
- });
284
- const expandedText = renderBootBlock({ ...renderData, notes: expanded });
285
- const freshRows = expandedText.match(/^ {2}\S[^\n]* ยท (?:just now|\d+s ago)$/gm) ?? [];
286
- assert.equal(freshRows.length, 13, "each shelf keeps three of its own pages; the session shelf keeps its one");
287
- assert.ok(expandedText.includes("@project/note-2.md"), "the project shelf's third page");
288
- assert.equal(expandedText.includes("@project/note-3.md"), false, "the project shelf's fourth page stays shelved");
289
- assert.ok(expandedText.includes("@models/default/note-2.md"), "the model shelf also gets three");
290
- assert.equal(expandedText.includes("You find"), false, "the old pocket heading is gone");
291
- const empty = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), () => []);
292
- assert.match(renderBootBlock({ ...renderData, notes: empty }), /YOUR NOTES\nโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n\nNone yet\. A blank slate is a fine place to start โ€” just don't finish there\./);
293
- const crumpledNote = note("session", "crumpled.md", "crumpled.md", "SHOULD_NOT_SHOW");
294
- const mapAndUnicode = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => scope === "session" ? [
295
- note("session", "MAP.md", "MAP.md", "SESSION_MAP_BODY"),
296
- note("session", "unicode.md", "unicode.md", "๐Ÿ‘ๅญ—"),
297
- { ...crumpledNote, meta: { ...crumpledNote.meta, crumpledAt: localIso(updated) } },
298
- ] : []);
299
- const mapAndUnicodeText = renderBootBlock({ ...renderData, notes: mapAndUnicode });
300
- assert.match(mapAndUnicodeText, / {2}๐Ÿ‘ๅญ—\n {2}unicode\.md ยท (?:just now|\d+s ago)/, "a headingless note is announced by its first line");
301
- assert.ok(mapAndUnicodeText.includes("no @ โ€” this session\nโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n\nMAP.md\n\n SESSION_MAP_BODY\n\nrecent\n\n ๐Ÿ‘ๅญ—\n unicode.md ยท just now"), "the session shelf keeps its typography");
302
- assert.equal(mapAndUnicodeText.includes("crumpled.md"), false);
303
- assert.equal(/MAP\.md ยท/.test(mapAndUnicodeText), false, "maps never take feed seats");
304
- assert.equal(mapAndUnicodeText.includes("@human โ€” the human"), false, "empty shelves are omitted");
305
- const readFailure = (code) => Object.assign(new Error("scripted read failure"), { code });
306
- const oneFailed = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
307
- if (scope === "human")
308
- throw readFailure("EIO");
309
- return rows.get(scope) ?? [];
310
- });
311
- assert.deepEqual(oneFailed.unavailable.map((namespace) => namespace.label), ["@human"]);
312
- const oneFailedText = renderBootBlock({
313
- tools: DEFAULT_BOOT_TOOL_NAMES,
314
- agentName: "root",
315
- modelName: "default",
316
- tree: renderData.tree,
317
- notes: oneFailed,
318
- });
319
- assert.ok(oneFailedText.includes("PROJECT_MAP_BODY") && oneFailedText.includes("@human โ€” the human\nโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n\n This drawer wouldn't open. Try `notes_list` again."), "healthy notebooks and a per-section recovery notice survive one failure");
320
- assert.equal(oneFailedText.includes("HUMAN_POCKET_BODY"), false, "the failed notebook's index is omitted");
321
- assert.equal(oneFailedText.includes("Human note"), false, "the failed notebook takes no feed seats");
322
- const allFailed = await loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), (scope) => {
323
- throw readFailure(scope === "session" ? "EACCES" : "EIO");
324
- });
325
- assert.equal(allFailed.unavailable.length, 5);
326
- const allFailedText = renderBootBlock({
327
- tools: DEFAULT_BOOT_TOOL_NAMES,
328
- agentName: "root",
329
- modelName: "default",
330
- tree: renderData.tree,
331
- notes: allFailed,
332
- });
333
- assert.ok(allFailedText.includes("pcw:test") && allFailedText.includes("root") && allFailedText.includes("next"), "identity survives an all-notebook failure");
334
- assert.ok(allFailedText.includes("Your memory gets wiped when this window ends"), "protocol survives an all-notebook failure");
335
- assert.equal(allFailedText.includes("scripted read failure"), false, "the model-facing notice does not expose OS/error details");
336
- await assert.rejects(() => loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), () => { throw new TypeError("programmer failure"); }), (error) => error instanceof TypeError, "unrelated TypeError construction failures remain visible");
337
- await assert.rejects(() => loadNotesSnapshot(notesIdentityFromPi(ctx), Date.now(), () => { throw Object.assign(new Error("invalid argument"), { code: "ERR_INVALID_ARG_TYPE" }); }), (error) => error.code === "ERR_INVALID_ARG_TYPE", "Node ERR_* failures are not treated as filesystem errno failures");
338
- });
339
- test("the boot block gives awake agents the notes file layout", async () => {
340
- const session = manager();
341
- const rendered = await explicitBoot(context(session), "pcw:test:root", undefined);
342
- assert.equal(rendered.includes(process.env.NOTESOUP_HOME ?? ""), false, "the absolute notes home is never exposed");
343
- assert.match(rendered, /`<path>`, no @[\s\S]*`@project\/<path>`[\s\S]*`@human\/<path>`/);
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");
345
- });
346
- test("the boot binds its tools and injects an over-budget MAP whole with a warning", async () => {
347
- const session = manager();
348
- const captured = makeExtension(session);
349
- const ctx = context(session);
350
- await call(captured, "notes_write", { address: "MAP.md", content: "M".repeat(DEFAULT_NOTE_BUDGET + 10) }, ctx);
351
- await call(captured, "notes_write", { address: "CHEATSHEET.md", content: "REMEMBER_THIS_RULE" }, ctx);
352
- const rendered = await explicitBoot(ctx, "pcw:test:root", undefined);
353
- for (const tool of ["notes_*", "history_*", "get_context_remaining", "empty_brain"]) {
354
- assert.ok(rendered.includes(`\`${tool}\``), `${tool} is bound in the protocol`);
220
+ test("boot acquisition isolates filesystem failures but not programmer errors", async () => {
221
+ const identity = notesIdentityFromPi(context(manager()));
222
+ const notes = createNotesStore(identity);
223
+ await notes.write("@project/available", "AVAILABLE_NOTE");
224
+ const [available] = await notes.list();
225
+ assert.ok(available);
226
+ for (const failures of [["human"], ["session", "project", "human", "agent", "model"]]) {
227
+ const snapshot = await loadNotesSnapshot(identity, Date.now(), scope => {
228
+ if (failures.includes(scope))
229
+ throw Object.assign(new Error("private filesystem detail"), { code: "EIO" });
230
+ return scope === "project" ? [available] : [];
231
+ });
232
+ assert.deepEqual(snapshot.unavailable.map(namespace => namespace.scope), failures);
233
+ assert.deepEqual(snapshot.namespaces.get("project"), failures.length === 1 ? [available] : []);
234
+ const rendered = renderBootBlock({
235
+ tools: DEFAULT_BOOT_TOOL_NAMES, agentName: "root", modelName: "default",
236
+ tree: { trunk: "snapshot-test", windows: [{ shortName: "root", isCurrent: true }] }, notes: snapshot,
237
+ });
238
+ assert.ok(rendered.includes("snapshot-test"));
239
+ assert.ok(rendered.includes(renderProtocolBlock(DEFAULT_BOOT_TOOL_NAMES, "root")));
240
+ assert.equal(rendered.includes("private filesystem detail"), false);
355
241
  }
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
- 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
- assert.equal(/CHEATSHEET\.md ยท/.test(rendered), false, "the stored cheatsheet takes no recent seat");
360
- for (const retired of ["history_list", "history_read"]) {
361
- assert.equal(rendered.includes(retired), false, `${retired} no longer appears in the boot block`);
242
+ for (const error of [new TypeError("programmer failure"), Object.assign(new Error("invalid argument"), { code: "ERR_INVALID_ARG_TYPE" })]) {
243
+ await assert.rejects(() => loadNotesSnapshot(identity, Date.now(), () => { throw error; }), thrown => thrown === error);
362
244
  }
363
245
  });
364
246
  test("an over-budget note is delivered as a bounded prefix and resumed by next_offset_chars", async () => {
@@ -487,7 +369,10 @@ test("a large mutation keeps a receipt and budget warning while details.diff car
487
369
  assertWithinBudget(raw, "bulk edit receipt");
488
370
  const update = resultData(raw);
489
371
  assert.equal(update.change_kind, "body");
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");
372
+ assert.match(textOf(raw), /^updated bulk-edit\.md\b/);
373
+ assert.ok(update.warnings.length > 0);
374
+ for (const warning of update.warnings)
375
+ assert.ok(textOf(raw).includes(warning), "budget warnings remain visible");
491
376
  assert.match(raw.details?.diff ?? "", new RegExp(`\\+.*?${"b".repeat(300)}`), "details.diff carries the UI diff");
492
377
  const body = resultRead(await call(captured, "notes_read", { address: "bulk-edit.md", max_chars: 300 }, ctx)).content;
493
378
  assert.equal(body, "b".repeat(300), "every one of the 1500 replacements was applied");
@@ -537,12 +422,13 @@ test("an extra value beyond the verbatim budget is named in place, not dropped",
537
422
  const path = physicalPath("session", "many-extras.md", ctx);
538
423
  mkdirSync(dirname(path), { recursive: true });
539
424
  const stamp = localIso(Date.now());
540
- const keys = Array.from({ length: 10 }, (_, index) => `k${index}: "${"x".repeat(400)}"`).join("\n");
425
+ const count = Math.ceil(TOOL_OUTPUT_MAX_BYTES / 400) + 1;
426
+ const keys = Array.from({ length: count }, (_, index) => `k${index}: "${"x".repeat(400)}"`).join("\n");
541
427
  writeFileSync(path, `---\norigin: self\ncreatedAt: ${stamp}\nupdatedAt: ${stamp}\nlastAccessed: ${stamp}\naccessCount: 0\n${keys}\n---\n\nbody`);
542
428
  const metadata = resultData(await call(captured, "notes_read", { address: "many-extras.md" }, ctx)).metadata;
543
429
  assert.equal(metadata.extra.k0, "x".repeat(400), "the first extras are delivered verbatim");
544
- assert.equal(metadata.extra.k9, "[omitted: too large]", "an extra past the verbatim budget is named, not dropped");
545
- assert.equal(Object.keys(metadata.extra).length, 10, "every key is still accounted for");
430
+ assert.equal(metadata.extra[`k${count - 1}`], "[omitted: too large]", "an extra past the verbatim budget is named, not dropped");
431
+ assert.equal(Object.keys(metadata.extra).length, count, "every key is still accounted for");
546
432
  });
547
433
  test("an unexpected notes defect propagates with its own identity while real filesystem refusals stay structured", async () => {
548
434
  const session = manager();
@@ -577,7 +463,8 @@ test("a body that repeats one anchor thousands of times refuses with bounded, co
577
463
  const refusal = resultError(raw);
578
464
  assert.equal(refusal.code, "ambiguous_edit");
579
465
  assert.match(refusal.message, /edits\[0\]/, "the message names the failing edit index");
580
- assert.match(refusal.message, /5000 times \(lines 1, 2, 3, 4, 5, 6, 7, 8, and 4992 more\)/, "the message names a bounded sample and the exact total");
466
+ assert.match(refusal.message, /5000 times/, "the message names the exact total");
467
+ assert.ok(refusal.message.length < repeats, "the message summarizes rather than enumerating every line");
581
468
  assert.equal(resultRead(await call(captured, "notes_read", { address: "many.md", max_chars: 15 }, ctx)).content, "beta\n".repeat(3), "the refused edit changed nothing");
582
469
  const replaced = resultData(await call(captured, "notes_update", { address: "many.md", edits: [{ oldText: "beta", newText: "B" }], replace_all: true }, ctx));
583
470
  assertWithinBudget(await call(captured, "notes_read", { address: "many.md" }, ctx), "read after replace_all");
@@ -29,20 +29,11 @@ function assertReceiptIdentity(value, address, scope, ctx) {
29
29
  assert.equal(value.address, address);
30
30
  assert.equal(value.project_key, scope === "project" ? projectKey(ctx.cwd, process.env.NOTESOUP_HOME) : undefined);
31
31
  }
32
- test("exactly the five notes tools are registered; the legacy five are gone", () => {
32
+ test("tools register their namespaces and sequential note mutations", () => {
33
33
  const captured = makeExtension(manager());
34
- for (const name of ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"]) {
35
- assert.ok(captured.tools.get(name), `${name} is registered`);
36
- }
37
- for (const legacy of ["notes_write_file", "notes_append_to_file", "notes_read_file", "notes_search_contents", "notes_list_files"]) {
38
- assert.equal(captured.tools.get(legacy), undefined, `${legacy} is unregistered`);
39
- }
40
34
  assert.equal(captured.tools.get("notes_write")?.executionMode, "sequential");
41
35
  assert.equal(captured.tools.get("notes_update")?.executionMode, "sequential");
42
36
  assert.equal(captured.tools.get("notes_read")?.executionMode, undefined);
43
- });
44
- test("notes and history tools are grouped under their own namespaces", () => {
45
- const captured = makeExtension(manager());
46
37
  for (const name of ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"]) {
47
38
  assert.equal(captured.tools.get(name)?.namespace?.name, "notes", `${name} is in notes`);
48
39
  }
@@ -69,26 +60,20 @@ test("every notes tool declares a result schema that accepts its own structured
69
60
  assert.equal(Check(schema, result.structuredContent), true, `${name} structured payload matches its declared schema`);
70
61
  }
71
62
  });
72
- test("note schemas drop status/stale and expose crumpled listing", () => {
63
+ test("note schemas accept their operations, reject unknown fields, and expose crumpled listing", () => {
73
64
  const captured = makeExtension(manager());
74
- const schema = (name) => captured.tools.get(name).parameters;
75
- const write = schema("notes_write");
76
- assert.equal(Check(write, { address: "a.md", content: "x" }), true);
77
- assert.equal(Check(write, { address: "a.md", content: "x", stale: true }), false, "notes_write no longer accepts stale");
78
- assert.equal(Check(write, { address: "a.md", content: "x", crumpled: true }), false, "notes_write does not accept crumpled");
79
- const edit = schema("notes_update");
80
- assert.equal(Check(edit, { address: "a.md", crumpled: true }), true);
81
- assert.equal(Check(edit, { address: "a.md", stale: true }), false, "notes_update no longer accepts stale");
82
- assert.equal(Check(edit, { address: "a.md", status: "archived" }), false, "status is gone");
83
- for (const name of ["notes_list", "notes_search"]) {
84
- const base = name === "notes_search" ? { query: "x" } : {};
85
- assert.equal(Check(schema(name), { ...base, crumpled: true }), true, `${name} accepts crumpled`);
86
- assert.equal(Check(schema(name), { ...base, status: "active" }), false, `${name} rejects status`);
87
- // The retired names are unknown parameters, refused like any other: `additionalProperties: false`.
88
- for (const retired of [{ wastebasket: true }, { pattern: "**" }]) {
89
- assert.equal(Check(schema(name), { ...base, ...retired }), false, `${name} refuses the retired ${Object.keys(retired)[0]} as an unknown parameter`);
90
- }
65
+ for (const [name, params] of [
66
+ ["notes_write", { address: "a.md", content: "x" }],
67
+ ["notes_update", { address: "a.md", crumpled: true }],
68
+ ["notes_read", { address: "a.md" }],
69
+ ["notes_list", { crumpled: true }],
70
+ ["notes_search", { query: "x", crumpled: true }],
71
+ ]) {
72
+ const schema = captured.tools.get(name).parameters;
73
+ assert.equal(Check(schema, params), true, name);
74
+ assert.equal(Check(schema, { ...params, unsupported: true }), false, `${name} refuses unknown fields`);
91
75
  }
76
+ assert.equal(Check(captured.tools.get("notes_write").parameters, { address: "a.md", content: "x", crumpled: true }), false, "restoration belongs to notes_update");
92
77
  });
93
78
  test("Pi resolves a per-call relative cwd against the session cwd", async () => {
94
79
  freshRoot();
@@ -124,8 +109,6 @@ test("write lands a real markdown file with harness frontmatter and a pure body"
124
109
  assert.match(raw, new RegExp(`^${key}: ${value}$`, "m"), `frontmatter carries ${key}=${value}`);
125
110
  }
126
111
  assert.equal(/^scope:/m.test(raw), false, "scope is derived from the file notebook, never persisted");
127
- assert.equal(/^status:/m.test(raw), false, "status is gone from persisted notes");
128
- assert.equal(/^stale:/m.test(raw), false, "the boolean stale flag is gone from persisted notes");
129
112
  assert.equal(/^crumpledAt:/m.test(raw), false, "a fresh note is uncrumpled");
130
113
  for (const key of ["createdAt", "updatedAt", "lastAccessed"]) {
131
114
  assert.match(raw, new RegExp(`^${key}: \\d{4}-\\d{2}-\\d{2}T`, "m"), `frontmatter renders ${key} via localIso`);
@@ -413,19 +396,6 @@ test("notes receipts report resolved identity across scopes", async () => {
413
396
  for (const row of searched.files)
414
397
  assertReceiptIdentity(row, row.address, notes.find((note) => note.address === row.address).scope, ctx);
415
398
  });
416
- test("mutation receipts keep their existing shape outside named project notebooks", async () => {
417
- freshRoot();
418
- const session = manager();
419
- const captured = makeExtension(session);
420
- const ctx = context(session);
421
- const written = await call(captured, "notes_write", { address: "@project/decision", content: "body" }, ctx);
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", "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
- for (const [name, result] of [["notes_write", written], ["notes_update", updated]]) {
426
- assert.equal(Check(captured.tools.get(name).outputSchema, result.structuredContent), true, `${name} keeps its ordinary project receipt`);
427
- }
428
- });
429
399
  test("list and search merge scopes and carry addresses; the path jail rejects escapes", async () => {
430
400
  freshRoot();
431
401
  const session = manager();
@@ -483,24 +453,6 @@ test("a read offsets the body in code points, not bytes or frontmatter", async (
483
453
  assert.equal(start.next_offset_chars, 3);
484
454
  assert.equal(resultRead(await call(captured, "notes_read", { address: "emoji.md", offset_chars: 14 }, ctx)).text, "", "the exact end is an empty window, not a refusal");
485
455
  });
486
- test("a read keeps its body window verbatim under the new presentation", async () => {
487
- freshRoot();
488
- const session = manager();
489
- const captured = makeExtension(session);
490
- const ctx = context(session);
491
- await call(captured, "notes_write", { address: "present.md", content: "0123456789" }, ctx);
492
- const limited = await call(captured, "notes_read", { address: "present.md", max_chars: 4 }, ctx);
493
- const text = limited.content[0].type === "text" ? limited.content[0].text : "";
494
- assert.equal(text.includes("READ WINDOW"), false, "the old READ WINDOW block is gone");
495
- assert.equal(text.includes("chars: ["), false, "no parsed range block stands between the header and the body");
496
- assert.equal(text.endsWith("\n\n[truncated; continue at offset_chars=4]"), true, "a limit-stopped window names the resume cursor");
497
- const header = text.slice(0, text.indexOf("\n\n"));
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
- const whole = await call(captured, "notes_read", { address: "present.md" }, ctx);
500
- const wholeText = whole.content[0].type === "text" ? whole.content[0].text : "";
501
- assert.equal(wholeText.endsWith("\n\n0123456789"), true, "a complete window carries no continuation footer");
502
- assert.equal(wholeText.includes("more characters"), false);
503
- });
504
456
  test("@ addresses select one notebook, keep boundaries, and never fall back", async () => {
505
457
  const root = freshRoot();
506
458
  const session = manager();
@@ -25,76 +25,33 @@ function jsonResult(value, isError = false) {
25
25
  function lines(component, width = 80) {
26
26
  return component.render(width).map((line) => stripTerminalSequences(line).trimEnd()).join("\n");
27
27
  }
28
- test("notes_write collapsed: outcome, address and content size", () => {
29
- const result = toolResult(success({ address: "@self/grudge.md", outcome: "created" }));
30
- const component = notesWriteRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "@self/grudge.md", content: "hello" } });
31
- assert.equal(lines(component), "wrote @self/grudge.md ยท 5 chars");
32
- });
33
- test("notes_write expanded: the written content follows the header", () => {
34
- const result = toolResult(success({ address: "plan.md", outcome: "overwrote" }));
35
- const component = notesWriteRenderers.renderResult(result, { expanded: true }, flatTheme, { args: { address: "plan.md", content: "one\ntwo" } });
36
- assert.equal(lines(component), "wrote plan.md ยท overwrote ยท 7 chars\n\none\ntwo");
37
- });
38
- test("notes_update edited: collapsed peeks at the first added line", () => {
39
- const result = toolResult(success({ address: "a.md", change_kind: "body" }), { diff: " 1 old\n-2 gone\n+2 here" });
40
- const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md" } });
41
- assert.equal(lines(component), "edited a.md ยท + here");
42
- });
43
- test("notes_update crumple: the address is struck through", () => {
44
- const result = toolResult(success({ address: "@self/stale.md", change_kind: "metadata" }));
45
- const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "@self/stale.md", crumpled: true } });
46
- assert.equal(lines(component), "โœ‚ crumpled ~~@self/stale.md~~");
47
- });
48
- test("notes_update moved: both addresses stay on the line", () => {
49
- const result = toolResult(success({ address: "@self/new.md", change_kind: "moved", rename_from: "a.md" }));
50
- const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md", rename_to: "@self/new.md" } });
51
- assert.equal(lines(component), "renamed a.md โ†’ @self/new.md");
52
- });
53
- test("notes_update unchanged keeps quiet", () => {
54
- const result = toolResult(success({ address: "a.md", change_kind: "none" }));
55
- const component = notesUpdateRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md" } });
56
- assert.equal(lines(component), "unchanged a.md");
57
- });
58
- test("notes_read collapsed: size and a peek at the first line", () => {
59
- const result = toolResult(success({ address: "@project/MAP.md", metadata: { origin: "self", created_at: "x", updated_at: "y", extra: {} }, text: "# MAP\n\nbody", total_chars: 11, next_offset_chars: null }));
60
- const component = notesReadRenderers.renderResult(result, { expanded: false }, flatTheme);
61
- assert.equal(lines(component), "read @project/MAP.md ยท 11 chars โ€” # MAP");
62
- });
63
28
  test("notes_read expanded: truncation points at the next offset", () => {
64
29
  const result = toolResult(success({ address: "a.md", metadata: { origin: "self", created_at: "x", updated_at: "y", extra: {} }, text: "part", total_chars: 10, next_offset_chars: 4 }));
65
30
  const component = notesReadRenderers.renderResult(result, { expanded: true }, flatTheme);
66
- assert.equal(lines(component), "read a.md ยท 10 chars ยท truncated โ€” part\n\npart\nโ€ฆ continue at offset_chars=4");
31
+ const text = lines(component);
32
+ assert.ok(text.includes("a.md") && text.includes("part"));
33
+ assert.ok(text.includes("offset_chars=4"), "a truncated read names its resume cursor");
67
34
  });
68
35
  test("refusals render as one error line with the code", () => {
69
36
  const result = toolResult({ ok: false, error: { code: "not_found", message: "No note at x.md." } });
70
37
  const component = notesReadRenderers.renderResult(result, { expanded: false }, flatTheme);
71
- assert.equal(lines(component), "not_found: No note at x.md.");
38
+ const text = lines(component);
39
+ assert.ok(text.includes("not_found") && text.includes("No note at x.md."));
40
+ assert.equal(text.split("\n").length, 1);
72
41
  });
73
42
  test("results without a structured payload fall back to the receipt line", () => {
74
43
  const result = { content: [{ type: "text", text: "created a.md" }], isError: false, details: undefined };
75
44
  const component = notesWriteRenderers.renderResult(result, { expanded: false }, flatTheme, { args: { address: "a.md", content: "x" } });
76
45
  assert.equal(lines(component), "created a.md");
77
46
  });
78
- test("empty_brain: divider with the last word, refusals in one line", () => {
47
+ test("empty_brain preserves its handoff and refusal reason", () => {
79
48
  initTheme();
80
49
  const ok = emptyBrainRenderers.renderResult(jsonResult({ status: "rollover_requested" }), { expanded: false }, flatTheme, { args: { last_word: "cake was worth it" } });
81
50
  const rendered = lines(ok, 40).split("\n");
82
- assert.match(rendered[0] ?? "", /^โ”€โ”€ โœ‚ brain emptied โ”€+$/);
51
+ assert.ok(rendered[0]?.length, "the reset has a visible header");
83
52
  assert.equal(rendered[1], "โ€œcake was worth itโ€");
84
53
  const refused = emptyBrainRenderers.renderResult(jsonResult({ error: "notesoup is off" }, true), { expanded: false }, flatTheme, { args: {} });
85
- assert.equal(lines(refused), "โœ‚ brain refused to empty โ€” notesoup is off");
86
- const pending = emptyBrainRenderers.renderResult(jsonResult({ status: "rollover_already_pending" }), { expanded: false }, flatTheme, { args: {} });
87
- assert.equal(lines(pending), "โœ‚ brain already being emptied");
88
- });
89
- test("empty_brain wraps a long last word inside the host's padded tool box", () => {
90
- const lastWord = "x".repeat(262);
91
- const component = emptyBrainRenderers.renderResult(jsonResult({ status: "rollover_requested" }), { expanded: false }, flatTheme, { args: { last_word: lastWord } });
92
- const box = new Box(1, 0);
93
- box.addChild(component);
94
- const rendered = box.render(163);
95
- assert.ok(rendered.every((line) => visibleWidth(line) <= 163), "tool output must fit the terminal, including box padding");
96
- assert.ok(rendered.length > 2, "the handoff should wrap rather than be truncated");
97
- assert.equal(rendered.slice(1).map((line) => stripTerminalSequences(line).trim()).join(""), `โ€œ${lastWord}โ€`);
54
+ assert.ok(lines(refused).includes("notesoup is off"), "the refusal reason survives rendering");
98
55
  });
99
56
  test("empty_brain wraps styled Unicode and multiline handoffs when resized", () => {
100
57
  const styledTheme = {
@@ -104,10 +61,12 @@ test("empty_brain wraps styled Unicode and multiline handoffs when resized", ()
104
61
  };
105
62
  const lastWord = `${"็•Œ๐Ÿฅฃe\u0301".repeat(30)}\nnext step`;
106
63
  const component = emptyBrainRenderers.renderResult(jsonResult({ status: "rollover_requested" }), { expanded: false }, styledTheme, { args: { last_word: lastWord } });
64
+ const box = new Box(1, 0);
65
+ box.addChild(component);
107
66
  for (const width of [80, 12, 40]) {
108
- const rendered = component.render(width);
67
+ const rendered = box.render(width);
109
68
  assert.ok(rendered.every((line) => visibleWidth(line) <= width), `styled output must fit width ${width}`);
110
- assert.equal(rendered.slice(1).map((line) => stripTerminalSequences(line).trimEnd()).join(""), `โ€œ${lastWord.replace("\n", "")}โ€`);
69
+ assert.equal(rendered.slice(1).map((line) => stripTerminalSequences(line).trim()).join(""), `โ€œ${lastWord.replace("\n", "")}โ€`);
111
70
  }
112
71
  });
113
72
  test("empty_brain keeps the divider and handoff within very narrow widths", () => {
@@ -122,21 +81,21 @@ test("real policy receipts keep policy and budget warnings visible in collapsed
122
81
  const home = mkdtempSync(join(tmpdir(), "policy-render-"));
123
82
  t.after(() => rmSync(home, { recursive: true, force: true }));
124
83
  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 };
84
+ const writeArgs = { address: "custom", content: "๐Ÿ˜€".repeat(3), budget: 2, pinned: true, readonly: false };
126
85
  const written = toolResult(await notesWrite.execute(writeArgs, context));
127
- const updateArgs = { address: "custom", readonly: true, edits: [{ oldText: "๐Ÿ˜€".repeat(2049), newText: "๐Ÿ˜€".repeat(2050) }] };
86
+ const updateArgs = { address: "custom", readonly: true, edits: [{ oldText: "๐Ÿ˜€".repeat(3), newText: "๐Ÿ˜€".repeat(4) }] };
128
87
  const updated = toolResult(await notesUpdate.execute(updateArgs, context));
129
88
  const read = toolResult(await notesRead.execute({ address: "custom", max_chars: 10 }, context));
130
89
  for (const expanded of [false, true]) {
131
90
  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 },
91
+ { component: notesWriteRenderers.renderResult(written, { expanded }, flatTheme, { args: writeArgs }), locked: false, count: 3 },
92
+ { component: notesUpdateRenderers.renderResult(updated, { expanded }, flatTheme, { args: updateArgs }), locked: true, count: 4 },
93
+ { component: notesReadRenderers.renderResult(read, { expanded }, flatTheme), locked: true, count: 4 },
135
94
  ];
136
95
  for (const { component, locked, count } of views) {
137
96
  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}`);
97
+ assert.ok(text.includes(`pinned true | budget 2 | readonly ${locked}`));
98
+ assert.ok(text.includes(`Warning: note body is ${count} Unicode code points, over budget 2`), `warning must not be clipped or hidden when expanded=${expanded}`);
140
99
  }
141
100
  }
142
101
  });
@@ -144,5 +103,7 @@ test("notes_update expanded diff goes through the host's diff renderer", () => {
144
103
  initTheme();
145
104
  const result = toolResult(success({ address: "a.md", change_kind: "body" }), { diff: " 1 old\n-2 gone\n+2 here" });
146
105
  const component = notesUpdateRenderers.renderResult(result, { expanded: true }, flatTheme, { args: { address: "a.md" } });
147
- assert.equal(lines(component), "edited a.md ยท + here\n\n 1 old\n-2 gone\n+2 here");
106
+ const text = lines(component);
107
+ assert.ok(text.includes("a.md"));
108
+ assert.ok(text.includes(" 1 old\n-2 gone\n+2 here"), "expanded updates carry the full host-rendered diff");
148
109
  });
@@ -9,7 +9,7 @@ import notesoup from "../plugins/pi/extension.js";
9
9
  import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE } from "../plugins/pi/entries.js";
10
10
  import { MANUAL_WIPE_TYPE } from "../plugins/pi/entries.js";
11
11
  import { assertBootHistory, toolContext } from "./helpers/extension.js";
12
- import { COUNTDOWN_LINE, FORCED_CONTINUATIONS, NORMAL_CONTINUATIONS } from "../src/budget/text.js";
12
+ import { FORCED_CONTINUATIONS, NORMAL_CONTINUATIONS } from "../src/budget/text.js";
13
13
  import { commandWarningContent } from "../plugins/pi/text.js";
14
14
  import { historyFromSession, nextHistorySeq } from "../plugins/pi/history.js";
15
15
  import { buildResetDrafts, inspectResetTail, LAST_WORD_PREFIX, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "../plugins/pi/reset/artifacts.js";
@@ -273,8 +273,6 @@ test("manual /empty with a prompt shows the human's command line in the close-ou
273
273
  const promptIndex = content.indexOf(promptLine);
274
274
  assert.ok(promptIndex >= 0, "the human's raw command line reaches the closing model");
275
275
  assert.ok(promptIndex > content.indexOf("</notesoup:budget_notice>"), "command context is outside the notice");
276
- assert.ok(content.includes("Then call `empty_brain`. Nothing in between.\n" + COUNTDOWN_LINE), "the countdown immediately follows the reset call");
277
- assert.equal(content.split(COUNTDOWN_LINE).length - 1, 1, "the notice carries the countdown once");
278
276
  // Command text is close-out context only.
279
277
  const settle = resultEntries(await h.emit("agent_before_settle", {
280
278
  type: "agent_before_settle",
@@ -918,10 +916,8 @@ test("empty_brain trims the last word, refuses an oversized one, and a blank per
918
916
  over.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
919
917
  const refused = await over.callTool("empty_brain", { last_word: "x".repeat(MAX_LAST_WORD_CHARS + 1) });
920
918
  assert.equal(refused.isError, true, "an oversized note fails the tool call so the host flags it");
921
- assert.match(JSON.stringify(refused), /error/, "an oversized note is refused, not truncated");
922
- assert.match(JSON.stringify(refused), new RegExp(`${MAX_LAST_WORD_CHARS + 1} characters`), "the refusal names the actual size and the limit");
923
919
  const refusedAstral = await over.callTool("empty_brain", { last_word: "\u{1F41F}".repeat(MAX_LAST_WORD_CHARS + 1) });
924
- assert.match(JSON.stringify(refusedAstral), new RegExp(`${MAX_LAST_WORD_CHARS + 1} characters`), "the guard counts code points, not UTF-16 units");
920
+ assert.equal(refusedAstral.isError, true, "the guard counts code points, not UTF-16 units");
925
921
  const untouched = resultEntries(await over.emit("turn_end", fakeBoundaryEvent()));
926
922
  assert.equal(untouched.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE).length, 0, "a refused call requests no reset");
927
923
  const h = harness();
@@ -930,11 +926,10 @@ test("empty_brain trims the last word, refuses an oversized one, and a blank per
930
926
  const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
931
927
  assert.equal(boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === RESET_LAST_WORD_TYPE).length, 0, "a blank last word persists no entry");
932
928
  });
933
- test("empty_brain accepts a 500-code-point sticky note without truncation", async () => {
934
- assert.equal(MAX_LAST_WORD_CHARS, 500);
929
+ test("empty_brain accepts a full-length sticky note without truncation", async () => {
935
930
  const h = harness();
936
931
  h.sessionManager.appendMessage({ role: "user", content: [{ type: "text", text: "before reset" }], timestamp: Date.now() });
937
- const sticky = "๐ŸŸ".repeat(500);
932
+ const sticky = "๐ŸŸ".repeat(MAX_LAST_WORD_CHARS);
938
933
  const accepted = await h.callTool("empty_brain", { last_word: ` ${sticky} ` });
939
934
  assert.notEqual(accepted.isError, true);
940
935
  const boundary = resultEntries(await h.emit("turn_end", fakeBoundaryEvent()));
@@ -62,7 +62,7 @@ The Pi history adapter supplies the selected raw session branch on demand withou
62
62
 
63
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.
64
64
 
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.
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, ordinary pages default to a 4096-code-point advisory budget (2048 for root CHEATSHEET/MAP), 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.
66
66
 
67
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.
68
68
 
@@ -2,19 +2,21 @@
2
2
 
3
3
  The package also ships `plugins/claude/`, an early-access Claude Code Mod that registers five notes tools as `mcp__notesoup__notes_*`, two history tools as `mcp__notesoup__history_*`, and `mcp__notesoup__empty_brain` and attaches one host-scoped notes boot block through Claude's conversation-scoped `prompt.context` event; Claude persists it across resume and reload. The sandboxed hooks module delegates filesystem and shared-domain work to the plugin-local `plugins/claude/dist/claude/helper.js` through Claude's bounded `$.process.run` capability.
4
4
 
5
- There is no independent proactive automatic clear line: crossing a measured threshold, `session.measure`, or completing an unrequested turn never clears context. `turn.complete` resets only an explicit pending request from `empty_brain`, `/empty`, or `/fresh-window`. Budget warning timing is unchanged and is derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reaches the sandboxed hooks module through the helper's `limits` operation:
5
+ Warning and automatic clear use one budget policy. The existing warning and reset points are derived from Claude's own auto-compact threshold instead of a fixed percent, in `plugins/claude/src/thresholds.ts`, and reach the sandboxed hooks module through the helper's `limits` operation. At the hard point, the next main `turn.step` ends the old turn after its whole tool batch; a successful main `turn.complete` also checks the point when no request is already pending. Both enter the existing non-held reset worker, without a separate cap-specific trigger. Measurement alone never clears context, child events cannot reset the main brain, and aborted/error/refusal turns do not commit a budget reset. The policy resolves its native point as follows:
6
6
 
7
7
  1. `$.session.usage({breakdown:"summary"}).context.breakdown.autoCompactThreshold` when it is a positive number, with `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` applied the way Claude applies it (it can only lower the point);
8
8
  2. otherwise computed from `$.session.usage().context.window` plus `CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `modelSettings.<model>.autoCompactWindow` and `autoCompactWindow` (the smallest configured window wins, capped at the model window), with Claude's 20000-token output reserve and 13000-token summary buffer; `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` lowers this fallback point by the same formula. With auto-compaction off, the percent override is ignored;
9
9
  3. otherwise the percent fallback, which assumes a classic 200K capacity, applies the same configured-window caps and token derivation, then converts the points to percentages.
10
10
 
11
- The warning remains `resetMarginTokens` (default 8192) plus `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below that point. Resolved points are reused only while the current model, threshold inputs and settings match; changing context fill alone does not invalidate them. The internal reset-derived intermediate is only warning math, not a clear trigger. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same margins still apply. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the budget warning. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, suppresses budget warnings and explicit resets, and makes `/fresh-window` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored. Setting `NOTESOUP_DISABLED` (presence-style, the same convention as `DISABLE_COMPACT`) turns the whole mod off: `session.start` registers no tools or commands and logs once, every event passes through untouched, and native compaction behaves as if the mod were absent.
11
+ The hard clear point is `resetMarginTokens` (default 8192) below the native point; the warning is another `warningRunwayTokens` (default `WARNING_RUNWAY_TOKENS`, 16384) below that. Resolved points are reused only while the current model, cap, threshold inputs and settings match; changing context fill alone does not invalidate them. With automatic compaction off (`autoCompactEnabled: false` in the merged settings, or `DISABLE_AUTO_COMPACT=1`) the point becomes the effective window minus the output reserve, so the same warning margins still apply, but automatic notesoup clears are disabled too. Explicit resets remain available. Every undocumented field is type-guarded and degrades to the next source; an unresolvable point, or missing usage, logs once and skips the budget warning. `DISABLE_COMPACT=1` is detected at `session.start`, logs once, suppresses budget warnings and explicit resets, and makes `/fresh-window` report that it cannot run. The margins are read from the `notesoup` object of Claude's merged `$.settings.read()` (`resetMarginTokens`, `warningRunwayTokens`); any other value is ignored. Setting `NOTESOUP_DISABLED` (presence-style, the same convention as `DISABLE_COMPACT`) turns the whole mod off: `session.start` registers no tools or commands and logs once, every event passes through untouched, and native compaction behaves as if the mod were absent.
12
+
13
+ `/notesoup cap 100k` supplies a runtime-only capacity ceiling, clamped to the smaller model/configured window before the same reserves and margins are deducted. A reported native threshold can only be lowered, never raised. `/notesoup cap` (or bare `/notesoup`) shows the cap; `/notesoup cap off` restores the uncapped policy. Whole tokens and decimal `k`/`m` suffixes are accepted, with caps too small for reserves refused. The cap survives notesoup rollover and model changes but is cleared on plugin reload, session end or session identity change. It does not call `/autocompact`, alter the model, or write settings/environment variables. An already pending reset keeps its continuation/STOP policy when the cap changes.
12
14
 
13
15
  Once per window, when the measured context crosses the warning point, main-agent tool results or prompt submission carry exactly the same budget warning as Pi, ending with `empty_brain` and the countdown. Delivery is consumed only when the downstream chain accepts the warning. The warned flag resets with the window ordinal. Its own `session.compact` hook answers native compaction in the main conversation instead of letting it summarize: an automatic compaction (threshold or prompt-too-long) becomes the freshly built notes boot followed by one randomly selected handoff paragraph (normal only when the model called `empty_brain`, otherwise forced), selected once for the new window and reused on retry โ€” the same boot-then-handoff order as Pi โ€” while user `/compact` and precompute are vetoed with a one-line notice. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block binds the shared reset sentence to `mcp__notesoup__empty_brain`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. A failed boot build falls back to Claude's own summary, which invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
14
16
 
15
17
  The reset flow has three separate lifetimes. `ResetFlow.request` lasts until successful reset or cancellation; it owns the first valid tool call's sticky note and continuation policy. `ResetState.commit` lasts for one native command attempt and tracks proof that Claude kept the boot. The per-turn cutoff can outlive the request when native auto compaction consumes it before the next step. Successful explicit reset and automatic reset share the same window/boot bookkeeping. A failed compaction retains the request for retry; an aborted, failed, or refused main turn cancels it. Session changes discard the flow and invalidate asynchronous work by generation.
16
18
 
17
- `empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
19
+ `empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. The automatic hard point uses the same cutoff and commit path; a budget reset uses the forced handoff pool and continues once only after a confirmed commit, unless manual STOP or natural input takes over. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
18
20
 
19
21
  Accepted natural input owns its continuation. Input received within the running turn, including input accepted before the first tool latch, releases the cutoff at the next step for the whole subsequent tool workflow. Input not yet delivered to a model request prevents reset work from starting. A separately queued natural turn also runs normally. No input is replayed. Native auto compaction consumes a pending request without resetting twice, while preserving its armed cutoff until turn completion or natural-input delivery; further auto compaction does not disarm it. Once that reset has completed and natural input releases its cutoff, a new `empty_brain` owns its own sticky and `terminate` policy. A consumed request's STOP does not carry into the new request.
20
22