notesoup 0.58.2 → 0.58.3

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 (47) hide show
  1. package/README.md +1 -1
  2. package/dist/src/boot/text.d.ts +1 -1
  3. package/dist/src/boot/text.js +5 -4
  4. package/dist/src/notes/policy.d.ts +1 -1
  5. package/dist/src/notes/policy.js +4 -3
  6. package/dist/src/tools/notes.js +1 -1
  7. package/dist/test/agent-loop.test.js +13 -39
  8. package/dist/test/boot.integration.test.js +20 -18
  9. package/dist/test/budget-settings.integration.test.js +18 -13
  10. package/dist/test/claude-history.test.js +1 -2
  11. package/dist/test/claude-mod.test.js +16 -8
  12. package/dist/test/codex-history.test.js +9 -6
  13. package/dist/test/codex-plugin.test.js +4 -8
  14. package/dist/test/dream-skill.test.js +6 -10
  15. package/dist/test/dsh-cli.test.js +2 -3
  16. package/dist/test/dsh.test.js +1 -7
  17. package/dist/test/helpers/extension.js +3 -1
  18. package/dist/test/history-corpus.test.js +2 -3
  19. package/dist/test/history-prefilter.test.js +33 -40
  20. package/dist/test/history-summary-cache.test.js +1 -1
  21. package/dist/test/history.integration.test.js +11 -37
  22. package/dist/test/host-neutral.test.js +2 -2
  23. package/dist/test/marker.test.js +1 -2
  24. package/dist/test/model-facing-text.test.js +20 -187
  25. package/dist/test/note-policy.test.js +40 -22
  26. package/dist/test/notes-library.test.js +2 -2
  27. package/dist/test/notes.integration.test.js +36 -149
  28. package/dist/test/notes.test.js +13 -61
  29. package/dist/test/pi-render.test.js +23 -62
  30. package/dist/test/reset-lifecycle.test.js +4 -9
  31. package/docs/architecture.md +1 -1
  32. package/docs/dsh.md +1 -1
  33. package/docs/notes-library.md +1 -1
  34. package/docs/tool-results.md +1 -1
  35. package/package.json +1 -1
  36. package/playbook.md +1 -1
  37. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  38. package/plugins/claude/dist/claude/helper.js +10 -8
  39. package/plugins/claude/playbook.md +1 -1
  40. package/plugins/claude/skills/dream/SKILL.md +1 -1
  41. package/plugins/claude/skills/memory/SKILL.md +1 -1
  42. package/plugins/codex/dist/codex/notesoup.js +10 -8
  43. package/skills/dream/SKILL.md +1 -1
  44. package/skills/memory/SKILL.md +1 -1
  45. package/src/boot/text.ts +5 -4
  46. package/src/notes/policy.ts +4 -3
  47. 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
 
package/docs/dsh.md CHANGED
@@ -47,7 +47,7 @@ The reminder and close-out warning go through `agent.steer`. Close-out remains a
47
47
  | dsh versions | Tested against **0.2.1-alpha.2**. Capability checks do not establish wire or persistence compatibility with every newer preview. Run the scripted tests before upgrading. |
48
48
  | Model calls per reset | **0** auxiliary model calls. The agent's note-writing turns and fresh-window continuation still make ordinary calls. |
49
49
  | Retention | Surface node **0**, one boot/continuation checkpoint, and subsequent messages. An unfinished tool batch postpones reset; no partial tool pairs are discarded. |
50
- | Boot bounds | Up to **5 live pins** and **3 recent notes per notebook**, from the shared policy/renderer. Root CHEATSHEET/MAP default pinned; explicit `pinned:false` overrides. All pages default to a **2048-code-point advisory budget**, adjustable per note. Pinned bodies arrive **whole**, with over-budget warnings instead of truncation; manually over-cap pins are omitted with a visible address list. |
50
+ | Boot bounds | Up to **5 live pins** and **3 recent notes per notebook**, from the shared policy/renderer. Root CHEATSHEET/MAP default pinned; explicit `pinned:false` overrides. Ordinary pages default to a **4096-code-point advisory budget**; root CHEATSHEET/MAP default to **2048**, adjustable per note. Pinned bodies arrive **whole**, with over-budget warnings instead of truncation; manually over-cap pins are omitted with a visible address list. |
51
51
  | Tool output | Shared **32 KiB** bounds; use `next_offset_chars`, history cursors, or narrower filters. There is no unbounded hidden result. |
52
52
  | Warning timing | Steering enters the next step; a large current response/tool batch can spend the runway. The hard reserve protects the next balanced boundary, not an in-flight provider call. |
53
53
  | Unknown capacity | Countdown is **null** and automatic reserve checks skip. Add `models[].contextWindow` to `llm-deepseek`; explicit resets still work. |
@@ -53,7 +53,7 @@ Addresses are a relative path (a current-session note), `@project/`, `@human/`,
53
53
 
54
54
  `effectiveNotePolicy(meta, path)` returns `{ pinned, budget, readonly }` for a notebook-relative Markdown path (`MAP.md`, not an `@` address). This is the shared default resolver used by storage, tools and boot:
55
55
 
