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
@@ -1,8 +1,13 @@
1
1
  /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
- import { readFile } from "node:fs/promises";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { setTimeout as sleep } from "node:timers/promises";
3
4
  import { isDeepStrictEqual } from "node:util";
4
5
  import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
5
6
 
7
+ class UnpersistedClaudeHead extends Error {
8
+ constructor() { super("Claude history active head is not persisted yet; retry after the transcript write"); }
9
+ }
10
+
6
11
  type Row = Record<string, unknown>;
7
12
  type WindowPosition = { ordinal: number } | { unknownAncestor: string };
8
13
  type Version = { row: Row; ancestorUuid?: string; ancestor?: Version; position?: WindowPosition };
@@ -180,7 +185,7 @@ function claudeHistoryFromRows(rows: Row[], source: Omit<ClaudeHistorySource, "t
180
185
  return version.position!;
181
186
  }
182
187
  if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
183
- if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
188
+ if (!nodes.has(source.headUuid)) throw new UnpersistedClaudeHead();
184
189
 
185
190
  // The inference tree uses the latest rewritten parents. At a compact boundary the logical
186
191
  // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
@@ -299,7 +304,29 @@ export function offlineClaudeHistoryFromJsonl(text: string, sessionId: string):
299
304
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
300
305
  }
301
306
 
302
- export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
307
+ export async function readClaudeHistory(source: ClaudeHistorySource, { waitForHead = false } = {}): Promise<ClaudeHistoryProjection> {
303
308
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
304
- return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
309
+ const snapshot = { ...source };
310
+ const read = async () => claudeHistoryFromJsonl(await readFile(snapshot.transcriptPath, "utf8"), snapshot);
311
+ if (!waitForHead || !snapshot.headUuid) return read();
312
+ const revision = async () => {
313
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot.transcriptPath, { bigint: true });
314
+ return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
315
+ };
316
+ let seen = await revision();
317
+ try { return await read(); }
318
+ catch (error) {
319
+ if (!(error instanceof UnpersistedClaudeHead)) throw error;
320
+ // A kept append can reach the tool before its disk write. Only retry that same
321
+ // head, and only reparse on file changes. Never fall back to an offline leaf.
322
+ for (const delay of [50, 100, 200, 300, 350]) {
323
+ await sleep(delay);
324
+ const current = await revision();
325
+ if (current === seen) continue;
326
+ seen = current;
327
+ try { return await read(); }
328
+ catch (retry) { if (!(retry instanceof UnpersistedClaudeHead)) throw retry; }
329
+ }
330
+ throw error;
331
+ }
305
332
  }
