notesoup 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +5 -2
  2. package/dist/src/boot/render.js +2 -2
  3. package/dist/src/boot/text.d.ts +0 -4
  4. package/dist/src/boot/text.js +18 -14
  5. package/dist/src/budget/policy.js +1 -1
  6. package/dist/src/budget/text.js +1 -1
  7. package/dist/src/dream/doctor.js +2 -1
  8. package/dist/src/dream/git.js +2 -1
  9. package/dist/src/dream/report.js +3 -2
  10. package/dist/src/error-message.d.ts +2 -0
  11. package/dist/src/error-message.js +4 -0
  12. package/dist/src/history/history.d.ts +23 -18
  13. package/dist/src/history/history.js +37 -20
  14. package/dist/src/history/query.d.ts +37 -49
  15. package/dist/src/history/query.js +114 -56
  16. package/dist/src/notes/store.d.ts +3 -4
  17. package/dist/src/notes/store.js +12 -16
  18. package/dist/src/pi/anchored.d.ts +16 -0
  19. package/dist/src/pi/anchored.js +55 -0
  20. package/dist/src/pi/budget.d.ts +1 -1
  21. package/dist/src/pi/budget.js +33 -28
  22. package/dist/src/pi/dream/cli.js +3 -2
  23. package/dist/src/pi/dream/runner.js +2 -1
  24. package/dist/src/pi/history-tools.d.ts +1 -1
  25. package/dist/src/pi/history-tools.js +2 -3
  26. package/dist/src/pi/reset/lifecycle.d.ts +1 -1
  27. package/dist/src/pi/reset/lifecycle.js +4 -3
  28. package/dist/src/pi/reset/text.d.ts +3 -3
  29. package/dist/src/pi/reset/text.js +2 -2
  30. package/dist/src/pi/runtime.js +12 -15
  31. package/dist/src/pi/thresholds.js +2 -1
  32. package/dist/src/pi/tool-names.d.ts +0 -4
  33. package/dist/src/pi/tool-names.js +0 -4
  34. package/dist/src/tools/history.d.ts +24 -33
  35. package/dist/src/tools/history.js +57 -98
  36. package/dist/src/tools/notes.d.ts +26 -58
  37. package/dist/src/tools/notes.js +85 -103
  38. package/dist/src/tools/result.d.ts +16 -13
  39. package/dist/src/tools/result.js +24 -50
  40. package/dist/src/tools/schema.d.ts +2 -2
  41. package/dist/src/tools/schema.js +3 -3
  42. package/dist/test/agent-loop.test.js +79 -29
  43. package/dist/test/boot.integration.test.js +6 -6
  44. package/dist/test/budget-settings.integration.test.js +9 -8
  45. package/dist/test/claude-mod.test.js +11 -11
  46. package/dist/test/dependencies.test.js +1 -1
  47. package/dist/test/helpers/extension.js +2 -3
  48. package/dist/test/history.integration.test.js +200 -123
  49. package/dist/test/host-neutral.test.js +32 -58
  50. package/dist/test/notes-library.test.js +8 -8
  51. package/dist/test/notes.integration.test.js +75 -57
  52. package/dist/test/notes.test.js +44 -42
  53. package/dist/test/reset-lifecycle.test.js +2 -2
  54. package/docs/architecture.md +3 -3
  55. package/docs/notes-library.md +6 -6
  56. package/docs/tool-results.md +15 -25
  57. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  58. package/mods/notesoup/dist/claude/helper.js +128 -179
  59. package/mods/notesoup/hooks/register.ts +19 -25
  60. package/mods/notesoup/playbook.md +10 -10
  61. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  62. package/package.json +1 -1
  63. package/playbook.md +10 -10
  64. package/skills/dream/SKILL.md +1 -1
  65. package/skills/memory/SKILL.md +11 -9
  66. package/src/boot/render.ts +2 -2
  67. package/src/boot/text.ts +18 -18
  68. package/src/budget/policy.ts +1 -1
  69. package/src/budget/text.ts +1 -1
  70. package/src/dream/doctor.ts +2 -1
  71. package/src/dream/git.ts +2 -1
  72. package/src/dream/report.ts +3 -2
  73. package/src/error-message.ts +4 -0
  74. package/src/history/history.ts +36 -20
  75. package/src/history/query.ts +130 -55
  76. package/src/notes/store.ts +15 -18
  77. package/src/pi/anchored.ts +62 -0
  78. package/src/pi/budget.ts +27 -26
  79. package/src/pi/dream/cli.ts +3 -2
  80. package/src/pi/dream/runner.ts +2 -1
  81. package/src/pi/history-tools.ts +2 -3
  82. package/src/pi/reset/lifecycle.ts +5 -4
  83. package/src/pi/reset/text.ts +2 -2
  84. package/src/pi/runtime.ts +12 -15
  85. package/src/pi/thresholds.ts +2 -1
  86. package/src/pi/tool-names.ts +0 -4
  87. package/src/tools/history.ts +61 -100
  88. package/src/tools/notes.ts +84 -97
  89. package/src/tools/result.ts +24 -49
  90. package/src/tools/schema.ts +3 -3
  91. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -2,45 +2,30 @@ import { Type } from "typebox";
