notesoup 0.57.3 → 0.58.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 (129) hide show
  1. package/README.md +15 -1
  2. package/dist/plugins/claude/src/helper.js +2 -11
  3. package/dist/plugins/claude/src/thresholds.js +5 -18
  4. package/dist/plugins/codex/src/mcp.js +3 -11
  5. package/dist/plugins/codex/src/state.d.ts +1 -1
  6. package/dist/plugins/codex/src/state.js +1 -1
  7. package/dist/plugins/dsh/tools.js +1 -1
  8. package/dist/plugins/pi/boot.d.ts +1 -1
  9. package/dist/plugins/pi/boot.js +2 -3
  10. package/dist/plugins/pi/budget.d.ts +1 -1
  11. package/dist/plugins/pi/budget.js +1 -1
  12. package/dist/plugins/pi/render.d.ts +1 -1
  13. package/dist/plugins/pi/render.js +20 -11
  14. package/dist/plugins/pi/runtime.js +6 -2
  15. package/dist/plugins/pi/tool-result.d.ts +2 -1
  16. package/dist/plugins/pi/window.js +24 -1
  17. package/dist/src/boot/render.d.ts +3 -4
  18. package/dist/src/boot/render.js +23 -21
  19. package/dist/src/boot/text.d.ts +2 -5
  20. package/dist/src/boot/text.js +12 -9
  21. package/dist/src/budget/text.d.ts +1 -1
  22. package/dist/src/budget/text.js +1 -1
  23. package/dist/src/history/corpus.d.ts +1 -1
  24. package/dist/src/history/corpus.js +1 -1
  25. package/dist/src/history/history.d.ts +2 -2
  26. package/dist/src/history/history.js +5 -8
  27. package/dist/src/history/query.d.ts +11 -3
  28. package/dist/src/history/query.js +7 -11
  29. package/dist/src/index.d.ts +4 -3
  30. package/dist/src/index.js +1 -1
  31. package/dist/src/notes/constants.d.ts +1 -1
  32. package/dist/src/notes/constants.js +1 -1
  33. package/dist/src/notes/errors.d.ts +1 -1
  34. package/dist/src/notes/frontmatter.d.ts +2 -1
  35. package/dist/src/notes/frontmatter.js +3 -1
  36. package/dist/src/notes/index.d.ts +1 -0
  37. package/dist/src/notes/index.js +1 -0
  38. package/dist/src/notes/policy.d.ts +16 -0
  39. package/dist/src/notes/policy.js +43 -0
  40. package/dist/src/notes/store.d.ts +8 -3
  41. package/dist/src/notes/store.js +64 -20
  42. package/dist/src/result.d.ts +21 -0
  43. package/dist/src/result.js +18 -0
  44. package/dist/src/text-match.d.ts +8 -0
  45. package/dist/src/text-match.js +34 -0
  46. package/dist/src/tools/dream.d.ts +9 -1
  47. package/dist/src/tools/dream.js +2 -1
  48. package/dist/src/tools/history.js +14 -5
  49. package/dist/src/tools/notes.d.ts +75 -13
  50. package/dist/src/tools/notes.js +58 -19
  51. package/dist/src/tools/output.d.ts +1 -3
  52. package/dist/src/tools/output.js +1 -19
  53. package/dist/src/tools/result.d.ts +2 -20
  54. package/dist/src/tools/result.js +4 -18
  55. package/dist/src/tools/schema.d.ts +3 -7
  56. package/dist/src/tools/schema.js +10 -16
  57. package/dist/test/agent-loop.test.js +78 -6
  58. package/dist/test/boot.integration.test.js +30 -3
  59. package/dist/test/claude-mod.test.js +7 -6
  60. package/dist/test/codex-history.test.js +2 -2
  61. package/dist/test/codex-plugin.test.js +2 -0
  62. package/dist/test/dependencies.test.js +38 -3
  63. package/dist/test/dsh.test.js +1 -1
  64. package/dist/test/helpers/dependency-graph.js +12 -6
  65. package/dist/test/helpers/extension.d.ts +2 -1
  66. package/dist/test/history.integration.test.js +47 -1
  67. package/dist/test/host-neutral.test.js +4 -3
  68. package/dist/test/model-facing-text.test.js +20 -16
  69. package/dist/test/note-policy.test.d.ts +1 -0
  70. package/dist/test/note-policy.test.js +227 -0
  71. package/dist/test/notes-query-namespaces.test.js +7 -3
  72. package/dist/test/notes.integration.test.js +10 -10
  73. package/dist/test/notes.test.js +4 -4
  74. package/dist/test/pi-render.test.js +28 -1
  75. package/dist/test/project-namespace.test.js +1 -1
  76. package/docs/architecture.md +10 -7
  77. package/docs/dsh.md +1 -1
  78. package/docs/notes-library.md +20 -7
  79. package/docs/reset-lifecycle.md +2 -2
  80. package/docs/tool-results.md +3 -1
  81. package/package.json +12 -12
  82. package/playbook.md +1 -1
  83. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  84. package/plugins/claude/dist/claude/helper.js +528 -422
  85. package/plugins/claude/hooks/register.ts +1 -10
  86. package/plugins/claude/playbook.md +1 -1
  87. package/plugins/claude/skills/dream/SKILL.md +1 -1
  88. package/plugins/claude/skills/memory/SKILL.md +1 -1
  89. package/plugins/claude/src/helper.ts +2 -11
  90. package/plugins/claude/src/thresholds.ts +5 -15
  91. package/plugins/codex/dist/codex/notesoup.js +520 -403
  92. package/plugins/codex/src/mcp.ts +5 -12
  93. package/plugins/codex/src/state.ts +1 -1
  94. package/plugins/dsh/tools.ts +2 -1
  95. package/plugins/pi/boot.ts +3 -4
  96. package/plugins/pi/budget.ts +1 -1
  97. package/plugins/pi/render.ts +20 -8
  98. package/plugins/pi/runtime.ts +6 -2
  99. package/plugins/pi/tool-result.ts +2 -1
  100. package/plugins/pi/window.ts +20 -1
  101. package/skills/dream/SKILL.md +1 -1
  102. package/skills/memory/SKILL.md +1 -1
  103. package/src/boot/render.ts +24 -21
  104. package/src/boot/text.ts +12 -9
  105. package/src/budget/text.ts +1 -1
  106. package/src/history/corpus.ts +1 -1
  107. package/src/history/history.ts +5 -6
  108. package/src/history/query.ts +11 -14
  109. package/src/index.ts +5 -2
  110. package/src/notes/constants.ts +1 -1
  111. package/src/notes/errors.ts +1 -1
  112. package/src/notes/frontmatter.ts +4 -2
  113. package/src/notes/index.ts +1 -0
  114. package/src/notes/policy.ts +49 -0
  115. package/src/notes/store.ts +66 -26
  116. package/src/result.ts +26 -0
  117. package/src/text-match.ts +32 -0
  118. package/src/tools/dream.ts +2 -1
  119. package/src/tools/history.ts +15 -6
  120. package/src/tools/notes.ts +60 -20
  121. package/src/tools/output.ts +1 -17
  122. package/src/tools/result.ts +4 -26
  123. package/src/tools/schema.ts +11 -17
  124. package/dist/plugins/codex/src/history.d.ts +0 -3
  125. package/dist/plugins/codex/src/history.js +0 -2
  126. package/dist/plugins/codex/src/transcript.d.ts +0 -3
  127. package/dist/plugins/codex/src/transcript.js +0 -2
  128. package/plugins/codex/src/history.ts +0 -3
  129. package/plugins/codex/src/transcript.ts +0 -3