@@ -13,7 +13,7 @@ const PRESENTATION = `Codex unknown arguments not recorded output nested calls c
13
13
  FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
14
14
  the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
15
15
  const HISTORY_BASE = '"history_base"';
16
- export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
16
+ export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean, stopOnHit?: boolean) => Promise<boolean>;
17
17
 
18
18
  /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
19
19
  export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter {
@@ -27,7 +27,7 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
27
27
  }));
28
28
  // No safe tokens (or generated text alone) cannot prove a miss.
29
29
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
30
- return async (chunks, codex = false) => {
30
+ return async (chunks, codex = false, stopOnHit = false) => {
31
31
  const decoder = new StringDecoder("utf8");
32
32
  const seen = alternatives.map((tokens) => tokens.map(() => false));
33
33
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
@@ -55,7 +55,10 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
55
55
  rawTail = raw.slice(-overlap);
56
56
  normalizedTail = normalized.slice(-overlap);
57
57
  };
58
- for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
58
+ for await (const chunk of chunks) {
59
+ if (!possible) scan(decoder.write(chunk));
60
+ if (possible && stopOnHit) return true;
61
+ }
59
62
  if (!possible) scan(decoder.end(), true);
60
63
  return possible;
61
64
  };
@@ -63,12 +66,13 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
63
66
 
64
67
  /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
65
68
  export async function historyFileMayMatch(path: string, prefilter: HistoryPrefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity): Promise<boolean> {
66
- if (codex) {
67
- const info = await stat(path);
68
- if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
69
- }
70
- // Native Codex compression is zstd; no decoded file or full Buffer is materialized.
71
- const compressed = codex && path.endsWith(".jsonl.zst");
69
+ // Plain Pi/Claude files will be read and validated by the strict decoder on a possible
70
+ // hit. Don't drain a potentially huge file just to read it from the beginning again.
71
+ if (!codex) return prefilter(createReadStream(path), false, true);
72
+ const info = await stat(path);
73
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
74
+ // Native Codex compression is zstd; scan through EOF to enforce the decoded size limit.
75
+ const compressed = path.endsWith(".jsonl.zst");
72
76
  if (compressed && typeof zlib.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
73
77
  const input = createReadStream(path);
74
78
  const consume = async (chunks: AsyncIterable<Buffer>) => {
@@ -4,7 +4,7 @@ import { assertVirtualPath, isSessionId, SLUG_PATTERN, type Scope } from "./path
4
4
 
5
5
  export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
- export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> and @sessions/<id>/<path> read named notebooks.";
7
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path>, @sessions/<id>/<path>, @agents/<name>/<path>, and @models/<name>/<path> read named notebooks.";
8
8
 
9
9
  /** The one namespace-head vocabulary: the scope each public `@head` names, and the directory family a head with `dir` lists. */
10
10
  export const NAMESPACE_HEADS: ReadonlyMap<string, { readonly scope: Scope; readonly dir?: "sessions" | "project" | "agents" | "models" }> = new Map([
@@ -34,7 +34,7 @@ export function pinnedPageOrder(path: string): number {
34
34
 
35
35
  export function noteBudgetWarnings(body: string, policy: NotePolicy): string[] {
36
36
  const count = Array.from(body).length;
37
- return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}; the full body is kept.`] : [];
37
+ return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} — boil it down.`] : [];
38
38
  }
39
39
 
40
40
  export function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void {
@@ -53,7 +53,7 @@ export function dreamingIdentity(identity: NotesIdentity, state: DreamState): No
53
53
  const NOT_DREAMING = "No dream is open; call dream_begin first.";
54
54
 
55
55
  export const dreamBeginParameters = Type.Object({
56
- project: Type.Optional(Type.String({ description: "(optional, default this project) Project name, as in @projects/<name>/." })),
56
+ project: Type.Optional(Type.String({ description: "Which project's pages; leave it out for this one." })),
57
57
  }, { additionalProperties: false });
58
58
 
59
59
  export const DreamBeginDataSchema = Type.Object({
@@ -69,7 +69,7 @@ function renderBeginData(data: DreamBeginData): string {
69
69
 
70
70
  export const dreamBegin = {
71
71
  name: "dream_begin", label: "Dream begin",
72
- description: "Dream: open one project's notes for consolidation, one project at a time. Lists its @projects/<name>/ notes and every session note born in it, crumpled ones included. Until dream_end, notes_write/notes_update can edit those addresses and reads leave no access stamp. Holds the notes home's dream lock through dream_end so Git audits cannot interleave, and commits a baseline of the notes home.",
72
+ description: "Spread one project's pages across the table — its project shelf, every session page born there, crumpled balls included. Until `dream_end` your pen works on all of them; other sessions' pages can be rewritten, not added to.",
73
73
  parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
74
74
  async execute(params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamBeginData>> {
75
75
  if (state.project !== undefined || state.pending !== undefined) {
@@ -123,13 +123,13 @@ export const dreamBegin = {
123
123
  render: (result: Outcome<DreamBeginData>): string => renderOutcome(result, renderBeginData),
124
124
  } as const;
125
125
 
126
- export const dreamForgetParameters = Type.Object({ address: Type.String() }, { additionalProperties: false });
126
+ export const dreamForgetParameters = Type.Object({ address: Type.String({ description: "Which crumpled page goes in the bin." }) }, { additionalProperties: false });
127
127
  export const DreamForgetDataSchema = Type.Object({ ...NoteIdentitySchema }, { additionalProperties: false });
128
128
  export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
129
129
 
130
130
  export const dreamForget = {
131
131
  name: "dream_forget", label: "Dream forget",
132
- description: "Dream: permanently delete one crumpled note in the project being dreamed over, or in @human/, @self/, @model/. Crumple it first; live notes refuse.",
132
+ description: "Throw a crumpled page in the bin for good. Only crumpled pages go.",
133
133
  parameters: dreamForgetParameters, outputSchema: resultSchema(DreamForgetDataSchema),
134
134
  async execute(params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamForgetData>> {
135
135
  if (state.project === undefined) return failure("not_dreaming", NOT_DREAMING);
@@ -148,7 +148,7 @@ export type DreamEndData = Static<typeof DreamEndDataSchema>;
148
148
 
149
149
  export const dreamEnd = {
150
150
  name: "dream_end", label: "Dream end",
151
- description: "Dream: close the open dream. Commits the dream's changes to the notes home's Git and releases the lock; the project's notes are read-only again and reads stamp access again.",
151
+ description: "Stack the pages, file them, close the drawer.",
152
152
  parameters: dreamEndParameters, outputSchema: resultSchema(DreamEndDataSchema),
153
153
  async execute(_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamEndData>> {
154
154
  const project = state.project;
@@ -92,25 +92,23 @@ function pageOutcome(result: HistoryPageResult): Outcome<HistoryPage> {
92
92
 
93
93
  /* ------------------------------------------------------------------ history_list */
94
94
 
95
- const sessionParameter = Type.Optional(Type.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
96
-
97
95
  export const historyListParameters = Type.Object({
98
- session: sessionParameter,
99
- query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
96
+ session: Type.Optional(Type.String({ minLength: 1, description: "Whose record: a session ID or prefix (pi:, claude:, codex:, dsh: allowed). Leave it out for this one. `*` means every recent session." })),
97
+ query: Type.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
100
98
  roles: historyRoles(),
101
- before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
102
- after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
103
- since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
104
- until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
105
- from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional) Which end `limit` counts from: newest or oldest (default oldest when `after_seq` is set, else newest). Results stay oldest first." })),
106
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
107
- max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
99
+ before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "Only entries before this seq." })),
100
+ after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "Only entries after this seq; 0 starts from the first page." })),
101
+ since: Type.Optional(Type.String({ minLength: 1, description: "Only entries at or after this time (ISO 8601; UTC without an offset)." })),
102
+ until: Type.Optional(Type.String({ minLength: 1, description: "Only entries before this time (ISO 8601; UTC without an offset)." })),
103
+ from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "Which end `limit` counts from: newest or oldest. Entries still read oldest first." })),
104
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "How many entries per page; folded runs don't count." })),
105
+ max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." })),
108
106
  }, { additionalProperties: false });
109
107
 
110
108
  export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryContext, HistoryTextWrapper?]> = {
111
109
  name: "history_list",
112
110
  label: "History list items",
113
- description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * to browse recent sessions across local harnesses (add query to search). Read one in full with `history_read`.",
111
+ description: "Flip back through the record, a page at a time. Another session: its ID. `*` pulls every recent session off the shelf; add `query` to search them.",
114
112
  parameters: historyListParameters,
115
113
  outputSchema: resultSchema(HistoryPageSchema),
116
114
  async execute(params, context, wrapText = plainText) {
@@ -162,12 +160,12 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
162
160
 
163
161
  /* ------------------------------------------------------------------ history_read */
164
162
 
165
- export const historyReadParameters = Type.Object({ session: sessionParameter, seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`. Pass its session too when present." }), ...TextWindowRequestSchema }, { additionalProperties: false });
163
+ export const historyReadParameters = Type.Object({ session: Type.Optional(Type.String({ minLength: 1, description: "Whose record: a session ID or prefix. Leave it out for this one." })), seq: Type.Integer({ minimum: 1, description: "Which entry, by its seq from `history_list`; bring its session along if it had one." }), ...TextWindowRequestSchema }, { additionalProperties: false });
166
164
 