2
2
  import { localIso } from "../notes/frontmatter.js";
3
3
  import { isFilesystemError } from "../notes/fs-error.js";
4
4
  import { createNotesStore, NoteError, noteIdentity } from "../notes/index.js";
5
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit } from "./output.js";
6
- import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowSchema } from "./result.js";
5
+ import { prefixFit } from "./output.js";
6
+ import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
7
7
  import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
8
8
  const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")];
9
9
  const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
10
- description: "Content source: user, self (default), or external.",
10
+ description: "(optional, default self) Who wrote it: user, self, or external.",
11
11
  }));
12
- const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "true crumples (archives) the note: hidden from list/search, still readable by address; false restores it." }));
13
- const WASTEBASKET_PARAMETER = Type.Optional(Type.Boolean({ description: "true lists only crumpled notes instead of live ones." }));
14
- const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "Max files (default: as many as fit the output budget)." }));
15
- const ADDRESS_DESCRIPTION = "Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
12
+ const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
13
+ const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
14
+ const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
15
+ const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
16
+ const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
16
17
  /** The one receipt field a caller cannot derive from the address itself. */
17
18
  function projectKeyField(scope, projectKey) {
18
19
  return scope === "project" ? { project_key: projectKey } : {};
19
20
  }
20
- const MAX_ERROR_LINE_FACTS = 20;
21
21
  /**
22
- * Typed refusal. Edit locations keep their precise line/edit facts in `details`.
22
+ * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
23
23
  * Convert expected refusals; unexpected errors propagate unchanged.
24
24
  */
25
25
  function failureOf(error) {
26
- if (error instanceof NoteError) {
27
- const details = {};
28
- let message = error.message;
29
- if (error.lineNumbers) {
30
- if (error.lineNumbers.length > MAX_ERROR_LINE_FACTS) {
31
- details.line_numbers = error.lineNumbers.slice(0, MAX_ERROR_LINE_FACTS);
32
- details.line_numbers_total = error.lineNumbers.length;
33
- message = `${message} (this refusal names ${MAX_ERROR_LINE_FACTS} of ${error.lineNumbers.length} match lines; the note is unchanged)`;
34
- }
35
- else {
36
- details.line_numbers = error.lineNumbers;
37
- }
38
- }
39
- if (error.editIndex !== undefined)
40
- details.edit_index = error.editIndex;
41
- return failure(error.code, message, Object.keys(details).length > 0 ? details : undefined);
42
- }
43
- // Address, pattern, and query guards raise declared types; nothing else is converted.
26
+ if (error instanceof NoteError)
27
+ return failure(error.code, error.message);
28
+ // Address, glob, and query guards raise declared types; nothing else is converted.
44
29
  if (error instanceof InvalidQueryError)
45
30
  return failure("invalid_query", error.message);
46
31
  if (isFilesystemError(error))
@@ -52,9 +37,11 @@ function byRecent(a, b) {
52
37
  }
53
38
  /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
54
39
  const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
55
- /** One unrecognized entry, and all of them together, are bounded; omissions are counted, never listed. */
40
+ /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
56
41
  export const MAX_METADATA_ENTRY_BYTES = 1024;
57
- const MAX_METADATA_EXTRA_BYTES = 2048;
42
+ const MAX_METADATA_VERBATIM_BYTES = 2048;
43
+ /** An extra value that cannot be carried is named in place, never silently dropped. */
44
+ export const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
58
45
  /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
59
46
  function extraEntryBytes(key, value) {
60
47
  return structuredBytes(key) + 1 + structuredBytes(value);
@@ -66,27 +53,28 @@ export const NoteMetadataSchema = Type.Object({
66
53
  crumpled_at: Type.Optional(Type.String()),
67
54
  project: Type.Optional(Type.String()),
68
55
  extra: Type.Record(Type.String(), Type.Unknown()),
69
- /** Values left in the file but too large to show, summarized so the summary cannot grow. */
70
- omitted_extra: Type.Optional(Type.Object({ keys: Type.Integer(), bytes: Type.Integer() })),
71
- });
72
- /** Normalize known metadata and bound extras without partially serializing their values. */
56
+ }, { additionalProperties: false });
57
+ /** Normalize known metadata and bound extras, naming an oversized value instead of hiding it. */
73
58
  function noteMetadata(meta) {
74
59
  const extra = {};
75
- let extraBytes = 0;
76
- let omittedKeys = 0;
77
- let omittedBytes = 0;
60
+ let verbatimBytes = 0;
61
+ const put = (key, value) => {
62
+ // defineProperty keeps a hand-written `__proto__` key as ordinary data.
63
+ Object.defineProperty(extra, key, { value, enumerable: true, writable: true, configurable: true });
64
+ };
78
65
  for (const [key, value] of Object.entries(meta)) {
79
66
  if (NORMALIZED_META_KEYS.has(key) || value === undefined)
80
67
  continue;
81
- const bytes = extraEntryBytes(key, value);
82
- if (bytes > MAX_METADATA_ENTRY_BYTES || extraBytes + bytes > MAX_METADATA_EXTRA_BYTES) {
83
- omittedKeys++;
84
- omittedBytes += bytes;
68
+ // A key too large to carry cannot be named at all; an oversized value is named in place.
69
+ if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES)
70
+ continue;
71
+ const entryBytes = extraEntryBytes(key, value);
72
+ if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
73
+ put(key, TOO_LARGE_EXTRA_VALUE);
85
74
  continue;
86
75
  }
87
- extraBytes += bytes;
88
- // defineProperty keeps a hand-written `__proto__` key as ordinary data.
89
- Object.defineProperty(extra, key, { value, enumerable: true, writable: true, configurable: true });
76
+ verbatimBytes += entryBytes;
77
+ put(key, value);
90
78
  }
