notesoup 0.59.0 → 0.59.2

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 (52) hide show
  1. package/dist/plugins/claude/src/helper.js +2 -2
  2. package/dist/plugins/dsh/tools.js +0 -3
  3. package/dist/src/boot/text.d.ts +1 -1
  4. package/dist/src/boot/text.js +6 -10
  5. package/dist/src/history/claude.d.ts +3 -1
  6. package/dist/src/history/claude.js +40 -4
  7. package/dist/src/history/prefilter.d.ts +1 -1
  8. package/dist/src/history/prefilter.js +14 -9
  9. package/dist/src/notes/address.d.ts +1 -1
  10. package/dist/src/notes/address.js +1 -1
  11. package/dist/src/notes/policy.js +1 -1
  12. package/dist/src/tools/dream.d.ts +3 -3
  13. package/dist/src/tools/dream.js +5 -5
  14. package/dist/src/tools/history.js +12 -13
  15. package/dist/src/tools/notes.d.ts +7 -5
  16. package/dist/src/tools/notes.js +35 -34
  17. package/dist/src/tools/result.js +2 -2
  18. package/dist/src/tools/schema.js +2 -2
  19. package/dist/test/claude-history.test.js +22 -0
  20. package/dist/test/claude-mod.test.js +13 -1
  21. package/dist/test/dsh.test.js +13 -1
  22. package/dist/test/history-prefilter.test.js +5 -0
  23. package/dist/test/note-policy.test.js +6 -1
  24. package/dist/test/notes.integration.test.js +28 -0
  25. package/docs/claude-code-mod.md +3 -1
  26. package/docs/history-sessions.md +1 -1
  27. package/package.json +1 -1
  28. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  29. package/plugins/claude/dist/claude/helper.js +111 -81
  30. package/plugins/claude/hooks/register.ts +14 -10
  31. package/plugins/claude/src/helper.ts +2 -2
  32. package/plugins/codex/dist/codex/notesoup.js +74 -69
  33. package/plugins/dsh/tools.ts +0 -2
  34. package/plugins/paseo/README.md +16 -0
  35. package/plugins/paseo/client/brain-empty-card.tsx +5 -3
  36. package/plugins/paseo/client/markdown-core.tsx +189 -0
  37. package/plugins/paseo/client/markdown.tsx +38 -135
  38. package/plugins/paseo/client/notes-op-card.tsx +15 -12
  39. package/plugins/paseo/client/paper-card.tsx +1 -3
  40. package/plugins/paseo/client/sticky-card.tsx +2 -1
  41. package/plugins/paseo/client/typography.ts +24 -0
  42. package/plugins/paseo/test/markdown-core.test.ts +75 -0
  43. package/src/boot/text.ts +6 -10
  44. package/src/history/claude.ts +31 -4
  45. package/src/history/prefilter.ts +13 -9
  46. package/src/notes/address.ts +1 -1
  47. package/src/notes/policy.ts +1 -1
  48. package/src/tools/dream.ts +5 -5
  49. package/src/tools/history.ts +12 -14
  50. package/src/tools/notes.ts +35 -33
  51. package/src/tools/result.ts +2 -2
  52. package/src/tools/schema.ts +2 -2
@@ -13,12 +13,12 @@ import { nullableString, searchQuery } from "./schema.js";
13
13
  import { notesIdentityForCall } from "./notes-context.js";
14
14
  const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")];
15
15
  const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
16
- description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self.",
16
+ description: "Whose handwriting: user, self, or external. Leave it out to keep what's there.",
17
17
  }));
18
18
  const POLICY_PARAMETERS = {
19
- pinned: Type.Optional(Type.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
20
- budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 4096; root CHEATSHEET.md and MAP.md default 2048). Over budget warns but saves; boot does not truncate." })),
21
- readonly: Type.Optional(Type.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." })),
19
+ pinned: Type.Optional(Type.Boolean({ description: "Tape the page inside the cover: read whole at every wake-up. Five per notebook, CHEATSHEET and MAP included." })),
20
+ budget: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "How much paper the page gets. Writing past it still saves, with a warning. A page over budget gets boiled down: stale lines out, repeats merged, the rest said shorter. More paper is for a page already boiled down that still needs the room." })),
21
+ readonly: Type.Optional(Type.Boolean({ description: "A paperclip that keeps your own hands off. `false` takes it off — same call is fine." })),
22
22
  };