@@ -1,17 +1,41 @@
1
1
  import type { NotesIdentity } from "../notes/identity.js";
2
+ import { assertAddress } from "../notes/address.js";
3
+ import { noteFileName } from "../notes/paths.js";
4
+ import { effectiveNotePolicy, noteBudgetWarnings } from "../notes/policy.js";
2
5
  import { Type, type Static } from "typebox";
3
6
  import { localIso } from "../notes/frontmatter.js";
4
7
  import { isFilesystemError } from "../notes/fs-error.js";
5
8
  import { createNotesStore, NoteError, noteIdentity, type NoteChange, type NoteMeta, type NoteQueryStatus, type NoteRow } from "../notes/index.js";
6
- import { prefixFit, TOOL_OUTPUT_LIMIT } from "./output.js";
7
- import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowRequestSchema, TextWindowSchema, type Outcome } from "./result.js";
8
- import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
9
+ import { TOOL_OUTPUT_LIMIT } from "./output.js";
10
+ import { failure, success, type Outcome } from "../result.js";
11
+ import { InvalidQueryError, prefixFit, searchQueries } from "../text-match.js";
12
+ import { fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
13
+ import { nullableString, searchQuery } from "./schema.js";
9
14
  import { notesIdentityForCall, type NotesToolContext } from "./notes-context.js";
10
15
 
11
16
  const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")] as const;
12
17
  const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
13
18
  description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self.",
14
19
  }));
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 2048 for every note). 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." })),
24
+ };
25
+ const PolicySchema = {
26
+ pinned: Type.Boolean(), budget: Type.Integer(), readonly: Type.Boolean(),
27
+ };
28
+ const WarningsSchema = { warnings: Type.Array(Type.String()) };
29
+ function policyAt(meta: NoteMeta, address: string) {
30
+ return effectiveNotePolicy(meta, noteFileName(assertAddress(address).path));
31
+ }
32
+ function renderPolicy(policy: { pinned: boolean; budget: number; readonly: boolean }): string {
33
+ return `pinned ${policy.pinned} | budget ${policy.budget} | readonly ${policy.readonly}`;
34
+ }
35
+ function withWarnings(text: string, data: { warnings: string[] }): string {
36
+ return [text, ...data.warnings].join("\n");
37
+ }
38
+
15
39
  const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