91
79
  return {
92
80
  origin: meta.origin,
@@ -95,7 +83,6 @@ function noteMetadata(meta) {
95
83
  ...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
96
84
  ...(typeof meta.project === "string" ? { project: meta.project } : {}),
97
85
  extra,
98
- ...(omittedKeys > 0 ? { omitted_extra: { keys: omittedKeys, bytes: omittedBytes } } : {}),
99
86
  };
100
87
  }
101
88
  function renderMetadata(metadata) {
@@ -109,8 +96,6 @@ function renderMetadata(metadata) {
109
96
  const extra = Object.keys(metadata.extra);
110
97
  if (extra.length > 0)
111
98
  fields.push(`extra ${JSON.stringify(metadata.extra)}`);
112
- if (metadata.omitted_extra !== undefined)
113
- fields.push(`${metadata.omitted_extra.keys} more metadata values (${metadata.omitted_extra.bytes} bytes) are in the note file but too large to show`);
114
99
  return fields.join(" | ");
115
100
  }
116
101
  /** Address plus project key in one line; the project key never replaces the address. */
@@ -122,56 +107,50 @@ const ListedFileSchema = Type.Object({
122
107
  project_key: Type.Optional(Type.String()),
123
108
  updated_at: Type.String(),
124
109
  crumpled_at: Type.Optional(Type.String()),
125
- });
110
+ }, { additionalProperties: false });
126
111
  const MatchSchema = Type.Object({
127
112
  line: Type.Integer(),
128
113
  text: Type.String(),
129
- truncated: Type.Boolean(),
130
114
  offset_chars: Type.Integer(),
131
- });
115
+ }, { additionalProperties: false });
132
116
  const SearchedFileSchema = Type.Object({
133
117
  ...ListedFileSchema.properties,
134
- matches_total: Type.Integer(),
135
118
  matches: Type.Array(MatchSchema),
136
- });
119
+ }, { additionalProperties: false });
137
120
  const SnapshotSchema = {
138
- more: Type.Integer(),
139
- crumpled_excluded: Type.Integer(),
121
+ more: Type.Integer({ description: "How many more were left out." }),
140
122
  homes_unavailable: Type.Array(Type.String()),
141
123
  };
142
124
  export const NotesWriteDataSchema = Type.Object({
143
125
  address: Type.String(),
144
126
  project_key: Type.Optional(Type.String()),
145
127
  outcome: Type.Union([Type.Literal("created"), Type.Literal("overwrote"), Type.Literal("uncrumpled")]),
146
- });
128
+ }, { additionalProperties: false });
147
129
  export const NotesUpdateDataSchema = Type.Object({
148
130
  address: Type.String(),
149
131
  project_key: Type.Optional(Type.String()),
150
- applied: Type.Integer(),
151
- change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("file")]),
132
+ change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("moved")]),
152
133
  diff: Type.String(),
153
- diff_truncated: Type.Optional(Type.Literal(true)),
154
134
  rename_from: Type.Optional(Type.String()),
155
- replaced_crumpled_target: Type.Optional(Type.Boolean()),
156
- });
135
+ }, { additionalProperties: false });
157
136
  export const NotesReadDataSchema = Type.Object({
158
137
  address: Type.String(),
159
138
  project_key: Type.Optional(Type.String()),
160
139
  metadata: NoteMetadataSchema,
161
140
  ...TextWindowSchema.properties,
162
- });
141
+ }, { additionalProperties: false });
163
142
  export const NotesListDataSchema = Type.Object({
164
143
  files: Type.Array(ListedFileSchema),
165
144
  ...SnapshotSchema,
166
- });
145
+ }, { additionalProperties: false });
167
146
  export const NotesSearchDataSchema = Type.Object({
168
147
  files: Type.Array(SearchedFileSchema),
169
148
  ...SnapshotSchema,
170
- });
149
+ }, { additionalProperties: false });
171
150
  /** Keep identities intact. Only search previews may shrink to make the first row fit. */
