notesoup 0.52.5 → 0.52.7

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 (44) hide show
  1. package/dist/plugins/claude/src/helper.js +34 -7
  2. package/dist/plugins/claude/src/history.d.ts +7 -2
  3. package/dist/plugins/claude/src/history.js +53 -22
  4. package/dist/plugins/claude/src/text.d.ts +5 -0
  5. package/dist/plugins/claude/src/text.js +12 -0
  6. package/dist/src/history/history.js +12 -11
  7. package/dist/src/notes/store.d.ts +2 -0
  8. package/dist/src/notes/store.js +2 -2
  9. package/dist/src/tools/dream.d.ts +2 -0
  10. package/dist/src/tools/history.d.ts +5 -3
  11. package/dist/src/tools/history.js +9 -11
  12. package/dist/src/tools/notes.d.ts +7 -0
  13. package/dist/src/tools/notes.js +8 -3
  14. package/dist/test/claude-history.test.js +135 -3
  15. package/dist/test/dream-skill.test.js +5 -0
  16. package/dist/test/dream-tools.test.js +15 -0
  17. package/dist/test/history.integration.test.js +26 -1
  18. package/dist/test/notes-library.test.js +1 -1
  19. package/dist/test/notes.test.js +1 -1
  20. package/dist/test/pi-render.test.js +2 -2
  21. package/docs/claude-code-mod.md +6 -2
  22. package/docs/tool-results.md +2 -2
  23. package/package.json +1 -1
  24. package/playbook.md +24 -13
  25. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  26. package/plugins/claude/dist/claude/helper.js +105 -44
  27. package/plugins/claude/playbook.md +24 -13
  28. package/plugins/claude/skills/dream/SKILL.md +8 -0
  29. package/plugins/claude/src/helper.ts +34 -9
  30. package/plugins/claude/src/history.ts +54 -22
  31. package/plugins/claude/src/text.ts +13 -0
  32. package/plugins/paseo/OVERVIEW.md +6 -2
  33. package/plugins/paseo/client/brain-empty-card.tsx +3 -1
  34. package/plugins/paseo/client/brain-empty-transformer.ts +7 -14
  35. package/plugins/paseo/client/notes-op-transformer.ts +10 -18
  36. package/plugins/paseo/client/tool-result.ts +31 -0
  37. package/plugins/paseo/test/brain-empty.test.ts +24 -1
  38. package/plugins/paseo/test/fixtures/claude-tool-calls.ts +86 -0
  39. package/plugins/paseo/test/notes-op.test.ts +39 -1
  40. package/skills/dream/SKILL.md +8 -0
  41. package/src/history/history.ts +12 -10
  42. package/src/notes/store.ts +4 -3
  43. package/src/tools/history.ts +14 -13
  44. package/src/tools/notes.ts +8 -3
@@ -9,6 +9,7 @@ import { unavailableNotesSnapshot } from "../src/boot/snapshot.js";
9
9
  import { DEFAULT_BOOT_TOOL_NAMES } from "../src/boot/text.js";
10
10
  import { allItems, eventDocument } from "../src/history/history.js";
11
11
  import { historyList, historyRead, historyWindows } from "../src/tools/history.js";
12
+ import { TOOL_OUTPUT_MAX_BYTES } from "../src/tools/output.js";
12
13
  import { dispatch } from "../plugins/claude/src/helper.js";
13
14
  const sessionId = "synthetic-session";
14
15
  function row(uuid, parentUuid, type, content, extra = {}) {
@@ -84,11 +85,15 @@ test("Claude file-history deltas do not become events or change history addresse
84
85
  assert.deepEqual(project([delta, rows[0], delta, rows[1], delta], "a"), baseline);
85
86
  assert.equal(baseline.highestSeq, 2);
86
87
  });