167
165
  export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryContext, HistoryTextWrapper?]> = {
168
166
  name: "history_read",
169
167
  label: "History read item",
170
- description: "Read one event in full: tool arguments, output, and nested calls.",
168
+ description: "Open one entry: what was called, what came back, the calls nested inside. Long entries come in slices; follow `next_offset_chars`.",
171
169
  parameters: historyReadParameters,
172
170
  outputSchema: resultSchema(HistoryReadDataSchema),
173
171
  async execute(params, context, wrapText = plainText) {
@@ -15,12 +15,12 @@ import { notesIdentityForCall, type NotesToolContext } from "./notes-context.js"
15
15
 
16
16
  const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")] as const;
17
17
  const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
18
- description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self.",
18
+ description: "Whose handwriting: user, self, or external. Leave it out to keep what's there.",
19
19
  }));
20
20
  const POLICY_PARAMETERS = {
21
- 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." })),
22
- 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." })),
23
- 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." })),
21
+ 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." })),
22
+ 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." })),
23
+ readonly: Type.Optional(Type.Boolean({ description: "A paperclip that keeps your own hands off. `false` takes it off — same call is fine." })),
24
24
  };
25
25
  const PolicySchema = {
26
26
  pinned: Type.Boolean(), budget: Type.Integer(), readonly: Type.Boolean(),
@@ -36,13 +36,12 @@ function withWarnings(text: string, data: { warnings: string[] }): string {
36
36
  return [text, ...data.warnings].join("\n");
37
37
  }
38
38
 
39
- const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
40
- const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
41
- const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
42
- const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses, or @default for the current notebooks.");
43
- 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." }));
44
- const QUERY_NAMESPACES_DESCRIPTION = "Omit `glob` or use `@default` for this session and current shared notebooks; `**` searches all notebooks, `@sessions/*/**` searches all sessions.";
45
- 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.";
39
+ 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." }));
40
+ const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "Only the crumpled balls." }));
41
+ const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "How many pages at most." }));
42
+ 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.");
43
+ const CWD_PARAMETER = Type.Optional(Type.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
44
+ 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." });
46
45
 
47
46
  /**
48
47
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
@@ -158,7 +157,7 @@ const MatchSchema = Type.Object({
158
157
 
159
158
  const SearchedFileSchema = Type.Object({
160
159
  ...ListedFileSchema.properties,
161
- matches: Type.Array(MatchSchema),
160
+ matches: Type.Array(MatchSchema), more_matches: Type.Optional(Type.Integer({ minimum: 1 })),
162
161
  }, { additionalProperties: false });
163
162
 
164
163
  export const SnapshotSchema = {
@@ -238,7 +237,7 @@ export function listedFile(row: Pick<NoteRow, "address" | "meta"> & { body?: str
238
237
  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 }) };
239
238
  }
240
239
 
241
- export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
240
+ export const notesWriteParameters = Type.Object({ address: ADDRESS_PARAMETER, content: Type.String({ description: "The whole page." }), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
242
241
 
243
242
  function renderWriteData(data: NotesWriteData): string {
244
243
  return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
@@ -246,7 +245,7 @@ function renderWriteData(data: NotesWriteData): string {
246
245
 
247
246
  export const notesWrite = {
248
247
  name: "notes_write", label: "Notes write",
249
- description: `Create a note, or overwrite its whole body. Name it for what it holds and when to use it. ${ADDRESS_DESCRIPTION}`,
248
+ 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.",
250
249
  parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
251
250
  async execute(params: Static<typeof notesWriteParameters>, context: NotesToolContext): Promise<Outcome<NotesWriteData>> {
252
251
  try {
@@ -259,13 +258,13 @@ export const notesWrite = {
259
258
  } as const;
260
259
 
261
260
  export const notesUpdateParameters = Type.Object({
262
- address: Type.String(),
263
- edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))),
261
+ address: ADDRESS_PARAMETER,
262
+ 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." })),
264
263
  origin: ORIGIN,
265
264
  ...POLICY_PARAMETERS,
266
265
  crumpled: CRUMPLED_PARAMETER,
267
- replace_all: Type.Optional(Type.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
268
- 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." })),
266
+ replace_all: Type.Optional(Type.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
267
+ 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." })),
269
268
  cwd: CWD_PARAMETER,
270
269
  }, { additionalProperties: false });
271
270
 
@@ -278,7 +277,7 @@ function renderUpdateData(data: NotesUpdateData): string {
278
277
 
279
278
  export const notesUpdate = {
280
279
  name: "notes_update", label: "Notes update",
281
- 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}`,
280
+ 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.",
282
281
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
283
282
  async execute(params: Static<typeof notesUpdateParameters>, context: NotesToolContext, onChange?: (change: NoteChange) => void): Promise<Outcome<NotesUpdateData>> {
284
283
  try {
@@ -296,7 +295,7 @@ export const notesUpdate = {
296
295
  render: (result: Outcome<NotesUpdateData>): string => renderOutcome(result, renderUpdateData),
297
296
  } as const;
298
297
 
299
- export const notesReadParameters = Type.Object({ address: Type.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
298
+ export const notesReadParameters = Type.Object({ address: ADDRESS_PARAMETER, ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
300
299
 
301
300
  function renderReadData(data: NotesReadData): string {
302
301
  return withWarnings(`${renderIdentity(data)}\n${renderMetadata(data.metadata)}`, data) + `\n\n${renderTextWindow(data)}`;
@@ -304,7 +303,7 @@ function renderReadData(data: NotesReadData): string {
304
303
 
305
304
  export const notesRead = {
306
305
  name: "notes_read", label: "Notes read",
307
- description: `Read a note. ${ADDRESS_DESCRIPTION}`,
306
+ description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
308
307
  parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
309
308
  async execute(params: Static<typeof notesReadParameters>, context: NotesToolContext): Promise<Outcome<NotesReadData>> {
310
309
  try {
@@ -337,7 +336,7 @@ export function renderListData(data: Snapshot<NotesListData["files"][number] & {
337
336
 
338
337
  export const notesList = {
339
338
  name: "notes_list", label: "Notes list",
340
- description: `List notes, newest first. Not pageable; \`more\` counts the rest. ${QUERY_NAMESPACES_DESCRIPTION} ${ADDRESS_DESCRIPTION}`,
339
+ description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile — narrow `glob`.",
341
340
  parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
342
341
  async execute(params: Static<typeof notesListParameters>, context: NotesToolContext): Promise<Outcome<NotesListData>> {
343
342
  try {
@@ -349,12 +348,12 @@ export const notesList = {
349
348
  render: (result: Outcome<NotesListData>): string => renderOutcome(result, renderListData),
350
349
  } as const;
351
350
 
352
- 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 });
351
+ 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 });
353
352
 
354
353
  function renderSearchData(data: NotesSearchData): string {
355
354
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
356
355
  for (const file of data.files) {
357
- lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
356
+ 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` : ""}`);
358
357
  lines.push(...file.warnings.map(warning => ` ${warning}`));
359
358
  for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
360
359
  }
@@ -364,6 +363,10 @@ function renderSearchData(data: NotesSearchData): string {
364
363
  }
365
364
 
366
365
  type SearchFile = NotesSearchData["files"][number];
366
+ function keepMatches(file: SearchFile, count = file.matches.length): SearchFile {
367
+ const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
368
+ return { ...file, matches: file.matches.slice(0, count), ...(more ? { more_matches: more } : {}) };
369
+ }
367
370
 
368
371
  /** A shortened match line still ends with a marker, so its own text says it was cut. */
369
372
  export const MATCH_SHORTENED_MARKER = " [truncated]";
@@ -374,28 +377,27 @@ function fitSearchFile(file: SearchFile, fits: (candidate: SearchFile) => boolea
374
377
  let high = file.matches.length;
375
378
  while (low < high) {
376
379
  const mid = Math.ceil((low + high) / 2);
377
- if (fits({ ...file, matches: file.matches.slice(0, mid) })) low = mid;
380
+ if (fits(keepMatches(file, mid))) low = mid;
378
381
  else high = mid - 1;
379
382
  }
380
- if (low > 0) return { ...file, matches: file.matches.slice(0, low) };
381
- const first = file.matches[0];
382
- if (!first) return file;
383
- const withText = (text: string): SearchFile => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
383
+ if (low > 0 || file.matches.length === 0) return keepMatches(file, low);
384
+ const first = file.matches[0]!;
385
+ const withText = (text: string): SearchFile => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
384
386
  return withText(prefixFit(first.text, text => fits(withText(text))));
385
387
  }
386
388
 
387
389
  export const notesSearch = {
388
390
  name: "notes_search", label: "Notes search",
389
- 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}`,
391
+ 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`.",
390
392
  parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
391
393
  async execute(params: Static<typeof notesSearchParameters>, context: NotesToolContext): Promise<Outcome<NotesSearchData>> {
392
394
  try {
393
395
  const identity = notesIdentityForCall(context, params.cwd);
394
396
  const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
395
- const files: NotesSearchData["files"] = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
397
+ const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => keepMatches({
396
398
  ...listedFile(row, identity),
397
- matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
398
- }));
399
+ matches: row.matches.map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
400
+ }, params.max_matches_per_file));
399
401
  return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