172
151
  function snapshot(rows, limit, status, renderData, shrink) {
173
152
  const files = [];
174
- const data = (selected) => ({ files: selected, more: rows.length - selected.length, crumpled_excluded: status.crumpledExcluded, homes_unavailable: status.homesUnavailable });
153
+ const data = (selected) => ({ files: selected, more: rows.length - selected.length, homes_unavailable: status.homesUnavailable });
175
154
  const render = (outcome) => renderOutcome(outcome, renderData);
176
155
  const fits = (item) => fitsResult(success(data([...files, item])), render);
177
156
  for (const item of rows.slice(0, limit)) {
@@ -200,7 +179,7 @@ function renderWriteData(data) {
200
179
  }
201
180
  export const notesWrite = {
202
181
  name: "notes_write", label: "Notes write",
203
- description: `Create or replace a note body, preserving metadata; uncrumples a crumpled note. Name it for its contents and when to use it. Store what git/history cannot recover. ${ADDRESS_DESCRIPTION}`,
182
+ description: `Create or replace a note's body, keeping metadata; uncrumples a crumpled note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
204
183
  parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
205
184
  async execute(params, identity) {
206
185
  try {
@@ -213,35 +192,41 @@ export const notesWrite = {
213
192
  },
214
193
  render: (result) => renderOutcome(result, renderWriteData),
215
194
  };
216
- export const notesUpdateParameters = Type.Object({ address: Type.String(), edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))), origin: ORIGIN, crumpled: CRUMPLED_PARAMETER, replace_all: Type.Optional(Type.Boolean()), rename_to: Type.Optional(Type.String({ description: "Move, preserving metadata. Use alone. Refuses live targets; may replace crumpled targets. References are not updated. Empty string is ignored." })) }, { additionalProperties: false });
195
+ export const notesUpdateParameters = Type.Object({
196
+ address: Type.String(),
197
+ edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))),
198
+ origin: ORIGIN,
199
+ crumpled: CRUMPLED_PARAMETER,
200
+ replace_all: Type.Optional(Type.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
201
+ rename_to: Type.Optional(Type.String({ description: "(optional) Move to this address, keeping metadata. Use alone. Won't overwrite a live note; references aren't updated." })),
202
+ }, { additionalProperties: false });
217
203
  function renderUpdateData(data) {
218
204
  const head = data.rename_from === undefined
219
- ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}: ${data.applied} ${data.applied === 1 ? "edit" : "edits"}`
220
- : `moved ${data.rename_from} -> ${data.address}${data.replaced_crumpled_target === true ? " (replaced a crumpled note)" : ""}`;
205
+ ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}`
206
+ : `moved ${data.rename_from} -> ${data.address}`;
221
207
  const lines = [head];
222
- if (data.diff_truncated === true)
223
- lines.push("diff (this receipt's diff was shortened to fit the output budget; the update itself was applied):");
224
- else if (data.diff.length > 0)
225
- lines.push("diff:");
226
208
  if (data.diff.length > 0)
227
- lines.push(data.diff);
209
+ lines.push("diff:", data.diff);
228
210
  return lines.join("\n");
229
211
  }
230
212
  function renderUpdate(result) {
231
213
  return renderOutcome(result, renderUpdateData);
232
214
  }
233
- /** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix. */
215
+ /** A shortened diff still says so in the receipt's own text, on both surfaces. */
216
+ export const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
217
+ /** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix and marked. */
234
218
  function boundedUpdate(data) {
235
219
  if (fitsResult(success(data), renderUpdate))
236
220
  return success(data);
237
- const shortened = { ...data, diff_truncated: true };
238
- const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...shortened, diff: candidate }), renderUpdate));
239
- const result = success({ ...shortened, diff });
221
+ if (data.diff === "")
222
+ return failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
223
+ const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}\n${DIFF_SHORTENED_MARKER}` }), renderUpdate));
224
+ const result = success({ ...data, diff: `${diff}\n${DIFF_SHORTENED_MARKER}` });
240
225
  return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
241
226
  }