87
- test("Claude skips unknown record types unless selected ancestry requires them", () => {
88
+ test("Claude skips unknown record types and treats required skipped UUIDs as gaps, not content", () => {
88
89
  const u = user("u", null, "hello"), a = assistant("a", "u", [{ type: "text", text: "reply" }]);
89
90
  const unknown = { type: "future-record", uuid: "future", parentUuid: "not-on-disk", content: "private metadata" };
90
91
  assert.deepEqual(project([unknown, u, unknown, a, unknown], "a"), project([u, a], "a"));
91
- assert.throws(() => project([u, unknown, { ...a, parentUuid: "future" }], "a"), /missing Claude transcript ancestor: future/);
92
+ const incomplete = project([u, unknown, { ...a, parentUuid: "future" }], "a");
93
+ assert.deepEqual(incomplete.missingAncestors, ["future"]);
94
+ assert.equal(incomplete.currentWindowOrdinal, undefined);
95
+ assert.deepEqual(allItems(incomplete).map((event) => event.seq), [2]);
96
+ assert.doesNotMatch(allItems(incomplete).map(eventDocument).join("\n"), /private metadata|hello/);
92
97
  });
93
98
  test("Claude duplicate UUID records do not allocate again or move addresses on reload", () => {
94
99
  const u = user("u", null, "hello"), a = assistant("a", "u", [call("one")]);
@@ -182,7 +187,7 @@ test("Claude resolves forward persisted ancestry without renumbering or using la
182
187
  assert.equal(allItems(projection).find((event) => event.text === "hook notice")?.windowId, `claude:${sessionId}:0`);
183
188
  assert.equal(allItems(projection).find((event) => event.text === "after reset")?.windowId, `claude:${sessionId}:1`);
184
189
  assert.deepEqual(project(rows, "new"), projection);
185
- assert.throws(() => project([notice], "notice"), /missing.*ancestor/);
190
+ assert.deepEqual(project([notice], "notice").missingAncestors, ["attachment"]);
186
191
  assert.equal(project([user("u", null, bootText(9))], "u").windows.length, 1, "ordinary user text is not a trusted retained boot");
187
192
  });
188
193
  test("Claude attachments expose recorded renderings only and keep non-rendered nodes in ancestry", () => {
@@ -203,8 +208,135 @@ test("Claude tolerates only the uncommitted JSONL tail, not malformed committed
203
208
  assert.throws(() => project([row("u", null, "user", { type: "text", text: "not an array" })], "u"), /message content/);
204
209
  assert.throws(() => project([user("u", null, "first"), user("u", null, "conflict")], "u"), /conflicting.*duplicate UUID/);
205
210
  assert.throws(() => project([{ ...user("u", null, "first"), isSidechain: true }], "u"), /only the main/);
211
+ assert.throws(() => project([user("u", "a", "cycle"), assistant("a", "u", "cycle")], "a"), /cyclic Claude transcript ancestry/);
212
+ assert.throws(() => project([user("u", "missing", "gap"), assistant("a", "a", "cycle")], "a"), /cyclic Claude transcript ancestry/);
206
213
  assert.throws(() => project([{ ...user("u", null, "first"), sessionId: "another-session" }], "u"), /different session/);
207
214
  });
215
+ test("Claude gaps retain only confirmed suffixes, keep pairing/seqs, and disappear when the ancestor is appended", async () => {
216
+ const rows = [user("prefix", null, "unconfirmed prefix"), assistant("sibling", "prefix", "unrelated sibling"),
217
+ assistant("suffix", "missing", [{ type: "text", text: "searchable suffix" }, call("one")]),
218
+ row("output", "suffix", "user", [result("one", "confirmed output")]),
219
+ assistant("gap-sibling", "missing", "unrelated gap sibling")];
220
+ const incomplete = project(rows, "output");
221
+ assert.deepEqual(incomplete.missingAncestors, ["missing"]);
222
+ assert.equal(incomplete.currentWindowOrdinal, undefined);
223
+ assert.deepEqual(allItems(incomplete).map((event) => event.seq), [3, 4, 5]);
224
+ assert.equal(incomplete.pairedResults.get(6), 4);
225
+ assert.equal(incomplete.highestSeq, 7);
226
+ assert.match(incomplete.windows[0].windowId, /:unknown:missing$/);
227
+ const suffix = await historyList.execute({ query: "searchable suffix" }, incomplete);
228
+ assert.ok(suffix.ok);
229
+ assert.deepEqual(suffix.data.items.map((item) => "seq" in item ? item.seq : -1), [3]);
230
+ const tool = await historyRead.execute({ seq: 4 }, incomplete);
231
+ assert.ok(tool.ok);
232
+ assert.match(tool.data.text, /confirmed output/);
233
+ assert.doesNotMatch(allItems(incomplete).map(eventDocument).join("\n"), /unconfirmed prefix|unrelated sibling|unrelated gap sibling/);
234
+ // A later first occurrence gets the next append seq, never an inserted seq.
235
+ const recovered = project([...rows, user("missing", "prefix", "recovered ancestor")], "output");
236
+ assert.deepEqual(recovered.missingAncestors, []);
237
+ assert.equal(recovered.currentWindowOrdinal, 0);
238
+ assert.equal(recovered.highestSeq, 8);
239
+ assert.deepEqual(allItems(recovered).map((event) => event.seq), [1, 3, 4, 5, 8]);
240
+ assert.equal(recovered.pairedResults.get(6), 4);
241
+ assert.ok(!recovered.branchSeqs.has(2) && !recovered.branchSeqs.has(7), "recovery never selects either sibling");
242
+ });
243
+ test("Claude helper reports gaps on list/read/windows and re-anchors reset state only with a retained boot", async (t) => {
244
+ const root = mkdtempSync(join(tmpdir(), "claude-history-gap-"));
245
+ t.after(() => rmSync(root, { recursive: true, force: true }));
246
+ const transcriptPath = join(root, "transcript.jsonl");
247
+ const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
248
+ const rows = [user("prefix", null, "do not expose disconnected prefix"),
249
+ { type: "future-record", uuid: "missing", parentUuid: "prefix", content: "do not expose metadata" },
250
+ assistant("suffix", "missing", "confirmed suffix")];
251
+ const history = { sessionId, transcriptPath, headUuid: "suffix" };
252
+ const invoke = (tool, params = {}) => dispatch({ op: "tool", tool, params, identity, history });
253
+ writeFileSync(transcriptPath, jsonl(rows));
254
+ for (const [tool, params] of [["history_list", {}], ["history_read", { seq: 2 }], ["history_windows", {}],
255
+ ["history_list", { query: "no matches" }], ["history_read", { seq: 99 }]]) {
256
+ const response = await invoke(tool, params);
257
+ assert.match(response.text, /history is incomplete: missing ancestor UUID\(s\): "missing"/);
258
+ assert.doesNotMatch(response.text, /do not expose/);
259
+ }
260
+ assert.match((await invoke("history_list")).text, /confirmed suffix/);
261
+ const excluded = await invoke("history_read", { seq: 1 });
262
+ assert.equal(excluded.ok, false);
263
+ assert.match(excluded.text, /outside the confirmed selected history/);
264
+ assert.match((await invoke("history_list", { window_id: "@previous" })).text, /Cannot resolve "@previous"/);
265
+ await assert.rejects(invoke("history_list", { window_id: "@previous", before_seq: "invalid" }), /invalid history_list parameters: before_seq/);
266
+ await assert.rejects(invoke("history_read", { seq: "2" }), /invalid history_read parameters: seq/);
267
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /cannot determine the current window ordinal/);
268
+ // A native boundary alone cannot count the missing earlier resets. A quoted
269
+ // identity without the full retained protocol is not a new ordinal anchor.
270
+ rows.push(compact("boundary", "suffix"), row("partial", "boundary", "user", "Current context window id: claude:synthetic-session:8"));
271
+ writeFileSync(transcriptPath, jsonl(rows));
272
+ history.headUuid = "partial";
273
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /cannot determine the current window ordinal/);
274
+ rows.push(row("boot", "partial", "user", bootText(8), { isCompactSummary: true }), user("after", "boot", "after anchored reset"));
275
+ writeFileSync(transcriptPath, jsonl(rows));
276
+ history.headUuid = "after";
277
+ const anchored = await readClaudeHistory(history);
278
+ assert.equal(anchored.currentWindowOrdinal, 8);
279
+ assert.deepEqual(anchored.windows.map((window) => window.windowId), [`claude:${sessionId}:8`, `claude:${sessionId}:unknown:missing`], "unknown segments are listed separately, not inserted into the numbered timeline");
280
+ assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 8 }, "never windows.length - 1");
281
+ assert.match((await invoke("history_read", { seq: 6 })).text, /window claude:synthetic-session:8/);
282
+ assert.match((await invoke("history_windows")).text, /history is incomplete/);
283
+ assert.match((await invoke("history_list", { window_id: "@previous" })).text, /Cannot resolve "@previous"/);
284
+ rows.push(compact("next", "after"), row("next-boot", "next", "user", bootText(9)), user("latest", "next-boot", "latest"));
285
+ writeFileSync(transcriptPath, jsonl(rows));
286
+ history.headUuid = "latest";
287
+ const previous = await invoke("history_list", { window_id: "@previous" });
288
+ assert.ok(previous.ok);
289
+ assert.match(previous.text, /after anchored reset/);
290
+ assert.doesNotMatch(previous.text, /confirmed suffix/);
291
+ // Restore the record as a supported message: warning disappears on the next
292
+ // read, without any in-memory repair state or changed existing addresses.
293
+ rows.push(user("missing", "prefix", "recovered ancestor"));
294
+ writeFileSync(transcriptPath, jsonl(rows));
295
+ assert.doesNotMatch((await invoke("history_windows")).text, /history is incomplete|:unknown:/);
296
+ assert.deepEqual(await dispatch({ op: "history_state", identity, history }), { window: 9 });
297
+ });
298
+ test("Claude gap windows sort by confirmed ordinal despite forward references, without duplicating paired output", async () => {
299
+ const rows = [row("notice", "boot9", "system", "notice"),
300
+ row("boot8", "missing", "user", bootText(8), { isCompactSummary: true }),
301
+ assistant("call", "boot8", [call("t")]), compact("boundary9", "call"),
302
+ row("boot9", "boundary9", "user", bootText(9)), row("result", "notice", "user", [result("t", "output")])];
303
+ const projection = project(rows, "result");
304
+ const windows = await historyWindows.execute({}, projection, sessionId);
305
+ assert.ok(windows.ok);
306
+ assert.deepEqual(windows.data.windows.map((window) => window.window_id), [8, 9].map((ordinal) => `claude:${sessionId}:${ordinal}`));
307
+ assert.equal(projection.currentWindowOrdinal, 9);
308
+ assert.equal(projection.highestSeq, 8);
309
+ assert.deepEqual(allItems(projection).filter((event) => event.role === "tool").map((event) => [event.seq, event.text]), [[4, "output"]]);
310
+ assert.equal(projection.pairedResults.get(8), 4);
311
+ const alias = await historyRead.execute({ seq: 8 }, projection);
312
+ assert.ok(!alias.ok);
313
+ assert.equal(alias.error.code, "not_an_event");
314
+ assert.match(alias.error.message, /read seq 4/);
315
+ });
316
+ test("Claude gap notices participate in list/read budgets without changing read coordinates", async (t) => {
317
+ const root = mkdtempSync(join(tmpdir(), "claude-history-budget-"));
318
+ t.after(() => rmSync(root, { recursive: true, force: true }));
319
+ const transcriptPath = join(root, "transcript.jsonl"), text = "x".repeat(50000);
320
+ writeFileSync(transcriptPath, jsonl([assistant("head", "missing", text)]));
321
+ const identity = { home: join(root, "notes"), sessionId, cwd: root, agent: "claude", model: "claude" };
322
+ const history = { sessionId, transcriptPath, headUuid: "head" };
323
+ const invoke = async (tool, params) => {
324
+ const response = await dispatch({ op: "tool", tool, params, identity, history });
325
+ assert.ok(response.ok);
326
+ assert.match(response.text, /history is incomplete.*"missing"/);
327
+ assert.ok(Buffer.byteLength(response.text, "utf8") <= TOOL_OUTPUT_MAX_BYTES, `${tool}: ${Buffer.byteLength(response.text, "utf8")} bytes`);
328
+ return response.text;
329
+ };
330
+ const first = await invoke("history_read", { seq: 1, max_chars: 50000 });
331
+ const offset = Number(/\[truncated; continue at offset_chars=(\d+)\]$/.exec(first)?.[1]);
332
+ assert.ok(offset > 0 && offset < text.length);
333
+ const firstBody = /\n\n(x+)\n\n\[truncated;/.exec(first)?.[1];
334
+ assert.equal(firstBody, text.slice(0, offset), "the footer addresses the first undelivered character, not the decorated text");
335
+ const rest = await invoke("history_read", { seq: 1, offset_chars: offset, max_chars: 50000 });
336
+ assert.equal(/\n\n(x+)$/.exec(rest)?.[1], text.slice(offset));
337
+ assert.doesNotMatch(rest, /\[truncated;/);
338
+ await invoke("history_list", { max_chars_per_item: 50000 });
339
+ });
208
340
  test("Claude helper history tools reuse shared schemas, outcomes and text rendering from a supplied path", async (t) => {
209
341
  const root = mkdtempSync(join(tmpdir(), "claude-history-"));
210
342
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -38,6 +38,11 @@ test("dream skill is publicly discoverable and resolves the shared playbook", ()
38
38
  assert.equal(skillPlaybook, packagePlaybook);
39
39
  const playbook = readFileSync(packagePlaybook, "utf8");
40
40
  assert.equal(readFileSync(skillPlaybook, "utf8"), playbook);
41
+ const instructions = readFileSync(join(skill.baseDir, "SKILL.md"), "utf8");
42
+ for (const name of ["dream_begin", "dream_forget", "dream_end"])
43
+ assert.ok(instructions.includes(name));
44
+ assert.match(instructions, /missing from the current tool list, search for them/);
45
+ assert.doesNotMatch(instructions, /tool_search|searchTools|codemode/);
41
46
  });
42
47
  test("npm tarball keeps the skill's relative playbook path portable after extraction", () => {
43
48
  const root = packageRoot();
@@ -36,6 +36,8 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
36
36
  const begun = await dreamBegin.execute({ project: "beta" }, me, state);
37
37
  assert.ok(begun.ok);
38
38
  assert.deepEqual(begun.data.files.map(f => f.address).sort(), ["@projects/beta/rule.md", "@sessions/b1/checkpoint.md", "@sessions/b2/trash.md"]);
39
+ assert.ok(begun.data.files.every(f => typeof f.last_accessed === "string"), "the dream's list shows each note's last access");
40
+ assert.match(dreamBegin.render(begun), /\| accessed /);
39
41
  assert.equal((await dreamBegin.execute({}, me, state)).ok, false, "only one dream at a time");
40
42
  assert.ok(existsSync(join(home, ".dream.lock.beta")), "the project lock is held");
41
43
  assert.equal((await dreamBegin.execute({ project: "beta" }, as("other", "alpha"), {})).ok, false, "another session can't dream the same project");
@@ -59,6 +61,19 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
59
61
  assert.equal((await notesWrite.execute({ address: "@projects/beta/rule", content: "x" }, ident())).ok, false, "closed again");
60
62
  assert.equal((await dreamEnd.execute({}, me, state)).ok, false);
61
63
  });
64
+ test("notes_read reports the access before itself, so reading never makes an unread note look fresh", async (t) => {
65
+ const { home, as } = fixture(t);
66
+ const me = as("s", "alpha");
67
+ const old = "2026-01-01T08:00:00.000+08:00";
68
+ mkdirSync(join(home, "human"), { recursive: true });
69
+ writeFileSync(join(home, "human", "stale.md"), `---\norigin: self\ncreatedAt: ${old}\nupdatedAt: ${old}\nlastAccessed: ${old}\naccessCount: 0\n---\n\nbody`);
70
+ const first = await notesRead.execute({ address: "@human/stale" }, me);
71
+ assert.ok(first.ok);
72
+ assert.equal(Date.parse(first.data.metadata.last_accessed), Date.parse(old), "the first read shows the old access");
73
+ const second = await notesRead.execute({ address: "@human/stale" }, me);
74
+ assert.ok(second.ok);
75
+ assert.ok(Date.parse(second.data.metadata.last_accessed) > Date.parse(old), "the first read still counted as an access");
76
+ });
62
77
  test("dream_begin refuses an unknown project", async (t) => {
63
78
  const { as } = fixture(t);
64
79
  const state = {};
@@ -93,6 +93,20 @@ test("every history operation declares a result schema its own payload satisfies
93
93
  const refusal = await call(captured, "history_read", { seq: 999 }, ctx);
94
94
  assert.equal(Check(historyRead.outputSchema, refusal.structuredContent), true, "a refusal satisfies the same result schema");
95
95
  });
96
+ test("pairing uses append seq rather than the presentation order of unnumbered segments", async () => {
97
+ const projection = projectHistory([
98
+ { windowId: "unknown-a", items: [
99
+ { seq: 1, windowId: "unknown-a", role: "system", text: "notice" },
100
+ { seq: 3, windowId: "unknown-a", role: "tool", toolCallId: "t", text: "output" },
101
+ ] },
102
+ { windowId: "unknown-b", items: [{ seq: 2, windowId: "unknown-b", role: "tool_call", toolCallId: "t", toolName: "bash", text: "" }] },
103
+ ], 3, new Set([1, 2, 3]));
104
+ assert.deepEqual(projection.windows.map((window) => window.windowId), ["unknown-a", "unknown-b"], "pairing must not invent segment chronology");
105
+ assert.deepEqual(projection.windows.flatMap((window) => window.items).filter((event) => event.role === "tool").map((event) => [event.seq, event.text]), [[2, "output"]]);
106
+ const alias = await historyRead.execute({ seq: 3 }, projection);
107
+ assert.ok(!alias.ok);
108
+ assert.equal(alias.error.code, "not_an_event");
109
+ });
96
110
  test("seq is stable across branch changes, abandoned entries stay unreadable, and a paired result seq is refused precisely", async () => {
97
111
  const session = manager();
98
112
  const captured = makeExtension(session);
@@ -647,7 +661,7 @@ test("history_read paginates one document with an accurate limit and a bounded b
647
661
  assert.equal(past.code, "invalid_offset");
648
662
  assert.match(past.message, new RegExp(`\\b${content.length}\\b`), "the refusal names the real length");
649
663
  });
650
- test("history windows expose stable ranges and session identity", async () => {
664
+ test("history windows expose stable ranges and include host decoration in the complete budget", async () => {
651
665
  const session = manager();
652
666
  const captured = makeExtension(session);
653
667
  const ctx = context(session);
@@ -656,6 +670,17 @@ test("history windows expose stable ranges and session identity", async () => {
656
670
  assert.equal(windows.session_id, session.getSessionId());
657
671
  assert.equal(windows.windows.length, 1);
658
672
  assert.deepEqual(windows.windows[0], { window_id: windows.windows[0].window_id, created_at: null, first_seq: 1, last_seq: 1 });
673
+ const projection = projectHistory([0, 1, 2].map((index) => ({ windowId: `w${index}-${"x".repeat(200)}`, items: [] })), 0, new Set());
674
+ const notice = `${"n".repeat(TOOL_OUTPUT_MAX_BYTES - 400)}\n`;
675
+ const wrapText = (text) => notice + text;
676
+ const bounded = await historyWindows.execute({}, projection, "session-x", wrapText);
677
+ assert.ok(bounded.ok);
678
+ assert.equal(bounded.data.windows.length, 1);
679
+ assert.equal(bounded.data.more, 2);
680
+ const text = wrapText(historyWindows.render(bounded));
681
+ assert.ok(Buffer.byteLength(text, "utf8") <= TOOL_OUTPUT_MAX_BYTES);
682
+ assert.ok(text.startsWith(notice), "decoration is measured, never clipped at delivery");
683
+ assert.match(text, /2 more windows not shown/);
659
684
  });
660
685
  test("historyDocument is one deterministic projection of the facts, with no UI header or continuation suffix", async () => {
661
686
  const windowId = "w1";
@@ -139,7 +139,7 @@ test("search offsets address the body and never move when access metadata grows"
139
139
  assert.equal(frontBody, "needle later");
140
140
  assert.equal(frontMatch.offsetChars, 0, "frontmatter length is not part of the body offset");
141
141
  assert.equal(Array.from(frontBody).slice(frontMatch.offsetChars).join(""), "needle later");
142
- assert.deepEqual(Object.keys((await notes.read("counted.md"))).sort(), ["body", "meta", "resolvedScope"], "a read exposes metadata and the body, never a serialized rendering");
142
+ assert.deepEqual(Object.keys((await notes.read("counted.md"))).sort(), ["accessedBefore", "body", "meta", "resolvedScope"], "a read exposes metadata and the body, never a serialized rendering");
143
143
  });
144
144
  test("invalid addressing and failed edits leave stored bytes untouched without poisoning the queue", async (t) => {
145
145
  const { home, context, notes } = fixture(t);
@@ -403,7 +403,7 @@ test("list and search merge scopes and carry addresses; the path jail rejects es
403
403
  const listed = resultData(await call(captured, "notes_list", {}, ctx));
404
404
  assert.deepEqual([...listed.files].map((file) => file.address).sort(), ["@human/three.md", "@project/two.md", "one.md"], "every merged row carries its full address");
405
405
  for (const row of listed.files) {
406
- assert.deepEqual(Object.keys(row).sort(), ["address", "updated_at", ...(row.address.startsWith("@project/") ? ["project_key"] : [])].sort());
406
+ assert.deepEqual(Object.keys(row).sort(), ["address", "updated_at", "last_accessed", ...(row.address.startsWith("@project/") ? ["project_key"] : [])].sort());
407
407
  }
408
408
  const scoped = resultData(await call(captured, "notes_list", { glob: "@human/**" }, ctx));
409
409
  assert.deepEqual(scoped.files.map((file) => file.address), ["@human/three.md"], "an address glob filter narrows the set");
@@ -51,12 +51,12 @@ test("notes_update unchanged keeps quiet", () => {
51
51
  assert.equal(lines(component), "unchanged a.md");
52
52
  });
53
53
  test("notes_read collapsed: size and a peek at the first line", () => {
54
- 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 }));
54
+ const result = toolResult(success({ address: "@project/MAP.md", metadata: { origin: "self", created_at: "x", updated_at: "y", last_accessed: "z", extra: {} }, text: "# MAP\n\nbody", total_chars: 11, next_offset_chars: null }));
55
55
  const component = notesReadRenderers.renderResult(result, { expanded: false }, flatTheme);
56
56
  assert.equal(lines(component), "read @project/MAP.md · 11 chars — # MAP");
57
57
  });
58
58
  test("notes_read expanded: truncation points at the next offset", () => {
59
- 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 }));
59
+ const result = toolResult(success({ address: "a.md", metadata: { origin: "self", created_at: "x", updated_at: "y", last_accessed: "z", extra: {} }, text: "part", total_chars: 10, next_offset_chars: 4 }));
60
60
  const component = notesReadRenderers.renderResult(result, { expanded: true }, flatTheme);
61
61
  assert.equal(lines(component), "read a.md · 10 chars · truncated — part\n\npart\n… continue at offset_chars=4");
62
62
  });
@@ -24,9 +24,13 @@ The notes tools also serve subagent calls, using the same session identity and s
24
24
 
25
25
  The active head comes from the main loop's successful `session.append` result UUID, including attachments and notices. On startup/resume, before such an append, the public API supplies no authoritative selected leaf: history explicitly refuses instead of assuming the last file row or `last-prompt.leafUuid` is current. The append result means the engine kept a row, but its disk write may lag; a head missing on disk is a retryable refusal, not permission to switch branches. Session end clears the binding; a new classic start rebinds it.
26
26
 
27
- Seqs are allocated over first-occurrence persisted append order, before active-branch filtering: one address per logical message/attachment/notice and additional addresses for each tool use/result. Repeated UUID records do not allocate again. List pages skip empty user/assistant envelopes even with explicit roles, so tool-only and thinking-only rows do not crowd out dialogue; direct reads preserve those addresses and explicitly say when no visible text was recorded. Results pair by `tool_use_id`; pending calls remain unfinished, and a paired result's seq redirects to its call. Only text blocks and recorded attachment renderings become visible text; thinking and raw, unrendered attachment payloads are never exposed. Record types other than user, assistant, system and attachment are ignored, including future metadata, without allocating addresses or exposing payloads. If the selected branch requires a skipped record as an ancestor, history refuses with the missing ancestor UUID. Invalid supported message/block schemas and malformed committed JSONL lines still refuse explicitly. An incomplete final unterminated write is tolerated. Valid forward parent references are resolved after reading the snapshot, without reallocating addresses.
27
+ Seqs are allocated over first-occurrence persisted append order, before active-branch filtering: one address per logical message/attachment/notice and additional addresses for each tool use/result. Repeated UUID records do not allocate again. List pages skip empty user/assistant envelopes even with explicit roles, so tool-only and thinking-only rows do not crowd out dialogue; direct reads preserve those addresses and explicitly say when no visible text was recorded. Results pair by `tool_use_id`; pending calls remain unfinished, and a paired result's seq redirects to its call. Only text blocks and recorded attachment renderings become visible text; thinking and raw, unrendered attachment payloads are never exposed. Record types other than user, assistant, system and attachment are ignored, including future metadata, without allocating addresses or exposing payloads. If the selected branch requires a skipped record as an ancestor, that UUID is an ancestry gap, not a visible metadata event. Invalid supported message/block schemas, conflicting duplicates, session/sidechain mismatches, cycles and malformed committed JSONL lines still refuse explicitly. An incomplete final unterminated write is tolerated. Valid forward parent references are resolved after reading the snapshot, without reallocating addresses.
28
28
 
29
- The selected tree follows the latest native `parentUuid` links. Compact boundaries also join their `logicalParentUuid` and recorded preserved segments through original ancestry, retaining old events instead of presenting only retained inference context. Auxiliary preservation UUIDs that were never persisted are skipped. Windows use `claude:<sessionId>:<ordinal>`, matching the current boot: native compact boundaries advance the ordinal, and retained notesoup boot markers name that same ordinal rather than advancing it again. A fork preserves the copied boot's ordinal but uses its own session id for public window ids. Copied prompt-context boot blocks are rebuilt with a fresh notes snapshot and the current session identity; historical boot messages in the transcript remain unchanged. Preserved duplicate rows keep their original window; new children of their rewritten versions inherit the new window. `@previous` resolves through this oldest-first window list. A missing required ancestor is an explicit refusal.
29
+ The selected tree follows the latest native `parentUuid` links. Compact boundaries also join their `logicalParentUuid` and recorded preserved segments through original ancestry, retaining old events instead of presenting only retained inference context. Auxiliary preservation UUIDs that were never persisted are skipped. Windows use `claude:<sessionId>:<ordinal>`, matching the current boot: native compact boundaries advance the ordinal, and retained notesoup boot markers name that same ordinal rather than advancing it again. A fork preserves the copied boot's ordinal but uses its own session id for public window ids. Copied prompt-context boot blocks are rebuilt with a fresh notes snapshot and the current session identity; historical boot messages in the transcript remain unchanged. Preserved duplicate rows keep their original window; new children of their rewritten versions inherit the new window.
30
+
31
+ A missing required ancestor stops only that traversal edge. Confirmed selected suffixes and explicitly linked compaction history remain queryable; append order never joins a disconnected prefix or selects a sibling. All three history tools prepend a bounded Claude-specific incomplete-history notice, including missing UUID evidence, even for empty selections or query errors. The same pure text wrapper is supplied to shared selection/read budget checks and final delivery, so the complete text including the notice fits 32 KiB without clipping event text or continuation footers afterward. The notice is outside event documents, search matches and read offsets; the shared query schemas are unchanged. Previously allocated seqs remain unchanged if the missing record later appears: its first occurrence takes the next append address, and a fresh projection removes the gap notice when ancestry is complete.
32
+
33
+ Without a path back to a root or retained boot, window ordinals are unknown. Those events use `claude:<sessionId>:unknown:<missingUuid>` as an explicitly unnumbered segment (possibly spanning native compactions), not an invented ordinal. A subsequent complete retained boot re-anchors its own and later window ordinals without filling the history gap. Incomplete projections list only evidenced windows/segments, not empty placeholders for unseen ordinals. Confirmed numbered windows are sorted by ordinal (including when forward references put newer-window rows on disk first). Unknown segments are listed separately after the numbered windows; that placement does not assert chronological order for them. Shared tool pairing scans stable append seq order before regrouping events for display, so it does not depend on window/segment presentation order. `@previous` requires the exact preceding numbered window to be evidenced when history is incomplete, rather than choosing an adjacent unknown segment. The helper's reset-facing `history_state` returns the head's independently resolved ordinal, never `windows.length - 1`; if it is unknown, it explicitly refuses rather than supplying a guessed number. Existing reset-hook refusal handling leaves its prior state intact.
30
34
 
31
35
  ## Validation
32
36
 
@@ -59,7 +59,7 @@ Pi's nested records contain child ID, name, optional arguments, status, timing a
59
59
 
60
60
  ## Bounds and continuation
61
61
 
62
- One selection determines the structured result and its text. Both complete representations must fit the 32 KiB output budget, including metadata, cursor and rendered notice. A programmatic caller does not receive an unbounded hidden payload beside a truncated textual one.
62
+ One selection determines the structured result and its text. Both complete representations must fit the 32 KiB output budget, including metadata, cursor and rendered notice. A programmatic caller does not receive an unbounded hidden payload beside a truncated textual one. History operations accept an optional pure text wrapper from the host: selection and read-window checks measure that wrapper around the shared rendering, and the caller must apply the same wrapper at delivery. Host prose stays in its plugin; no final clipping or separate query is involved.
63
63
 
64
64
  History pages carry `page_older` and `page_newer`, the exact params to merge into the next call; `from` picks which end of a bounded range `limit` counts from, `since`/`until` narrow that range by event `created_at`, and only a 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. `history_windows` is a snapshot too: its `more` counts the windows the budget left out and there is no window cursor, because `history_list` rows also expose `window_id`. 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.
65
65
 
@@ -73,6 +73,6 @@ A note read reports unrecognized frontmatter under `metadata.extra`; a value too
73
73
  - The history adapter owns native decoding, seq allocation and branch visibility.
74
74
  - Shared operations own the typed result, filtering, paging, character windows and refusal messages.
75
75
  - Shared renderers derive text from that result.
76
- - Pi/Claude adapters supply host identity, projections and transport packaging only.
76
+ - Pi/Claude adapters supply host identity, projections, optional pure text decoration and transport packaging only.
77
77
 
78
78
  There is no second query implementation for codemode, no copy of session storage and no migration of user records.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.52.5",
3
+ "version": "0.52.7",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
package/playbook.md CHANGED
@@ -4,31 +4,42 @@ I am reviewing my notes: keeping what is useful, connecting what belongs togethe
4
4
 
5
5
  ## Scope
6
6
 
7
- Work within the readable sources and writable homes established for this run. Do not broaden that scope while exploring. If a boundary is unclear, ask before crossing it.
8
-
9
- A project dream draws from that project's material, project notes, and session notes identified as belonging to the project; it organizes only that project's notes. A store-wide dream may inspect across homes, but authorship and write permissions still apply. Unknown ownership is a coverage gap to report, not a reason to guess or repair ownership.
7
+ A dream covers one project: its `@project` notes and the session notes born in it. `@human`, `@self`, and `@model` are not part of a dream unless the human asks for them or the dream runs from inside the notes home itself. Do not broaden that scope while exploring; if a boundary is unclear, ask before crossing it. Unknown ownership is a coverage gap to report, not a reason to guess or repair ownership.
10
8
 
11
9
  The homes serve different readers:
12
10
 
13
- - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
11
+ - Session notes (`<path>`, no `@`) are a trip's working record. Read them as sources; do not rewrite them. Only the wastebasket rule below may remove another session's notes.
14
12
  - `@project` notes hold knowledge for whoever next works on that project.
15
13
  - `@human` notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own conclusions into rules in the human's voice.
16
14
  - `@self` notes belong to their author: private if the author has a name, one shared notebook for everyone nameless. Other named authors' notes are read-only unless the human authorizes revision.
17
15
  - `@model` notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
18
16
 
17
+ ## What a durable note holds
18
+
19
+ Durable notes hold decisions, constraints, and lessons that stay true after the current work ends. They are not diaries: commit hashes, test counts, dates, and the story of how something was reached belong to git and history. A session finding is worth promoting only when it meets this bar.
20
+
19
21
  ## Review and consolidate
20
22
 
21
- 1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
22
- 2. **Verify only what the proposed change depends on.** Before correcting or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead; do not promote an unsupported claim as current fact.
23
- 3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
24
- 4. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, migrate it: copy it there preserving frontmatter with a one-line provenance note, crumple the original, and update both homes' maps. Crumple keeps the original readable by address, so relocation is reversible: do it, don't propose it. Propose only when the destination home itself is unclear.
25
- 5. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
26
- 6. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links. Checkpoints may exceed the budget: trim prose, never facts.
27
- 7. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
28
- 8. **Preserve the record.** Never physically delete a live note; after merging, crumple the absorbed note only if it is writable. The wastebasket is the one exception: physically delete a crumpled note when its home is writable and it has been crumpled and untouched for more than 7 days. With raw frontmatter, judge by `lastAccessed`, falling back to `crumpledAt`. With only `notes_*` tools, judge by `crumpled_at`. If no date is readable, keep the note and report it. Never read a raw note through `notes_read` to get the date: it refreshes `lastAccessed`. A venue that cannot delete files lists the doomed addresses in its report instead of blanking them. Preserve existing metadata and provenance.
23
+ 1. **Leave stable notes alone.** Change a note to incorporate new evidence, fix a verified error, retire a stale claim, merge a genuine duplicate, trim diary content, or split an oversized file, not merely to shorten or rephrase it. No change is a valid outcome.
24
+ 2. **Verify only what the proposed change depends on.** Before correcting, retiring, or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead.
25
+ 3. **Retire what is no longer true.** When evidence shows a durable note is stale, correct it in place; if nothing true remains, crumple it. Remove or fix its MAP line either way. A note's last access is a hint, not evidence: long-unread notes are candidates to check, not to crumple on sight. A read reports the access before itself, so reviewing a note does not make it look fresh.
26
+ 4. **Merge only genuine duplicates.** Merge two notes only when they share a topic and kind (checkpoint, design, log). First carry every fact, condition, and exception unique to the absorbed note into the survivor, then crumple the absorbed note. Otherwise keep both and record any unresolved conflict.
27
+ 5. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, move it there, preserving its metadata, and update both homes' maps. Do it, don't propose it. Propose only when the destination home itself is unclear.
28
+ 6. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
29
+ 7. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links.
30
+ 8. **Keep maps useful.** Each writable home's MAP.md may include a Cheatsheet of rules that apply in every window; keep it short, about 5 lines. The rest stays the note index: durable notes' addresses and short gists, for lookup. Preserve standing rules, add promoted notes, and drop entries that no longer hold. Maps follow the same size budget.
31
+
32
+ ## Deleting
33
+
34
+ Never physically delete a live note; crumple it first. Two cases allow deleting a crumpled note:
35
+
36
+ - **Your own session's notes** may be deleted once crumpled.
37
+ - **The wastebasket:** any note within the dream's reach that was crumpled more than 7 days ago may be deleted, whatever its home or session. Judge by its crumpled date; if none is readable, keep it and report it.
38
+
39
+ Where notes cannot be deleted, list the doomed addresses in the report instead of blanking them.
29
40
 
30
41
  ## Report
31
42
 
32
- Give a concise report grouped by home: what you inspected, changed, promoted, deleted, and left unresolved. Mention coverage gaps and partial failures. If no notes changed, say so. Distinguish actual note changes from execution or audit artifacts; do not claim success for an incomplete run.
43
+ Give a concise report grouped by home: what you inspected, changed, retired, promoted, deleted, and left unresolved. Mention coverage gaps and partial failures. If no notes changed, say so. Distinguish actual note changes from execution or audit artifacts; do not claim success for an incomplete run.
33
44
 
34
45
  Put skill ideas and unresolved questions in the final message as proposals for the human, not new skill files.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.52.5",
3
+ "version": "0.52.7",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"