56
- - All pages have a default budget of **2048 Unicode code points**, adjustable to any positive safe integer. `warnings` on write/update/rename results report body overflow but do not reject it. Astral characters count once. The separate serialized-file byte limit still applies.
56
+ - Ordinary pages have a default budget of **4096 Unicode code points**; root `CHEATSHEET.md` and `MAP.md` default to **2048**, adjustable to any positive safe integer. `warnings` on write/update/rename results report body overflow but do not reject it. Astral characters count once. The separate serialized-file byte limit still applies.
57
57
  - Only root `CHEATSHEET.md` and `MAP.md` default to pinned; all other paths, including nested files with those names, default false. Explicit false overrides the default. Raw `meta` keeps absent policy fields absent, so implicit defaults are re-evaluated at a move's destination; explicitly set values travel with the note.
58
58
  - Every physical notebook allows **5 live pins**, including existing default pages. Crumpled pins don't count. New pinning, writes that restore notes, explicit restores, and moves/renames all check admission and refuse with `pin_limit` before mutation if they would add a sixth pin. Same-notebook moves of an already-live pin don't consume another slot. Existing over-cap notes can still be edited, unpinned or crumpled. Boot defensively selects at most five pins, default-page-first then path order, visibly naming omitted pins in a manually over-cap notebook. Pinned bodies are injected whole, with budget warnings rather than truncation.
59
59
  - `readonly: true` is a **soft lock**, not an authorization/security boundary. Existing locked notes refuse changes, overwrite, crumple/restore, rename/move, and dream deletion with `readonly`. Explicit `readonly: false` permits a metadata-only unlock or unlock plus the requested mutation in one call. A new/unlocked note may be written and locked together. Replacing a locked crumpled move target also requires explicit false. Reads/access counters still write, and filesystem edits can bypass the lock.
@@ -69,7 +69,7 @@ One selection determines the structured result and its text. Both complete repre
69
69
 
70
70
  `after_seq` is a strict lower bound; `after_seq: 0` starts from the beginning. History pages carry boolean `has_older` and `has_newer` flags. For single-session pages, use the first item’s `seq` as `before_seq` to page older, and the last item’s `seq` as `after_seq` to page newer; include its `session` when present. Wildcard pages instead report more results and suggest narrowing by time, query, roles or session pattern; an overview with unvisited sessions may have more. The single-session rendered newer footer gives `→ newer: {"after_seq":...}` with an optional session. `from` picks which end of a bounded range `limit` counts from: it defaults to `oldest` when `after_seq` is set, and `newest` otherwise. Explicit `from` wins. `since`/`until` narrow that range by event `created_at`, and only a single-session call without roles or a non-empty query folds tool/context runs. Omitted queries, empty strings and empty lists all disable search filtering; empty entries in a query list are ignored. Without a query, notes search returns scoped notes with empty `matches`, not every body line. Notes listings/search are snapshots with a `more` count and can be narrowed by `glob`; they are not falsely advertised as paginated. A read can stop anywhere in the event document, including inside serialized arguments; concatenate its verbatim text slices before parsing any arguments. There is no separately truncated arguments object.
71
71
 
72
- `notes_write` and `notes_update` accept optional `pinned`, `budget`, and `readonly` policy fields. Their receipts, list/search rows, and read `metadata` expose the effective `pinned`, `budget`, and `readonly` values as structured fields **and visible text**. Successes also carry a `warnings` array (per file for list/search), rendered visibly when a body exceeds its budget: the default is 2048 Unicode code points for every page, adjustable per note. Overflow saves successfully; boot injects full pinned bodies instead of cutting them. Pi's custom write/update/read renderers show policy and warnings even when collapsed, outside the expandable body/diff and clipped summary. A readonly note refuses mutations with `readonly` until explicitly unlocked with `readonly:false`; this is a soft lock, not security. Pin admission refuses a sixth live pin per notebook with `pin_limit`, including restore/move/rename. Invalid policy fields refuse with `invalid_policy`.
72
+ `notes_write` and `notes_update` accept optional `pinned`, `budget`, and `readonly` policy fields. Their receipts, list/search rows, and read `metadata` expose the effective `pinned`, `budget`, and `readonly` values as structured fields **and visible text**. Successes also carry a `warnings` array (per file for list/search), rendered visibly when a body exceeds its budget: the default is 4096 Unicode code points for ordinary pages and 2048 for root `CHEATSHEET.md` and `MAP.md`, adjustable per note. Overflow saves successfully; boot injects full pinned bodies instead of cutting them. Pi's custom write/update/read renderers show policy and warnings even when collapsed, outside the expandable body/diff and clipped summary. A readonly note refuses mutations with `readonly` until explicitly unlocked with `readonly:false`; this is a soft lock, not security. Pin admission refuses a sixth live pin per notebook with `pin_limit`, including restore/move/rename. Invalid policy fields refuse with `invalid_policy`.
73
73
 
74
74
  A note read reports unrecognized frontmatter under `metadata.extra`; a value too large to carry, or past the verbatim budget, is named in place as `[omitted: too large]` under its key rather than delivered in part, and the value itself stays in the note file. A rename receipt uses `address` for the destination and `rename_from` for the source; it has no duplicate `rename_to` field.
75
75