242
227
  export const notesUpdate = {
243
228
  name: "notes_update", label: "Notes update",
244
- description: `Edit body text, change origin or crumpled state, or move a note. Each oldText must match once unless replace_all is true; edits cannot change frontmatter. Metadata-only updates need origin or crumpled. Returns applied changes and a bounded diff. ${ADDRESS_DESCRIPTION}`,
229
+ description: `Edit a note's body, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true; frontmatter can't be edited. Returns a diff. ${ADDRESS_DESCRIPTION}`,
245
230
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
246
231
  async execute(params, identity, renderDiff) {
247
232
  try {
@@ -252,13 +237,13 @@ export const notesUpdate = {
252
237
  if ((params.edits?.length ?? 0) > 0 || params.origin !== undefined || params.crumpled !== undefined || params.replace_all === true) {
253
238
  return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
254
239
  }
255
- const { replacedCrumpledTarget } = await store.rename(params.address, renameTo);
240
+ await store.rename(params.address, renameTo);
256
241
  const from = noteIdentity(identity, params.address).address;
257
242
  const to = noteIdentity(identity, renameTo);
258
- return boundedUpdate({ ...to, rename_from: from, applied: 0, change_kind: "file", diff: `rename ${from} -> ${to.address}`, replaced_crumpled_target: replacedCrumpledTarget });
243
+ return boundedUpdate({ ...to, rename_from: from, change_kind: "moved", diff: `rename ${from} -> ${to.address}` });
259
244
  }
260
- const { applied, change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
261
- return boundedUpdate({ ...noteIdentity(identity, params.address), applied, change_kind: change.kind, diff: renderDiff(change) });
245
+ const { change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
246
+ return boundedUpdate({ ...noteIdentity(identity, params.address), change_kind: change.kind, diff: renderDiff(change) });
262
247
  }
263
248
  catch (error) {
264
249
  return failureOf(error);
@@ -266,13 +251,13 @@ export const notesUpdate = {
266
251
  },
267
252
  render: renderUpdate,
268
253
  };
269
- export const notesReadParameters = Type.Object({ address: Type.String(), offset_chars: Type.Optional(Type.Integer({ description: "Body code-point offset (default 0); negative counts from EOF." })), limit_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `Max code points (default ${DEFAULT_READ_WINDOW_CHARS}); also bounded by output bytes.` })) }, { additionalProperties: false });
254
+ export const notesReadParameters = Type.Object({ address: Type.String(), ...TextWindowRequestSchema }, { additionalProperties: false });
270
255
  function renderReadData(data) {
271
256
  return `${renderIdentity(data)}\n${renderMetadata(data.metadata)}\n\n${renderTextWindow(data)}`;
272
257
  }
273
258
  export const notesRead = {
274
259
  name: "notes_read", label: "Notes read",
275
- description: `Read note metadata and a verbatim body slice, excluding frontmatter. Pass next_offset_chars as offset_chars until null. ${ADDRESS_DESCRIPTION}`,
260
+ description: `Read a note's metadata and body, without frontmatter. ${ADDRESS_DESCRIPTION}`,
276
261
  parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
277
262
  async execute(params, identity) {
278
263
  try {
@@ -284,7 +269,7 @@ export const notesRead = {
284
269
  return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end of the body: the note has ${totalChars} body chars; the largest legal offset is ${totalChars} (an empty end-read)`);
285
270
  const resolved = noteIdentity(identity, params.address);
286
271
  const metadata = noteMetadata(note.meta);
287
- return readTextWindow(note.body, params.offset_chars, params.limit_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
272
+ return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
288
273
  }
289
274
  catch (error) {
290
275
  return failureOf(error);
@@ -292,27 +277,25 @@ export const notesRead = {
292
277
  },
293
278
  render: (result) => renderOutcome(result, renderReadData),
294
279
  };
295
- export const notesListParameters = Type.Object({ pattern: nullableString(), limit: FILE_LIMIT_PARAMETER, wastebasket: WASTEBASKET_PARAMETER }, { additionalProperties: false });
280
+ export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
296
281
  function renderListData(data) {
297
282
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
298
283
  for (const file of data.files) {
299
284
  lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
300
285
  }
301
286
  if (data.more > 0)
302
- lines.push(`${data.more} more matching notes omitted; narrow with pattern`);
303
- if (data.crumpled_excluded > 0)
304
- lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to list them`);
287
+ lines.push(`${data.more} more matching notes omitted; narrow with glob`);
305
288
  for (const home of data.homes_unavailable)
306
289
  lines.push(`${home} could not be read`);
307
290
  return lines.join("\n");
308
291
  }
309
292
  export const notesList = {
310
293
  name: "notes_list", label: "Notes list",
311
- description: `List notes in the session and the four @ homes, newest first. Snapshot, not pageable: more counts omitted files; pattern globs full addresses. Reports unavailable homes and how many crumpled notes were excluded. ${ADDRESS_DESCRIPTION}`,
294
+ description: `List notes in this session and the four @ homes, newest first. Not pageable; \`more\` counts the rest. ${ADDRESS_DESCRIPTION}`,
312
295
  parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
313
296
  async execute(params, identity) {
314
297
  try {
315
- const { rows, status } = await createNotesStore(identity).listWithStatus({ pattern: params.pattern ?? undefined, wastebasket: params.wastebasket });
298
+ const { rows, status } = await createNotesStore(identity).listWithStatus({ glob: params.glob ?? undefined, crumpled: params.crumpled });
316
299
  return snapshot(rows.map(row => listedFile(row, identity)), params.limit, status, renderListData);
317
300
  }
318
301
  catch (error) {
@@ -321,23 +304,23 @@ export const notesList = {
321
304
  },
322
305
  render: (result) => renderOutcome(result, renderListData),
323
306
  };
324
- export const notesSearchParameters = Type.Object({ query: searchQuery(), pattern: nullableString(), limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "Max matches shown per file (default: no cap); matches_total still counts all." })), wastebasket: WASTEBASKET_PARAMETER }, { additionalProperties: false });
307
+ export const notesSearchParameters = Type.Object({ query: 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 }, { additionalProperties: false });
325
308
  function renderSearchData(data) {
326
- const lines = [`${data.files.length} ${data.files.length === 1 ? "file" : "files"}`];
309
+ const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
327
310
  for (const file of data.files) {
328
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches_total} ${file.matches_total === 1 ? "match" : "matches"}${file.matches.length < file.matches_total ? ` (${file.matches.length} shown)` : ""}`);
311
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
329
312
  for (const match of file.matches)
330
- lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}${match.truncated ? " [line shortened]" : ""}`);
313
+ lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
331
314
  }
332
315
  if (data.more > 0)
333
- lines.push(`${data.more} more matching files omitted; narrow with pattern`);
334
- if (data.crumpled_excluded > 0)
335
- lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to search them`);
316
+ lines.push(`${data.more} more matching notes omitted; narrow with glob`);
336
317
  for (const home of data.homes_unavailable)
337
318
  lines.push(`${home} could not be read`);
338
319
  return lines.join("\n");
339
320
  }
340
- /** Prefer whole match lines; shorten the first line only if no whole line fits. */
321
+ /** A shortened match line still ends with a marker, so its own text says it was cut. */
322
+ export const MATCH_SHORTENED_MARKER = " [truncated]";
323
+ /** Prefer whole match lines; shorten the first line only if no whole line fits, and mark it. */
341
324
  function fitSearchFile(file, fits) {
342
325
  let low = 0;
343
326
  let high = file.matches.length;
@@ -353,20 +336,19 @@ function fitSearchFile(file, fits) {
353
336
  const first = file.matches[0];
354
337
  if (!first)
355
338
  return file;
356
- const withText = (text) => ({ ...file, matches: [{ ...first, text, truncated: true }] });
339
+ const withText = (text) => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
357
340
  return withText(prefixFit(first.text, text => fits(withText(text))));
358
341
  }
359
342
  export const notesSearch = {
360
343
  name: "notes_search", label: "Notes search",
361
- description: `Search note bodies for case-insensitive literal queries (OR). Returns matching lines and body code-point offsets for notes_read. Snapshot, not pageable: more counts omitted files; matches_total is before per-file capping. pattern globs full addresses across the session and the four @ homes. ${ADDRESS_DESCRIPTION}`,
344
+ description: `Search note bodies for literal text, case-insensitive. Returns matching lines with offsets for \`notes_read\`. Not pageable; \`more\` counts the rest. ${ADDRESS_DESCRIPTION}`,
362
345
  parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
363
346
  async execute(params, identity) {
364
347
  try {
365
- const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { pattern: params.pattern ?? undefined, wastebasket: params.wastebasket });
348
+ const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
366
349
  const files = rows.sort(byRecent).map(row => ({
367
350
  ...listedFile(row, identity),
368
- matches_total: row.matches.length,
369
- matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, truncated: false, offset_chars: match.offsetChars })),
351
+ matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
370
352
  }));