23
23
  const PolicySchema = {
24
24
  pinned: Type.Boolean(), budget: Type.Integer(), readonly: Type.Boolean(),
@@ -33,13 +33,12 @@ function renderPolicy(policy) {
33
33
  function withWarnings(text, data) {
34
34
  return [text, ...data.warnings].join("\n");
35
35
  }
36
- const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
37
- const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
38
- const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
39
- const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses, or @default for the current notebooks.");
40
- const CWD_PARAMETER = Type.Optional(Type.String({ minLength: 1, description: "(optional) Select the current project for this call. A relative path resolves against the host session cwd; the path must be an existing directory." }));
41
- const QUERY_NAMESPACES_DESCRIPTION = "Omit `glob` or use `@default` for this session and current shared notebooks; `**` searches all notebooks, `@sessions/*/**` searches all sessions.";
42
- const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable notebooks; `@projects/<name>/<path>` and `@sessions/<id>/<path>` read named project and session notes (read-only). Not file paths: never pass them to file tools.";
36
+ const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "`true` balls the page up: gone from list and search, still readable. `false` smooths it flat again." }));
37
+ const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "Only the crumpled balls." }));
38
+ const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "How many pages at most." }));
39
+ const GLOB_PARAMETER = nullableString("Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf · `MAP.md` that page in every notebook · `**` everything · `@sessions/*/**` every session.");
40
+ const CWD_PARAMETER = Type.Optional(Type.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
41
+ const ADDRESS_PARAMETER = Type.String({ description: "Which drawer the page sits in. `plan.md` — this session's desk, cleared when it ends. `@project/` this project's shelf · `@human/` your human's file · `@self/` your own notebook · `@model/` your brain's. `@projects/<name>/`, `@sessions/<id>/`, `@agents/<name>/`, `@models/<name>/` — someone else's shelf: read only. Paper, not files: hand one to read/write/edit/bash and a real `@project` folder is born." });
43
42
  /**
44
43
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
45
44
  * Convert expected refusals; unexpected errors propagate unchanged.
@@ -151,7 +150,7 @@ const MatchSchema = Type.Object({
151
150
  }, { additionalProperties: false });
152
151
  const SearchedFileSchema = Type.Object({
153
152
  ...ListedFileSchema.properties,
154
- matches: Type.Array(MatchSchema),
153
+ matches: Type.Array(MatchSchema), more_matches: Type.Optional(Type.Integer({ minimum: 1 })),
155
154
  }, { additionalProperties: false });
156
155
  export const SnapshotSchema = {
157
156
  more: Type.Integer({ description: "How many more were left out." }),
@@ -211,13 +210,13 @@ export function listedFile(row, identity) {
211
210
  const policy = policyAt(row.meta, row.address);
212
211
  return { ...noteIdentity(identity, row.address), ...policy, warnings: row.warnings ?? (row.body === undefined ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
213
212
  }
214
- export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
213
+ export const notesWriteParameters = Type.Object({ address: ADDRESS_PARAMETER, content: Type.String({ description: "The whole page." }), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
215
214
  function renderWriteData(data) {
216
215
  return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
217
216
  }
218
217
  export const notesWrite = {
219
218
  name: "notes_write", label: "Notes write",
220
- description: `Create a note, or overwrite its whole body. Name it for what it holds and when to use it. ${ADDRESS_DESCRIPTION}`,
219
+ description: "Take a fresh page and write it — or rip out the old one and write it again. Title it for what's inside and when you'll reach for it.",
221
220
  parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
222
221
  async execute(params, context) {
223
222
  try {
@@ -232,13 +231,13 @@ export const notesWrite = {
232
231
  render: (result) => renderOutcome(result, renderWriteData),
233
232
  };
234
233
  export const notesUpdateParameters = Type.Object({
235
- address: Type.String(),
236
- edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))),
234
+ address: ADDRESS_PARAMETER,
235
+ edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String({ description: "The passage as it stands on the page." }), newText: Type.String({ description: "What goes in its place." }) }, { additionalProperties: false }), { description: "Pen strokes, in order. Each `oldText` is the exact passage — same case, found once — and `newText` is what goes in its place." })),
237
236
  origin: ORIGIN,
238
237
  ...POLICY_PARAMETERS,
239
238
  crumpled: CRUMPLED_PARAMETER,
240
- replace_all: Type.Optional(Type.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
241
- rename_to: Type.Optional(Type.String({ description: "(optional) Move to this address, optionally with edits or metadata changes. Won't overwrite a live note; references aren't updated." })),
239
+ replace_all: Type.Optional(Type.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
240
+ rename_to: Type.Optional(Type.String({ description: "Move the page to another address. Never lands on top of a live page; nothing pointing at it follows." })),
242
241
  cwd: CWD_PARAMETER,
243
242
  }, { additionalProperties: false });
244
243
  function renderUpdateData(data) {
@@ -249,7 +248,7 @@ function renderUpdateData(data) {
249
248
  }
250
249
  export const notesUpdate = {
251
250
  name: "notes_update", label: "Notes update",
252
- description: `Change part of a note's body, policy (pinned/budget/readonly), origin, crumpled state, or address. A readonly note requires explicit readonly:false before any change, or in the same call. When things change, replace the stale part in place; don't just tack an update onto the bottom. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
251
+ description: "Work on a page you already have: cross out and rewrite lines, move it, pin it, lock it, give it more paper, crumple it. Keep every page true to now: wrong, stale, or no-longer-mattering lines get rewritten or struck where they stand. The page stays one page.",
253
252
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
254
253
  async execute(params, context, onChange) {
255
254
  try {
@@ -269,13 +268,13 @@ export const notesUpdate = {
269
268
  },
270
269
  render: (result) => renderOutcome(result, renderUpdateData),
271
270
  };
272
- export const notesReadParameters = Type.Object({ address: Type.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
271
+ export const notesReadParameters = Type.Object({ address: ADDRESS_PARAMETER, ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
273
272
  function renderReadData(data) {
274
273
  return withWarnings(`${renderIdentity(data)}\n${renderMetadata(data.metadata)}`, data) + `\n\n${renderTextWindow(data)}`;
275
274
  }
276
275
  export const notesRead = {
277
276
  name: "notes_read", label: "Notes read",
278
- description: `Read a note. ${ADDRESS_DESCRIPTION}`,
277
+ description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
279
278
  parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
280
279
  async execute(params, context) {
281
280
  try {
@@ -312,7 +311,7 @@ export function renderListData(data) {
312
311
  }
313
312
  export const notesList = {
314
313
  name: "notes_list", label: "Notes list",
315
- description: `List notes, newest first. Not pageable; \`more\` counts the rest. ${QUERY_NAMESPACES_DESCRIPTION} ${ADDRESS_DESCRIPTION}`,
314
+ description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile — narrow `glob`.",
316
315
  parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
317
316
  async execute(params, context) {
318
317
  try {
@@ -326,11 +325,11 @@ export const notesList = {
326
325
  },
327
326
  render: (result) => renderOutcome(result, renderListData),
328
327
  };
329
- export const notesSearchParameters = Type.Object({ query: Type.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default all) Max matching lines per note." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
328
+ export const notesSearchParameters = Type.Object({ query: Type.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "How many hit lines per page at most." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
330
329
  function renderSearchData(data) {
331
330
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
332
331
  for (const file of data.files) {
333
- lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
332
+ lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
334
333
  lines.push(...file.warnings.map(warning => ` ${warning}`));
335
334
  for (const match of file.matches)
336
335
  lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
@@ -341,6 +340,10 @@ function renderSearchData(data) {
341
340
  lines.push(`${namespace} could not be read`);
342
341
  return lines.join("\n");
343
342
  }
343
+ function keepMatches(file, count = file.matches.length) {
344
+ const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
345
+ return { ...file, matches: file.matches.slice(0, count), ...(more ? { more_matches: more } : {}) };
346
+ }
344
347
  /** A shortened match line still ends with a marker, so its own text says it was cut. */
345
348
  export const MATCH_SHORTENED_MARKER = " [truncated]";
346
349
  /** Prefer whole match lines; shorten the first line only if no whole line fits, and mark it. */
@@ -349,31 +352,29 @@ function fitSearchFile(file, fits) {
349
352
  let high = file.matches.length;
350
353
  while (low < high) {
351
354
  const mid = Math.ceil((low + high) / 2);
352
- if (fits({ ...file, matches: file.matches.slice(0, mid) }))
355
+ if (fits(keepMatches(file, mid)))
353
356
  low = mid;
354
357
  else
355
358
  high = mid - 1;
356
359
  }
357
- if (low > 0)
358
- return { ...file, matches: file.matches.slice(0, low) };
360
+ if (low > 0 || file.matches.length === 0)
361
+ return keepMatches(file, low);
359
362
  const first = file.matches[0];
360
- if (!first)
361
- return file;
362
- const withText = (text) => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
363
+ const withText = (text) => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
363
364
  return withText(prefixFit(first.text, text => fits(withText(text))));
364
365
  }
365
366
  export const notesSearch = {
366
367
  name: "notes_search", label: "Notes search",
367
- description: `Search note bodies for literal text, case-insensitive. Without a query, lists notes with no match lines. Returns matching lines with offsets for \`notes_read\`. Not pageable; \`more\` counts the rest. ${QUERY_NAMESPACES_DESCRIPTION} ${ADDRESS_DESCRIPTION}`,
368
+ description: "Run a finger down every page for some text, case doesn't matter. Returns the lines it hits and where they sit; no query just lists the pages. One pass; `more` counts pages left on the pile — narrow `glob`.",
368
369
  parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
369
370
  async execute(params, context) {
370
371
  try {
371
372
  const identity = notesIdentityForCall(context, params.cwd);
372
373
  const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
373
- const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
374
+ const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => keepMatches({
374
375
  ...listedFile(row, identity),
375
- matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
376
- }));
376
+ matches: row.matches.map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
377
+ }, params.max_matches_per_file));
377
378
  return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