400
402
  } catch (error) { return failureOf(error); }
401
403
  },
@@ -50,8 +50,8 @@ export type TextWindow = Static<typeof TextWindowSchema>;
50
50
  * because `readTextWindow` already owns the defaults.
51
51
  */
52
52
  export const TextWindowRequestSchema = {
53
- offset_chars: Type.Optional(Type.Integer({ description: "(optional, default 0) Start offset in chars; negative counts from the end." })),
54
- max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${DEFAULT_READ_WINDOW_CHARS}) Max chars to return.` })),
53
+ offset_chars: Type.Optional(Type.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
54
+ max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." })),
55
55
  };
56
56
 
57
57
  /**
@@ -2,7 +2,7 @@ import { Type, type TSchema } from "typebox";
2
2
  import { Errors } from "typebox/value";
3
3
  import { HistoryRoleSchema } from "../history/history.js";
4
4
  export const nullableString = (description?: string) => 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
 
7
7
  /** First parameter violation; skip false subschemas so additionalProperties can name the field. */
8
8
  export function paramProblem(schema: TSchema, params: unknown): string {
@@ -14,4 +14,4 @@ export function paramProblem(schema: TSchema, params: unknown): string {
14
14
  }
15
15
 
16
16
  /** Search query parameter: one literal, or several literals combined with OR. */
17
- 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 });
17
+ 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 });