371
353
  return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
372
354
  }
@@ -1,10 +1,9 @@
1
1
  /** Internal outcomes, compact wire results, and bounded read windows. */
2
2
  import { Type, type Static, type TSchema } from "typebox";
3
- /** `details` is sanitized context for a caller, never a payload or a file body. */
3
+ /** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
4
4
  export declare const OperationErrorSchema: Type.TObject<{
5
5
  code: Type.TString;
6
6
  message: Type.TString;
7
- details: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
8
7
  }>;
9
8
  export type OperationError = Static<typeof OperationErrorSchema>;
10
9
  /** `data` exists without `error`, never both, never neither. */
@@ -16,22 +15,20 @@ export type Outcome<T> = {
16
15
  error: OperationError;
17
16
  };
18
17
  export declare function success<T>(data: T): Outcome<T>;
19
- /** A code is an internal stable identifier and is never clipped; the dynamic message and details are the bounded surface. */
18
+ /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
20
19
  export declare const ERROR_MESSAGE_MAX_CHARS = 2000;
21
- export declare const ERROR_DETAILS_MAX_BYTES = 4096;
22
- export declare function failure(code: string, message: string, details?: Record<string, unknown>): Outcome<never>;
20
+ export declare function failure(code: string, message: string): Outcome<never>;
23
21
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
24
- export type WireError = {
25
- error: string;
26
- code: string;
27
- details?: Record<string, unknown>;
28
- };
22
+ export declare const WireErrorSchema: Type.TObject<{
23
+ error: Type.TString;
24
+ code: Type.TString;
25
+ }>;
26
+ export type WireError = Static<typeof WireErrorSchema>;
29
27
  export type WireResult<T> = T | WireError;
30
28
  export declare function wireResult<T>(result: Outcome<T>): WireResult<T>;