378
379
  }
379
380
  catch (error) {
@@ -40,8 +40,8 @@ export const TextWindowSchema = Type.Object({
40
40
  * because `readTextWindow` already owns the defaults.
41
41
  */
42
42
  export const TextWindowRequestSchema = {
43
- offset_chars: Type.Optional(Type.Integer({ description: "(optional, default 0) Start offset in chars; negative counts from the end." })),
44
- max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${DEFAULT_READ_WINDOW_CHARS}) Max chars to return.` })),
43
+ offset_chars: Type.Optional(Type.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
44
+ max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." })),
45
45
  };
46
46
  /**
47
47
  * Read one code-point window of `text` and build the operation's data around it. `offset` and
@@ -2,7 +2,7 @@ import { Type } from "typebox";
2
2
  import { Errors } from "typebox/value";
3
3
  import { HistoryRoleSchema } from "../history/history.js";
4
4
  export const nullableString = (description) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
5
- export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
5
+ export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "Only these voices: user, assistant, tool, context. Without roles or query, tool and context runs fold into one line." }));
6
6
  /** First parameter violation; skip false subschemas so additionalProperties can name the field. */
7
7
  export function paramProblem(schema, params) {
8
8
  const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
@@ -13,4 +13,4 @@ export function paramProblem(schema, params) {
13
13
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
14
14
  }
15
15
  /** Search query parameter: one literal, or several literals combined with OR. */
16
- export const searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => Type.Union([Type.String(), Type.Array(Type.String())], { description });
16
+ export const searchQuery = (description = "Text to look for, or a list (any match). Leave it out to just list the pages.") => Type.Union([Type.String(), Type.Array(Type.String())], { description });
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { setTimeout as sleep } from "node:timers/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import test from "node:test";
@@ -50,6 +51,27 @@ test("Claude helper resolves foreign history without requiring a current append
50
51
  assert.equal(invalid.ok, false);
51
52
  assert.match(invalid.text, /invalid_session/);
52
53
  });
54
+ test("Claude history tools wait for the confirmed append, never substitute a persisted sibling", async (t) => {
55
+ const home = mkdtempSync(join(tmpdir(), "claude-history-lag-"));
56
+ t.after(() => rmSync(home, { recursive: true, force: true }));
57
+ const transcriptPath = join(home, "transcript.jsonl");
58
+ const rows = [user("root", null, "start"), assistant("sibling", "root", "sibling-only text")];
59
+ writeFileSync(transcriptPath, jsonl(rows));
60
+ const identity = { home, sessionId, cwd: home, agent: "claude", model: "claude" };
61
+ const history = { sessionId, transcriptPath, headUuid: "active" };
62
+ const options = { roots: { pi: null, claude: null, codex: null }, env: {} };
63
+ const invoke = (tool, params) => dispatch({ op: "tool", tool, params, identity, history }, options);
64
+ await assert.rejects(dispatch({ op: "history_state", identity, history }), /active head is not persisted/);
65
+ const delayedWrite = sleep(120).then(() => writeFileSync(transcriptPath, jsonl([...rows, assistant("active", "root", "confirmed active text")])));
66
+ const [list, read] = await Promise.all([invoke("history_list", {}), invoke("history_read", { session: `claude:${sessionId}`, seq: 3 }), delayedWrite]);
67
+ for (const outcome of [list, read]) {
68
+ assert.ok(outcome.ok, outcome.text);
69
+ assert.match(outcome.text, /confirmed active text/);
70
+ assert.doesNotMatch(outcome.text, /sibling-only text/);
71
+ }
72
+ history.headUuid = "never-written";
73
+ await assert.rejects(invoke("history_list", {}), /active head is not persisted/);
74
+ });
53
75
  test("Claude append and result arrival preserve call addresses and use the shared paired read", async () => {
54
76
  const rows = [user("u", null, "run tools"), assistant("a", "u", [{ type: "thinking", thinking: "private thought" }, { type: "text", text: "working" }, call("one"), call("two")])];
55
77
  const pending = project(rows, "a");
@@ -71,7 +71,7 @@ async function loadHookModule(t) {
71
71
  if (typeof matcherOrHandler === "function")
72
72
  on(event, matcherOrHandler);
73
73
  else
74
- on(event, ($, e, next) => Object.entries(matcherOrHandler).every(([key, value]) => e[key] === value) ? handler($, e, next) : next(e));
74
+ on(event, ($, e, next) => Object.entries(matcherOrHandler).every(([key, value]) => Array.isArray(value) ? value.includes(e[key]) : e[key] === value) ? handler($, e, next) : next(e));
75
75
  }) };
76
76
  }
77
77
  /** An engine that answers the hook by running the real helper against a throwaway notes home. */
@@ -1824,6 +1824,13 @@ test("Claude history keeps classic transcript_path across startup, confirms appe
1824
1824
  const handlers = new Map();
1825
1825
  (await loadHookModule(t)).register((event, handler) => handlers.set(event, handler));
1826
1826
  const invoke = (name, event = {}, result = {}) => handlers.get(name)(host, event, async () => result);
1827
+ const budgets = new Map();
1828
+ const run = host.process.run;
1829
+ host.process.run = (argv, init) => {
1830
+ const request = JSON.parse(init.stdin);
1831
+ budgets.set(request.tool ?? request.op, init?.timeoutMs);
1832
+ return run(argv, init);
1833
+ };
1827
1834
  const transcriptPath = join(home, "transcript.jsonl");
1828
1835
  const root = { type: "user", uuid: "root", parentUuid: null, sessionId: "hook-session", message: { role: "user", content: "old request" } };
1829
1836
  const attachment = { type: "attachment", uuid: "startup", parentUuid: "root", sessionId: "hook-session", rendered: [{ content: [{ type: "text", text: "startup injection" }] }] };
@@ -1858,6 +1865,11 @@ test("Claude history keeps classic transcript_path across startup, confirms appe
1858
1865
  const switched = await call("history_list");
1859
1866
  assert.match(switched.result, /another branch/);
1860
1867
  assert.doesNotMatch(switched.result, /startup injection/);
1868
+ await call("notes_list");
1869
+ assert.equal(budgets.get("history_list"), 120_000);
1870
+ assert.equal(budgets.get("history_read"), 120_000);
1871
+ assert.equal(budgets.get("notes_list"), 10_000);
1872
+ assert.equal(budgets.get("history_state"), 10_000);
1861
1873
  });
1862
1874
  test("Claude history without a documented path refuses honestly and keeps notes usable", async (t) => {
1863
1875
  const home = mkdtempSync(join(tmpdir(), "claude-no-history-path-"));
@@ -8,7 +8,8 @@ import { tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { resolveProjectNamespace } from "../src/notes/project-namespace.js";
10
10
  import { WINDOW_IDENTITY_CLOSE_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
11
- import { notesRead } from "../src/tools/notes.js";
11
+ import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../src/tools/notes.js";
12
+ import { historyList, historyRead } from "../src/tools/history.js";
12
13
  import { notesToolContext } from "../src/tools/notes-context.js";
13
14
  import { success } from "../src/result.js";
14
15
  import { createNotesStore } from "../src/notes/index.js";
@@ -24,6 +25,17 @@ function prompt(text) { return createUserMessage({ content: [{ type: "text", tex
24
25
  async function run(agent, text) { agent.followup(prompt(text)); await agent.whenIdle(); }
25
26
  function system(request) { return typeof request.system === "string" ? request.system : request.system?.map((block) => block.text).join("\n") ?? ""; }
26
27
  function code(expected) { return (error) => error?.code === expected; }
28
+ test("dsh preserves shared tool and parameter descriptions verbatim", async (t) => {
29
+ const { ctx } = await dshFixture(t);
30
+ for (const operation of [notesWrite, notesUpdate, notesRead, notesList, notesSearch, historyList, historyRead]) {
31
+ const registered = ctx.tools.get(operation.name);
32
+ assert.equal(registered.description, operation.description);
33
+ const properties = registered.parameters.properties;
34
+ for (const [name, parameter] of Object.entries(operation.parameters.properties)) {
35
+ assert.equal(properties[name].description, parameter.description, `${operation.name}.${name}`);
36
+ }
37
+ }
38
+ });
27
39
  // Critical lifecycle tests exercise the actual loop, DeepSeek HTTP adapter, tool registry,
28
40
  // token meter and SQLite query service. Only the provider is a scripted Messages server.
29
41
  test("dsh registered tools query other DSH sessions and foreign Pi files through the same session surface", async (t) => {
@@ -35,6 +35,11 @@ test("only EOF proves a miss, while errors after tokens or a fallback still prop
35
35
  }
36
36
  assert.equal(await createHistoryPrefilter(["needle"])(late()), true);
37
37
  assert.equal(finished, true);
38
+ finished = false;
39
+ assert.equal(await createHistoryPrefilter(["needle"])(late(), false, true), true);
40
+ assert.equal(finished, false, "a plain-file hit leaves the rest to the strict decoder");
41
+ assert.equal(await createHistoryPrefilter(["absentword"])(late(), false, true), false);
42
+ assert.equal(finished, true, "even the early-hit path must read to EOF to prove a miss");
38
43
  async function* broken() { yield Buffer.from("needle"); throw new Error("read failed"); }
39
44
  for (const queries of [["absentword"], ["needle"], ["😀"]])
40
45
  await assert.rejects(createHistoryPrefilter(queries)(broken()), /read failed/);
@@ -85,7 +85,7 @@ test("tools set policy, validate values, and visibly report effective policy and
85
85
  const updated = await notesUpdate.execute({ address: "custom", readonly: false, edits: [{ oldText: "😀".repeat(2), newText: "😀".repeat(3) }] }, context);
86
86
  assert.equal(Check(notesUpdate.outputSchema, wireResult(updated)), true);
87
87
  assert.equal(data(updated).warnings.length, 1);
88
- assert.match(notesUpdate.render(updated), /3 Unicode code points, over budget 2/);
88
+ assert.match(notesUpdate.render(updated), /3 Unicode code points, over budget 2 — boil it down\./);
89
89
  assert.equal((await notes.read("custom")).body, "😀".repeat(3), "over budget saves the entire body");
90
90
  const read = await notesRead.execute({ address: "custom", max_chars: 10 }, context);
91
91
  assert.equal(Check(notesRead.outputSchema, wireResult(read)), true);
@@ -102,6 +102,11 @@ test("tools set policy, validate values, and visibly report effective policy and
102
102
  assert.equal(data(search).files[0].budget, 2);
103
103
  assert.match(notesSearch.render(search), /pinned true \| budget 2 \| readonly false/);
104
104
  assert.match(notesSearch.render(search), /Warning: note body is 3/);
105
+ const overflow = await notesWrite.execute({ address: "overflow", content: "😀".repeat(3), budget: 2 }, context);
106
+ for (const warnings of [data(overflow).warnings, data(read).warnings]) {
107
+ assert.ok(warnings.length > 0);
108
+ assert.ok(warnings.every(warning => warning.endsWith("— boil it down.")));
109
+ }
105
110
  const larger = await notesUpdate.execute({ address: "custom", budget: 4, pinned: false }, context);
106
111
  assert.deepEqual(data(larger).warnings, []);
107
112
  assert.equal(data(larger).change_kind, "metadata");
@@ -334,6 +334,33 @@ test("an over-budget note search match is a marked prefix with an honest line ad
334
334
  }
335
335
  assert.ok(parts.join("").endsWith(hugeLine), "resuming across pages reconstructs the matched body line");
336
336
  });
337
+ for (const [label, padding, cap] of [
338
+ ["match cap", 0, 2],
339
+ ["output budget", Math.floor(TOOL_OUTPUT_MAX_BYTES / 3), undefined],
340
+ ["both limits", Math.floor(TOOL_OUTPUT_MAX_BYTES / 3), 6],
341
+ ["shortened first line", TOOL_OUTPUT_MAX_BYTES * 2, undefined],
342
+ ]) {
343
+ test(`notes_search reports dropped lines after ${label}`, async () => {
344
+ const session = manager();
345
+ const captured = makeExtension(session);
346
+ const ctx = context(session);
347
+ const lines = Array.from({ length: padding > TOOL_OUTPUT_MAX_BYTES ? 3 : 8 }, (_, index) => `needle ${index}${"y".repeat(padding)}`);
348
+ resultData(await call(captured, "notes_write", { address: "matches.md", content: lines.join("\n") }, ctx));
349
+ const raw = await call(captured, "notes_search", { query: "needle", max_matches_per_file: cap }, ctx);
350
+ assertWithinBudget(raw, label);
351
+ const found = resultData(raw);
352
+ assert.equal(found.more, 0, "line omissions are separate from omitted pages");
353
+ const [file] = found.files;
354
+ assert.ok(file);
355
+ assert.ok(file.matches.length > 0 && file.matches.length < lines.length);
356
+ if (cap !== undefined)
357
+ assert.ok(file.matches.length <= cap);
358
+ if (padding > 0)
359
+ assert.ok(file.matches.length < (cap ?? lines.length), "the output budget also drops lines");
360
+ assert.equal(file.more_matches, lines.length - file.matches.length);
361
+ assert.ok(textOf(raw).includes(`${file.more_matches} more lines`));
362
+ });
363
+ }
337
364
  test("notes_search ignores case, treats queries literally, and preserves original Unicode offsets", async () => {
338
365
  const session = manager();
339
366
  const captured = makeExtension(session);
@@ -342,6 +369,7 @@ test("notes_search ignores case, treats queries literally, and preserves origina
342
369
  const found = resultData(await call(captured, "notes_search", { query: ["missing", "needle.*"], glob: "case-match.md" }, ctx));
343
370
  assert.equal(found.files.length, 1);
344
371
  assert.equal(found.files[0].matches.length, 1);
372
+ assert.equal(found.files[0].more_matches, undefined);
345
373
  const hit = found.files[0];
346
374
  const read = resultRead(await call(captured, "notes_read", { address: hit.address, offset_chars: hit.matches[0].offset_chars }, ctx));
347
375
  assert.equal(read.content, "NeEdLe.* tail");
@@ -34,7 +34,9 @@ The notes tools also serve subagent calls, using the same session identity and s
34
34
 
35
35
  Explicit `session` selectors use the [local cross-harness corpus](history-sessions.md), including Pi/Claude/Codex files, without needing the current main transcript to have a head yet. Explicitly selecting the current Claude session still uses its strict live binding. Offline Claude targets prefer non-attachment graph leaves when available, then select the last remaining leaf in transcript order; no leaves still refuses. The persisted Claude decoder is shared under `src/history/claude.ts`; its plugin entry remains in `plugins/claude/src/history.ts`.
36
36
 
37
- 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.
37
+ 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. History tools wait briefly (up to one second of polling) for the exact confirmed UUID, retrying the read only when the file changes. If it still isn't on disk they refuse rather than switch branches. The internal `history_state` check for reset bookkeeping does not wait. Session end clears the binding; a new classic start rebinds it.
38
+
39
+ History tools have a two-minute helper deadline so a cold search can scan large archives. Notes, boot and reset helper calls keep the ten-second deadline.
38
40
 
39
41
  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.
40
42
 
@@ -27,7 +27,7 @@ history_list({ session: "*", query: ["deployment", "rollback"], limit: 20 })
27
27
  history_list({ session: "codex:*", query: "migration", roles: ["tool"], since: "2026-10-01" })
28
28
  ```
29
29
 
30
- - With a non-empty `query`, matching is literal, case-insensitive, and ORs a list of texts, as in one-session search. Local files are conservatively pre-filtered before full decoding: JSON escapes, Unicode case folding, generated event text and inherited Codex history must not lose hits. Uncertain cases use the full decoder.
30
+ - With a non-empty `query`, matching is literal, case-insensitive, and ORs a list of texts, as in one-session search. Local files are conservatively pre-filtered before full decoding: JSON escapes, Unicode case folding, generated event text and inherited Codex history must not lose hits. Uncertain cases use the full decoder. A possible hit in a Pi or Claude file stops the prefilter early: the strict decoder will read and validate the file next.
31
31
  - Without `query` (including empty strings/lists or lists containing only empty entries), return a recent-sessions overview. Sessions are considered newest-modified first, or oldest-modified first with `from: "oldest"`; loading stops once `limit` sessions (default 20) produce a representative. Apply `roles`, `since` and `until` before choosing each representative: without roles, prefer the first visible user event, falling back to the latest visible dialogue event or latest event of any role; with roles, choose the latest matching visible event. Sort the chosen representatives by event time, oldest first. There are no folded rows.
32
32
  - `before_seq` and `after_seq` refuse with `invalid_bounds`: seqs from different sessions cannot define a common range.
33
33
  - `history_read` refuses wildcard selectors with `invalid_session`; take a specific `session` and `seq` from a search hit instead.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.59.0",
3
+ "version": "0.59.2",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.59.0",
3
+ "version": "0.59.1",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"