16
40
  const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
17
41
  const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
@@ -33,7 +57,7 @@ export function failureOf(error: unknown): Outcome<never> {
33
57
  }
34
58
 
35
59
  /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
36
- const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
60
+ const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project", "pinned", "budget", "readonly"]);
37
61
  /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
38
62
  const MAX_METADATA_ENTRY_BYTES = 1024;
39
63
  const MAX_METADATA_VERBATIM_BYTES = 2048;
@@ -41,6 +65,7 @@ const MAX_METADATA_VERBATIM_BYTES = 2048;
41
65
  const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
42
66
 
43
67
  export const NoteMetadataSchema = Type.Object({
68
+ ...PolicySchema,
44
69
  origin: Type.Union([...ORIGIN_VALUES]),
45
70
  created_at: Type.String(),
46
71
  updated_at: Type.String(),
@@ -51,7 +76,7 @@ export const NoteMetadataSchema = Type.Object({
51
76
  export type NoteMetadata = Static<typeof NoteMetadataSchema>;
52
77
 
53
78
  /** Normalize known metadata and bound extras, naming an oversized value instead of hiding it. */
54
- function noteMetadata(meta: NoteMeta): NoteMetadata {
79
+ function noteMetadata(meta: NoteMeta, address: string): NoteMetadata {
55
80
  const extra: Record<string, unknown> = {};
56
81
  let verbatimBytes = 0;
57
82
  const put = (key: string, value: unknown): void => {
@@ -72,6 +97,7 @@ function noteMetadata(meta: NoteMeta): NoteMetadata {
72
97
  put(key, value);
73
98
  }
74
99
  return {
100
+ ...policyAt(meta, address),
75
101
  origin: meta.origin,
76
102
  created_at: localIso(meta.createdAt),
77
103
  updated_at: localIso(meta.updatedAt),
@@ -83,6 +109,7 @@ function noteMetadata(meta: NoteMeta): NoteMetadata {
83
109
 
84
110
  function renderMetadata(metadata: NoteMetadata): string {
85
111
  const fields = [
112
+ renderPolicy(metadata),
86
113
  `origin ${metadata.origin}`,
87
114
  `created ${metadata.created_at}`,
88
115
  `updated ${metadata.updated_at}`,
@@ -117,6 +144,8 @@ export const NoteIdentitySchema = {
117
144
 
118
145
  export const ListedFileSchema = Type.Object({
119
146
  ...NoteIdentitySchema,
147
+ ...PolicySchema,
148
+ ...WarningsSchema,
120
149
  updated_at: Type.String(),
121
150
  crumpled_at: Type.Optional(Type.String()),
122
151
  }, { additionalProperties: false });
@@ -139,12 +168,16 @@ export const SnapshotSchema = {
139
168
 
140
169
  export const NotesWriteDataSchema = Type.Object({
141
170
  ...NoteIdentitySchema,
171
+ ...PolicySchema,
172
+ ...WarningsSchema,
142
173
  outcome: Type.Union([Type.Literal("created"), Type.Literal("overwrote"), Type.Literal("uncrumpled")]),
143
174
  }, { additionalProperties: false });
144
175
  export type NotesWriteData = Static<typeof NotesWriteDataSchema>;
145
176
 
146
177
  export const NotesUpdateDataSchema = Type.Object({
147
178
  ...NoteIdentitySchema,
179
+ ...PolicySchema,
180
+ ...WarningsSchema,
148
181
  change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("moved")]),
149
182
  rename_from: Type.Optional(Type.String()),
150
183
  }, { additionalProperties: false });
@@ -153,6 +186,7 @@ export type NotesUpdateData = Static<typeof NotesUpdateDataSchema>;
153
186
  export const NotesReadDataSchema = Type.Object({
154
187
  ...NoteIdentitySchema,
155
188
  metadata: NoteMetadataSchema,
189
+ ...WarningsSchema,
156
190
  ...TextWindowSchema.properties,
157
191
  }, { additionalProperties: false });
158
192
  export type NotesReadData = Static<typeof NotesReadDataSchema>;
@@ -199,14 +233,15 @@ export function snapshot<T extends { address: string }>(
199
233
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
200
234
  }
201
235
 
202
- export function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
203
- return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
236
+ export function listedFile(row: Pick<NoteRow, "address" | "meta"> & { body?: string; warnings?: string[] }, identity: NotesIdentity): NotesListData["files"][number] {
237
+ const policy = policyAt(row.meta, row.address);
238
+ 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 }) };
204
239
  }
205
240
 
206
- export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN, cwd: CWD_PARAMETER }, { additionalProperties: false });
241
+ export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
207
242
 
208
243
  function renderWriteData(data: NotesWriteData): string {
209
- return `${data.outcome} ${renderIdentity(data)}`;
244
+ return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
210
245
  }
211
246
 
212
247
  export const notesWrite = {
@@ -216,8 +251,8 @@ export const notesWrite = {
216
251
  async execute(params: Static<typeof notesWriteParameters>, context: NotesToolContext): Promise<Outcome<NotesWriteData>> {
217
252
  try {
218
253
  const identity = notesIdentityForCall(context, params.cwd);
219
- const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin });
220
- return success({ ...noteIdentity(identity, params.address), outcome });
254
+ const { outcome, meta, warnings } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly });
255
+ return success({ ...noteIdentity(identity, params.address), outcome, ...policyAt(meta, params.address), warnings });
221
256
  } catch (error) { return failureOf(error); }
222
257
  },
223
258
  render: (result: Outcome<NotesWriteData>): string => renderOutcome(result, renderWriteData),
@@ -227,6 +262,7 @@ export const notesUpdateParameters = Type.Object({
227
262
  address: Type.String(),
228
263
  edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))),
229
264
  origin: ORIGIN,
265
+ ...POLICY_PARAMETERS,
230
266
  crumpled: CRUMPLED_PARAMETER,
231
267
  replace_all: Type.Optional(Type.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
232
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." })),
@@ -234,14 +270,15 @@ export const notesUpdateParameters = Type.Object({
234
270
  }, { additionalProperties: false });
235
271
 
236
272
  function renderUpdateData(data: NotesUpdateData): string {
237
- return data.rename_from === undefined
273
+ const receipt = data.rename_from === undefined
238
274
  ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}`
239
275
  : `moved ${data.rename_from} -> ${data.address}`;
276
+ return withWarnings(`${receipt} | ${renderPolicy(data)}`, data);
240
277
  }
241
278
 
242
279
  export const notesUpdate = {
243
280
  name: "notes_update", label: "Notes update",
244
- description: `Change part of a note's body, its origin or crumpled state, or its address. 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}`,
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}`,
245
282
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
246
283
  async execute(params: Static<typeof notesUpdateParameters>, context: NotesToolContext, onChange?: (change: NoteChange) => void): Promise<Outcome<NotesUpdateData>> {
247
284
  try {
@@ -249,11 +286,11 @@ export const notesUpdate = {
249
286
  const store = createNotesStore(identity);
250
287
  // Empty filler is not a request: models that pass every parameter get the edit path.
251
288
  const renameTo = params.rename_to === "" ? undefined : params.rename_to;
252
- const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
289
+ const { change, moved, meta, warnings } = await store.update(params.address, params.edits, { origin: params.origin, pinned: params.pinned, budget: params.budget, readonly: params.readonly, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
253
290
  onChange?.(change);
254
291
  const from = noteIdentity(identity, params.address).address;
255
292
  const to = noteIdentity(identity, renameTo ?? params.address);
256
- return success({ ...to, ...(moved ? { rename_from: from } : {}), change_kind: moved ? "moved" : change.kind });
293
+ return success({ ...to, ...policyAt(meta, to.address), warnings, ...(moved ? { rename_from: from } : {}), change_kind: moved ? "moved" : change.kind });
257
294
  } catch (error) { return failureOf(error); }
258
295
  },
259
296
  render: (result: Outcome<NotesUpdateData>): string => renderOutcome(result, renderUpdateData),
@@ -262,7 +299,7 @@ export const notesUpdate = {
262
299
  export const notesReadParameters = Type.Object({ address: Type.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
263
300
 
264
301
  function renderReadData(data: NotesReadData): string {
265
- return `${renderIdentity(data)}\n${renderMetadata(data.metadata)}\n\n${renderTextWindow(data)}`;
302
+ return withWarnings(`${renderIdentity(data)}\n${renderMetadata(data.metadata)}`, data) + `\n\n${renderTextWindow(data)}`;
266
303
  }
267
304
 
268
305
  export const notesRead = {
@@ -277,8 +314,9 @@ export const notesRead = {
277
314
  if (!note) return failure("not_found", `No note at ${resolved.address}.`);
278
315
  const totalChars = Array.from(note.body).length;
279
316
  if (params.offset_chars !== undefined && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
280
- const metadata = noteMetadata(note.meta);
281
- return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
317
+ const metadata = noteMetadata(note.meta, resolved.address);
318
+ const warnings = noteBudgetWarnings(note.body, metadata);
319
+ return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), (result) => renderOutcome(result, renderReadData));
282
320
  } catch (error) { return failureOf(error); }
283
321
  },
284
322
  render: (result: Outcome<NotesReadData>): string => renderOutcome(result, renderReadData),
@@ -289,7 +327,8 @@ export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FI
289
327
  export function renderListData(data: Snapshot<NotesListData["files"][number] & { last_accessed?: string }>): string {
290
328
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
291
329
  for (const file of data.files) {
292
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.last_accessed === undefined ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
330
+ lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at}${file.last_accessed === undefined ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
331
+ lines.push(...file.warnings.map(warning => ` ${warning}`));
293
332
  }
294
333
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
295
334
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
@@ -315,7 +354,8 @@ export const notesSearchParameters = Type.Object({ query: Type.Optional(searchQu
315
354
  function renderSearchData(data: NotesSearchData): string {
316
355
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
317
356
  for (const file of data.files) {
318
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
357
+ lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
358
+ lines.push(...file.warnings.map(warning => ` ${warning}`));
319
359
  for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
320
360
  }
321
361
  if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
@@ -1,23 +1,7 @@
1
- /** Shared output budget primitives. */
1
+ /** Tool output budgets and default window sizes. */
2
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
3
3
  /** The per-call limit as the model reads it in refusals. */
4
4
  export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
5
5
  export const DEFAULT_READ_WINDOW_CHARS = 12000;
6
6
  export const MAX_READ_WINDOW_CHARS = 50000;
7
7
  export const HISTORY_PREVIEW_CHARS = 1200;
8
-
9
- /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
10
- export function prefixFit(text: string, fits: (content: string) => boolean): string {
11
- if (fits(text)) return text;
12
- const chars = Array.from(text);
13
- // Serialized size is non-decreasing in the kept count, so the largest fitting prefix is
14
- // found by a monotone binary search instead of a quadratic shrink loop.
15
- let low = 0;
16
- let high = chars.length;
17
- while (low < high) {
18
- const mid = Math.ceil((low + high) / 2);
19
- if (fits(chars.slice(0, mid).join(""))) low = mid;
20
- else high = mid - 1;
21
- }
22
- return chars.slice(0, low).join("");
23
- }
@@ -1,30 +1,8 @@
1
- /** Internal outcomes, compact wire results, and bounded read windows. */
1
+ /** Compact tool wire results and bounded read windows. */
2
2
  import { Type, type Static, type TSchema } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES } from "./output.js";
4
-
5
- /** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
6
- export const OperationErrorSchema = Type.Object({
7
- code: Type.String(),
8
- message: Type.String(),
9
- }, { additionalProperties: false });
10
- export type OperationError = Static<typeof OperationErrorSchema>;
11
-
12
- /** `data` exists without `error`, never both, never neither. */
13
- export type Outcome<T> = { ok: true; data: T } | { ok: false; error: OperationError };
14
-
15
- export function success<T>(data: T): Outcome<T> {
16
- return { ok: true, data };
17
- }
18
-
19
- /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
20
- export const ERROR_MESSAGE_MAX_CHARS = 2000;
21
-
22
- /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
23
- export function failure(code: string, message: string): Outcome<never> {
24
- const chars = Array.from(message);
25
- const bounded = chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
26
- return { ok: false, error: { code, message: bounded } };
27
- }
3
+ import { failure, success, type Outcome } from "../result.js";
4
+ import { prefixFit } from "../text-match.js";
5
+ import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES } from "./output.js";
28
6
 
29
7
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
30
8
  export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
@@ -1,23 +1,17 @@
1
- import { Type } from "typebox";
1
+ import { Type, type TSchema } from "typebox";
2
+ import { Errors } from "typebox/value";
2
3
  import { HistoryRoleSchema } from "../history/history.js";
3
4
  export const nullableString = (description?: string) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
4
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
6
 
6
- /** Search query parameter: one literal, or several literals combined with OR. */
7
- 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 });
8
-
9
- /** Expected search-query refusal, distinct from any other Error an operation may raise. */
10
- export class InvalidQueryError extends Error {
11
- constructor(message: string) {
12
- super(message);
13
- this.name = "InvalidQueryError";
14
- }
7
+ /** First parameter violation; skip false subschemas so additionalProperties can name the field. */
8
+ export function paramProblem(schema: TSchema, params: unknown): string {
9
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
10
+ if (!first) return "unrecognized shape";
11
+ const extra = first.keyword === "additionalProperties" ? `: ${(first.params as { additionalProperties: string[] }).additionalProperties.join(", ")}` : "";
12
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
13
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
15
14
  }
16
15
 
17
- /** Missing/empty queries disable filtering; empty list entries are ignored, not OR wildcards. */
18
- export function searchQueries(query: unknown): string[] {
19
- const candidates = query === undefined ? [] : typeof query === "string" ? [query] : query;
20
- if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
21
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
22
- return candidates.filter((candidate) => candidate !== "") as string[];
23
- }
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 });
@@ -1,3 +0,0 @@
1
- /** Codex's SDK-facing entry; the local corpus uses the same persisted wire decoder. */
2
- export { readCodexHistory } from "../../../src/history/codex.js";
3
- export type { CodexHistoryState, CodexTranscriptSource } from "../../../src/history/codex.js";
@@ -1,2 +0,0 @@
1
- /** Codex's SDK-facing entry; the local corpus uses the same persisted wire decoder. */
2
- export { readCodexHistory } from "../../../src/history/codex.js";
@@ -1,3 +0,0 @@
1
- /** Codex wire-format entry shared by boot/state and cross-harness history. */
2
- export { nativeObject, nativeString, readCodexTranscript, readCodexTranscriptState } from "../../../src/history/codex-transcript.js";
3
- export type { CodexTranscriptSource, CodexTranscriptState, CodexRecord, NativeObject } from "../../../src/history/codex-transcript.js";
@@ -1,2 +0,0 @@
1
- /** Codex wire-format entry shared by boot/state and cross-harness history. */
2
- export { nativeObject, nativeString, readCodexTranscript, readCodexTranscriptState } from "../../../src/history/codex-transcript.js";
@@ -1,3 +0,0 @@
1
- /** Codex's SDK-facing entry; the local corpus uses the same persisted wire decoder. */
2
- export { readCodexHistory } from "../../../src/history/codex.js";
3
- export type { CodexHistoryState, CodexTranscriptSource } from "../../../src/history/codex.js";
@@ -1,3 +0,0 @@
1
- /** Codex wire-format entry shared by boot/state and cross-harness history. */
2
- export { nativeObject, nativeString, readCodexTranscript, readCodexTranscriptState } from "../../../src/history/codex-transcript.js";
3
- export type { CodexTranscriptSource, CodexTranscriptState, CodexRecord, NativeObject } from "../../../src/history/codex-transcript.js";