31
29
  export declare function resultSchema<S extends TSchema>(dataSchema: S): Type.TUnion<[S, Type.TObject<{
32
30
  error: Type.TString;
33
31
  code: Type.TString;
34
- details: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
35
32
  }>]>;
36
33
  /** A refusal reads as one short line; a success is the operation's own reading of its data. */
37
34
  export declare function renderOutcome<T>(result: Outcome<T>, renderData: (data: T) => string): string;
@@ -45,12 +42,18 @@ export declare function fitsResult<T>(result: Outcome<T>, render: (result: Outco
45
42
  /** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
46
43
  export declare const TextWindowSchema: Type.TObject<{
47
44
  text: Type.TString;
48
- offset_chars: Type.TInteger;
49
45
  total_chars: Type.TInteger;
50
46
  next_offset_chars: Type.TUnion<[Type.TInteger, Type.TNull]>;
51
- limited_by: Type.TUnion<[Type.TLiteral<"limit">, Type.TLiteral<"bytes">, Type.TNull]>;
52
47
  }>;
53
48
  export type TextWindow = Static<typeof TextWindowSchema>;
49
+ /**
50
+ * The request both read operations share: where to start and how much to deliver. Optional in full,
51
+ * because `readTextWindow` already owns the defaults.
52
+ */
53
+ export declare const TextWindowRequestSchema: {
54
+ offset_chars: Type.TOptional<Type.TInteger>;
55
+ max_chars: Type.TOptional<Type.TInteger>;
56
+ };
54
57
  /**
55
58
  * Read one code-point window of `text` and build the operation's data around it. `offset` and
56
59
  * `limit` are the integers the parameter schema already admitted; a negative `offset` resolves to
@@ -1,60 +1,37 @@
1
1
  /** Internal outcomes, compact wire results, and bounded read windows. */
2
2
  import { Type } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
4
- /** `details` is sanitized context for a caller, never a payload or a file body. */
3
+ import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
4
+ /** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
5
5
  export const OperationErrorSchema = Type.Object({
6
6
  code: Type.String(),
7
7
  message: Type.String(),
8
- details: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
9
8
  }, { additionalProperties: false });
10
9
  export function success(data) {
11
10
  return { ok: true, data };
12
11
  }
13
- /** A code is an internal stable identifier and is never clipped; the dynamic message and details are the bounded surface. */
12
+ /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
14
13
  export const ERROR_MESSAGE_MAX_CHARS = 2000;
15
- export const ERROR_DETAILS_MAX_BYTES = 4096;
16
14
  function boundedMessage(message) {
17
15
  const chars = Array.from(message);
18
16
  return chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
19
17
  }
20
- /** Oversized context becomes an explicit marker, and context JSON cannot serialize propagates instead of being swallowed. */
21
- function boundedDetails(details) {
22
- const json = JSON.stringify(details);
23
- const bytes = Buffer.byteLength(json, "utf8");
24
- return bytes <= ERROR_DETAILS_MAX_BYTES ? JSON.parse(json) : { truncated: true, details_bytes: bytes };
25
- }
26
- export function failure(code, message, details) {
27
- return {
28
- ok: false,
29
- error: {
30
- code,
31
- message: boundedMessage(message),
32
- ...(details === undefined ? {} : { details: boundedDetails(details) }),
33
- },
34
- };
18
+ export function failure(code, message) {
19
+ return { ok: false, error: { code, message: boundedMessage(message) } };
35
20
  }
21
+ /** Public results have no success envelope. `error` is reserved for a refusal message. */
22
+ export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
36
23
  export function wireResult(result) {
37
24
  if (result.ok)
38
25
  return result.data;
39
- const { code, message, details } = result.error;
40
- return { error: message, code, ...(details === undefined ? {} : { details }) };
26
+ const { code, message } = result.error;
27
+ return { error: message, code };
41
28
  }
42
29
  export function resultSchema(dataSchema) {
43
- return Type.Union([
44
- dataSchema,
45
- Type.Object({
46
- error: Type.String(),
47
- code: Type.String(),
48
- details: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
49
- }, { additionalProperties: false }),
50
- ]);
30
+ return Type.Union([dataSchema, WireErrorSchema]);
51
31
  }
52
32
  /** A refusal reads as one short line; a success is the operation's own reading of its data. */
53
33
  export function renderOutcome(result, renderData) {
54
- if (result.ok)
55
- return renderData(result.data);
56
- const { code, message, details } = result.error;
57
- return `error: ${code}: ${message}${details === undefined ? "" : ` ${JSON.stringify(details)}`}`;
34
+ return result.ok ? renderData(result.data) : `error: ${result.error.code}: ${result.error.message}`;
58
35
  }
59
36
  /** Bytes of the structured payload as delivered: compact JSON, not the model-facing text. A value with no JSON representation has no size to measure. */
60
37
  export function structuredBytes(value) {
@@ -70,11 +47,17 @@ export function fitsResult(result, render) {
70
47
  /** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
71
48
  export const TextWindowSchema = Type.Object({
72
49
  text: Type.String(),
73
- offset_chars: Type.Integer({ minimum: 0 }),
74
50
  total_chars: Type.Integer({ minimum: 0 }),
75
- next_offset_chars: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()], { description: "Continue at this code-point offset; null at EOF." }),
76
- limited_by: Type.Union([Type.Literal("limit"), Type.Literal("bytes"), Type.Null()]),
51
+ next_offset_chars: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()], { description: "Pass as `offset_chars` to continue; null at the end." }),
77
52
  }, { additionalProperties: false });
53
+ /**
54
+ * The request both read operations share: where to start and how much to deliver. Optional in full,
55
+ * because `readTextWindow` already owns the defaults.
56
+ */
57
+ export const TextWindowRequestSchema = {
58
+ offset_chars: Type.Optional(Type.Integer({ description: "(optional, default 0) Start offset in chars; negative counts from the end." })),
59
+ max_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${DEFAULT_READ_WINDOW_CHARS}) Max chars to return.` })),
60
+ };
78
61
  /**
79
62
  * Read one code-point window of `text` and build the operation's data around it. `offset` and
80
63
  * `limit` are the integers the parameter schema already admitted; a negative `offset` resolves to
@@ -91,13 +74,10 @@ export function readTextWindow(text, offset, limit, makeData, render) {
91
74
  const range = Math.min(requestedChars, chars.length - start);
92
75
  const window = (delivered) => {
93
76
  const end = start + delivered;
94
- const withheld = end < chars.length;
95
77
  return {
96
78
  text: chars.slice(start, end).join(""),
97
- offset_chars: start,
98
79
  total_chars: chars.length,
99
- next_offset_chars: withheld ? end : null,
100
- limited_by: !withheld ? null : delivered === range ? "limit" : "bytes",
80
+ next_offset_chars: end < chars.length ? end : null,
101
81
  };
102
82
  };
103
83
  const fits = (delivered) => fitsResult(success(makeData(window(delivered))), render);
@@ -113,18 +93,12 @@ export function readTextWindow(text, offset, limit, makeData, render) {
113
93
  else
114
94
  high = mid - 1;
115
95
  }
116
- if (low === 0) {
117
- return failure("output_too_large", "The response metadata leaves no room for a progressing read window.", { total_chars: chars.length, offset_chars: start, budget_bytes: TOOL_OUTPUT_MAX_BYTES });
118
- }
96
+ if (low === 0)
97
+ return failure("output_too_large", "The response metadata leaves no room for a progressing read window.");
119
98
  return success(makeData(window(low)));
120
99
  }
121
100
  /** The continuation line never becomes part of `window.text`, and a complete window has none. */
122
101
  export function renderTextWindow(window) {
123
102
  const next = window.next_offset_chars;
124
- if (next === null)
125
- return window.text;
126
- const resume = `Use offset_chars=${next} to continue.`;
127
- if (window.limited_by === "limit")
128
- return `${window.text}\n\n[${window.total_chars - next} more characters. ${resume}]`;
129
- return `${window.text}\n\n[Showing chars [${window.offset_chars}, ${next}) of ${window.total_chars} (${TOOL_OUTPUT_MAX_BYTES / 1024}KB limit). ${resume}]`;
103
+ return next === null ? window.text : `${window.text}\n\n[truncated; continue at offset_chars=${next}]`;
130
104
  }
@@ -1,9 +1,9 @@
1
1
  import { Type } from "typebox";
2
- export declare const nullableString: () => Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
2
+ export declare const nullableString: (description?: string) => Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
3
3
  export declare const positiveInteger: () => Type.TOptional<Type.TInteger>;
4
4
  export declare const historyRoles: () => Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
5
5
  /** Search query parameter: one literal, or several literals combined with OR. */
6
- export declare const searchQuery: () => Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
6
+ export declare const searchQuery: (description?: string) => Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
7
7
  /** Expected search-query refusal, distinct from any other Error an operation may raise. */
8
8
  export declare class InvalidQueryError extends Error {
9
9
  constructor(message: string);
@@ -1,10 +1,10 @@
1
1
  import { Type } from "typebox";
2
2
  import { HistoryRoleSchema } from "../history/history.js";
3
- export const nullableString = () => Type.Optional(Type.Union([Type.String(), Type.Null()]));
3
+ export const nullableString = (description) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
4
4
  export const positiveInteger = () => Type.Optional(Type.Integer({ minimum: 1 }));
5
- export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "Any of user, assistant, tool, context." }));
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." }));
6
6
  /** Search query parameter: one literal, or several literals combined with OR. */
7
- export const searchQuery = () => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })]);
7
+ export const searchQuery = (description) => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })], description === undefined ? {} : { description });
8
8
  /** Expected search-query refusal, distinct from any other Error an operation may raise. */
9
9
  export class InvalidQueryError extends Error {
10
10
  constructor(message) {