notesoup 0.41.0 → 0.43.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 (127) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.js +1 -6
  3. package/dist/src/boot/text.d.ts +12 -0
  4. package/dist/src/boot/text.js +15 -3
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +14 -0
  9. package/dist/src/budget/text.js +14 -0
  10. package/dist/src/claude/helper.js +24 -4
  11. package/dist/src/claude/thresholds.d.ts +39 -0
  12. package/dist/src/claude/thresholds.js +128 -0
  13. package/dist/src/dream/doctor.js +1 -1
  14. package/dist/src/dream/jail.js +10 -10
  15. package/dist/src/dream/lock.js +6 -13
  16. package/dist/src/dream/report.js +5 -15
  17. package/dist/src/history/history.js +5 -3
  18. package/dist/src/history/query.js +14 -26
  19. package/dist/src/notes/address.d.ts +1 -2
  20. package/dist/src/notes/address.js +14 -26
  21. package/dist/src/notes/errors.d.ts +2 -0
  22. package/dist/src/notes/errors.js +5 -0
  23. package/dist/src/notes/frontmatter.js +16 -2
  24. package/dist/src/notes/identity.js +0 -3
  25. package/dist/src/notes/paths.d.ts +11 -1
  26. package/dist/src/notes/paths.js +28 -7
  27. package/dist/src/notes/store.d.ts +1 -0
  28. package/dist/src/notes/store.js +54 -49
  29. package/dist/src/pi/boot.js +1 -5
  30. package/dist/src/pi/budget.d.ts +3 -3
  31. package/dist/src/pi/budget.js +11 -11
  32. package/dist/src/pi/dream/cli.js +43 -11
  33. package/dist/src/pi/estimate.d.ts +1 -5
  34. package/dist/src/pi/estimate.js +4 -4
  35. package/dist/src/pi/history.js +1 -4
  36. package/dist/src/pi/notes/adapter.d.ts +1 -1
  37. package/dist/src/pi/notes/adapter.js +2 -2
  38. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  39. package/dist/src/pi/reset/artifacts.js +4 -4
  40. package/dist/src/pi/reset/committed.js +2 -2
  41. package/dist/src/pi/runtime.js +9 -6
  42. package/dist/src/pi/thresholds.js +5 -9
  43. package/dist/src/pi/tool-result.d.ts +1 -4
  44. package/dist/src/pi/tool-result.js +3 -3
  45. package/dist/src/pi/window.d.ts +5 -0
  46. package/dist/src/pi/window.js +7 -0
  47. package/dist/src/settings.d.ts +10 -0
  48. package/dist/src/settings.js +10 -4
  49. package/dist/src/tools/history.js +15 -18
  50. package/dist/src/tools/notes.d.ts +3 -7
  51. package/dist/src/tools/notes.js +18 -27
  52. package/dist/src/tools/output.d.ts +2 -3
  53. package/dist/src/tools/output.js +3 -9
  54. package/dist/src/tools/result.d.ts +1 -0
  55. package/dist/src/tools/result.js +15 -21
  56. package/dist/src/tools/schema.d.ts +0 -1
  57. package/dist/src/tools/schema.js +3 -4
  58. package/dist/test/agent-loop.test.js +1 -2
  59. package/dist/test/boot.integration.test.js +1 -1
  60. package/dist/test/claude-mod.test.js +425 -23
  61. package/dist/test/claude-validation.test.d.ts +1 -0
  62. package/dist/test/claude-validation.test.js +73 -0
  63. package/dist/test/dream-skill.test.js +2 -4
  64. package/dist/test/dream.test.js +17 -3
  65. package/dist/test/helpers/extension.js +1 -1
  66. package/dist/test/history.integration.test.js +9 -9
  67. package/dist/test/host-neutral.test.js +16 -1
  68. package/dist/test/notes-library.test.js +31 -2
  69. package/dist/test/notes.integration.test.js +11 -11
  70. package/dist/test/notes.test.js +40 -21
  71. package/dist/test/reset-lifecycle.test.js +1 -1
  72. package/docs/claude-code-mod.md +13 -3
  73. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  74. package/mods/notesoup/dist/claude/helper.js +285 -152
  75. package/mods/notesoup/hooks/register.ts +308 -51
  76. package/mods/notesoup/playbook.md +1 -1
  77. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  78. package/mods/notesoup/skills/memory/SKILL.md +61 -0
  79. package/mods/pi-context/dist/claude/helper.js +9324 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +1 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +2 -7
  86. package/src/boot/text.ts +21 -3
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +20 -0
  90. package/src/claude/helper.ts +22 -5
  91. package/src/claude/thresholds.ts +153 -0
  92. package/src/dream/doctor.ts +1 -1
  93. package/src/dream/jail.ts +10 -10
  94. package/src/dream/lock.ts +3 -9
  95. package/src/dream/report.ts +5 -10
  96. package/src/history/history.ts +5 -3
  97. package/src/history/query.ts +14 -27
  98. package/src/notes/address.ts +13 -25
  99. package/src/notes/errors.ts +6 -0
  100. package/src/notes/frontmatter.ts +12 -2
  101. package/src/notes/identity.ts +0 -2
  102. package/src/notes/paths.ts +23 -5
  103. package/src/notes/store.ts +50 -48
  104. package/src/pi/boot.ts +1 -13
  105. package/src/pi/budget.ts +10 -11
  106. package/src/pi/dream/cli.ts +35 -10
  107. package/src/pi/estimate.ts +4 -4
  108. package/src/pi/history.ts +1 -5
  109. package/src/pi/notes/adapter.ts +2 -2
  110. package/src/pi/reset/artifacts.ts +4 -4
  111. package/src/pi/reset/committed.ts +2 -2
  112. package/src/pi/runtime.ts +8 -7
  113. package/src/pi/thresholds.ts +5 -11
  114. package/src/pi/tool-result.ts +3 -3
  115. package/src/pi/window.ts +8 -0
  116. package/src/settings.ts +22 -5
  117. package/src/tools/history.ts +15 -19
  118. package/src/tools/notes.ts +21 -32
  119. package/src/tools/output.ts +3 -12
  120. package/src/tools/result.ts +14 -19
  121. package/src/tools/schema.ts +3 -4
  122. package/dist/src/dream/playbook.d.ts +0 -1
  123. package/dist/src/dream/playbook.js +0 -2
  124. package/dist/src/pi/reset/text.d.ts +0 -5
  125. package/dist/src/pi/reset/text.js +0 -6
  126. package/src/dream/playbook.ts +0 -3
  127. package/src/pi/reset/text.ts +0 -10
@@ -1,6 +1,6 @@
1
1
  /** Host-neutral history operations: one bounded payload for text and structured results. */
2
2
  import { Type } from "typebox";
3
- import { HISTORY_PREVIEW_CHARS } from "./output.js";
3
+ import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
4
4
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
5
5
  import { historyRoles, searchQuery } from "./schema.js";
6
6
  import { HistoryPageSchema, selectPage } from "../history/query.js";
@@ -48,9 +48,6 @@ function renderPageItem(item) {
48
48
  lines.push(item.content);
49
49
  return lines.join("\n");
50
50
  }
51
- function isFoldedRow(item) {
52
- return "folded" in item;
53
- }
54
51
  function renderFoldedRow(row) {
55
52
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
56
53
  const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
@@ -59,8 +56,8 @@ function renderFoldedRow(row) {
59
56
  function renderPage(page) {
60
57
  // An empty selection has no anchors either, so it would otherwise render as nothing at all.
61
58
  if (page.items.length === 0)
62
- return "no events match this selection";
63
- const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
59
+ return "No events match these filters.";
60
+ const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
64
61
  const cursors = [
65
62
  page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
66
63
  page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
@@ -82,7 +79,7 @@ function pageFits(page) {
82
79
  const MAX_REPORTED_WINDOWS = 5;
83
80
  /** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
84
81
  function knownWindowSuffix(known) {
85
- return known.length === 0 ? "" : `; known: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
82
+ return known.length === 0 ? "" : `; its windows: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
86
83
  }
87
84
  export const PREVIOUS_WINDOW = "@previous";
88
85
  /** Resolve "@previous" against oldest-first windows; every other value passes through. */
@@ -93,13 +90,13 @@ function resolveWindowId(projection, windowId) {
93
90
  if (previous !== undefined)
94
91
  return { ok: true, window_id: previous.windowId };
95
92
  const known = projection.windows.map((current) => current.windowId);
96
- return { ok: false, outcome: failure("unknown_window_id", `unknown window_id "${PREVIOUS_WINDOW}": this session has no window before the current one${knownWindowSuffix(known)}`) };
93
+ return { ok: false, outcome: failure("unknown_window_id", `"${PREVIOUS_WINDOW}" has nothing to point at: this session has no window before the current one${knownWindowSuffix(known)}.`) };
97
94
  }
98
95
  function badWindowId(projection, params) {
99
96
  const badWindow = unknownWindowId(projection, params);
100
97
  if (!badWindow)
101
98
  return undefined;
102
- return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}`);
99
+ return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}.`);
103
100
  }
104
101
  /* ------------------------------------------------------------------ history_windows */
105
102
  export const historyWindowsParameters = Type.Object({}, { additionalProperties: false });
@@ -125,14 +122,14 @@ export const historyWindows = {
125
122
  data.windows.push(row);
126
123
  data.more--;
127
124
  }
128
- return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one `history_windows` response.");
125
+ return fits(data) ? success(data) : failure("output_too_large", `The session id alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry.`);
129
126
  },
130
127
  render: (result) => renderOutcome(result, renderWindows),
131
128
  };
132
129
  function renderWindows(data) {
133
130
  const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
134
131
  if (data.more > 0)
135
- lines.push(`${data.more} more windows not shown; \`history_list\` also reports window ids on events`);
132
+ lines.push(`${data.more} more windows not shown; every \`history_list\` event also names its window.`);
136
133
  return lines.join("\n");
137
134
  }
138
135
  /* ------------------------------------------------------------------ history_list */
@@ -145,8 +142,8 @@ export const historyListParameters = Type.Object({
145
142
  until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
146
143
  from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
147
144
  window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
148
- limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
149
- max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
145
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
146
+ 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.` })),
150
147
  }, { additionalProperties: false });
151
148
  export const historyList = {
152
149
  name: "history_list",
@@ -179,22 +176,22 @@ export const historyRead = {
179
176
  // Address checks run in one order: past the end of the file, off this branch, then
180
177
  // consumed by a pairing. Only the last two can mention what is at the address.
181
178
  if (item === undefined && params.seq > projection.highestSeq) {
182
- return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}`);
179
+ return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
183
180
  }
184
181
  if (!projection.branchSeqs.has(params.seq)) {
185
- return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here`);
182
+ return failure("not_on_branch", `Seq ${params.seq} is on another branch of this session; it can't be read from here.`);
186
183
  }
187
184
  if (item === undefined) {
188
185
  const callSeq = projection.pairedResults.get(params.seq);
189
186
  if (callSeq !== undefined) {
190
- return failure("not_an_event", `seq ${params.seq} is a tool result already shown inside the call at seq ${callSeq}; read that seq instead`);
187
+ return failure("not_an_event", `Seq ${params.seq} is a tool result, shown together with its call; read seq ${callSeq} instead.`);
191
188
  }
192
- return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`);
189
+ return failure("unknown_seq", `Seq ${params.seq} holds nothing to read.`);
193
190
  }
194
191
  const document = eventDocument(item);
195
192
  const totalChars = Array.from(document).length;
196
193
  if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
197
- return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end: the item has ${totalChars} chars; the largest legal offset is ${totalChars} (an empty end-read)`);
194
+ return failure("invalid_offset", `This event ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
198
195
  }
199
196
  return readTextWindow(document, params.offset_chars, params.max_chars, (window) => ({
200
197
  seq: item.seq,
@@ -2,10 +2,6 @@ import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { Type, type Static } from "typebox";
3
3
  import { type NoteChange } from "../notes/index.js";
4
4
  import { type Outcome } from "./result.js";
5
- /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
6
- export declare const MAX_METADATA_ENTRY_BYTES = 1024;
7
- /** An extra value that cannot be carried is named in place, never silently dropped. */
8
- export declare const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
9
5
  export declare const NoteMetadataSchema: Type.TObject<{
10
6
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
11
7
  created_at: Type.TString;
@@ -80,7 +76,7 @@ export declare const notesWriteParameters: Type.TObject<{
80
76
  export declare const notesWrite: {
81
77
  readonly name: "notes_write";
82
78
  readonly label: "Notes write";
83
- readonly 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. 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.";
79
+ readonly description: "Create or replace a note. Name it for what it holds and when to use it. Store what git and history can't recover. 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.";
84
80
  readonly parameters: Type.TObject<{
85
81
  address: Type.TString;
86
82
  content: Type.TString;
@@ -115,7 +111,7 @@ export declare const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
115
111
  export declare const notesUpdate: {
116
112
  readonly name: "notes_update";
117
113
  readonly label: "Notes update";
118
- readonly 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. 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.";
114
+ readonly description: "Edit a note, change its origin or crumpled state, or move it. Each `oldText` must match exactly once unless `replace_all` is true. 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.";
119
115
  readonly parameters: Type.TObject<{
120
116
  address: Type.TString;
121
117
  edits: Type.TOptional<Type.TArray<Type.TObject<{
@@ -149,7 +145,7 @@ export declare const notesReadParameters: Type.TObject<{
149
145
  export declare const notesRead: {
150
146
  readonly name: "notes_read";
151
147
  readonly label: "Notes read";
152
- readonly description: "Read a note's metadata and body, without frontmatter. 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.";
148
+ readonly description: "Read a note. 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.";
153
149
  readonly parameters: Type.TObject<{
154
150
  offset_chars: Type.TOptional<Type.TInteger>;
155
151
  max_chars: Type.TOptional<Type.TInteger>;
@@ -2,7 +2,7 @@ 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 { prefixFit } from "./output.js";
5
+ import { prefixFit, TOOL_OUTPUT_LIMIT } from "./output.js";
6
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")];
@@ -14,10 +14,6 @@ const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(opti
14
14
  const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
15
15
  const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
16
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.";
17
- /** The one receipt field a caller cannot derive from the address itself. */
18
- function projectKeyField(scope, projectKey) {
19
- return scope === "project" ? { project_key: projectKey } : {};
20
- }
21
17
  /**
22
18
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
23
19
  * Convert expected refusals; unexpected errors propagate unchanged.
@@ -32,20 +28,13 @@ function failureOf(error) {
32
28
  return failure("io_error", "notes operation failed");
33
29
  throw error;
34
30
  }
35
- function byRecent(a, b) {
36
- return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
37
- }
38
31
  /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
39
32
  const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
40
33
  /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
41
- export const MAX_METADATA_ENTRY_BYTES = 1024;
34
+ const MAX_METADATA_ENTRY_BYTES = 1024;
42
35
  const MAX_METADATA_VERBATIM_BYTES = 2048;
43
36
  /** An extra value that cannot be carried is named in place, never silently dropped. */
44
- export const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
45
- /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
46
- function extraEntryBytes(key, value) {
47
- return structuredBytes(key) + 1 + structuredBytes(value);
48
- }
37
+ const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
49
38
  export const NoteMetadataSchema = Type.Object({
50
39
  origin: Type.Union([...ORIGIN_VALUES]),
51
40
  created_at: Type.String(),
@@ -68,7 +57,8 @@ function noteMetadata(meta) {
68
57
  // A key too large to carry cannot be named at all; an oversized value is named in place.
69
58
  if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES)
70
59
  continue;
71
- const entryBytes = extraEntryBytes(key, value);
60
+ // The key counts too: hand-written frontmatter can have arbitrarily long keys.
61
+ const entryBytes = structuredBytes(key) + 1 + structuredBytes(value);
72
62
  if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
73
63
  put(key, TOO_LARGE_EXTRA_VALUE);
74
64
  continue;
@@ -164,14 +154,14 @@ function snapshot(rows, limit, status, renderData, shrink) {
164
154
  files.push(reduced);
165
155
  }
166
156
  if (files.length === 0)
167
- return failure("output_too_large", "The first matching note cannot fit in a response without losing its identity.");
157
+ return failure("output_too_large", `\`${item.address}\` won't fit on the list (${TOOL_OUTPUT_LIMIT} per call); narrow \`glob\` to leave it out.`);
168
158
  break;
169
159
  }
170
160
  const outcome = success(data(files));
171
- return fitsResult(outcome, render) ? outcome : failure("output_too_large", "The notes snapshot metadata exceeds the response budget.");
161
+ return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
172
162
  }
173
163
  function listedFile(row, identity) {
174
- return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
164
+ return { address: row.address, ...(row.scope === "project" ? { project_key: identity.projectKey } : {}), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
175
165
  }
176
166
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
177
167
  function renderWriteData(data) {
@@ -179,7 +169,7 @@ function renderWriteData(data) {
179
169
  }
180
170
  export const notesWrite = {
181
171
  name: "notes_write", label: "Notes write",
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}`,
172
+ description: `Create or replace a note. Name it for what it holds and when to use it. Store what git and history can't recover. ${ADDRESS_DESCRIPTION}`,
183
173
  parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
184
174
  async execute(params, identity) {
185
175
  try {
@@ -214,19 +204,20 @@ function renderUpdate(result) {
214
204
  }
215
205
  /** A shortened diff still says so in the receipt's own text, on both surfaces. */
216
206
  export const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
207
+ const RECEIPT_TOO_LONG = `Saved, but the receipt is too long to hand back (${TOOL_OUTPUT_LIMIT} per call). Check the note with \`notes_read\`.`;
217
208
  /** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix and marked. */
218
209
  function boundedUpdate(data) {
219
210
  if (fitsResult(success(data), renderUpdate))
220
211
  return success(data);
221
212
  if (data.diff === "")
222
- return failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
213
+ return failure("output_too_large", RECEIPT_TOO_LONG);
223
214
  const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}\n${DIFF_SHORTENED_MARKER}` }), renderUpdate));
224
215
  const result = success({ ...data, diff: `${diff}\n${DIFF_SHORTENED_MARKER}` });
225
- return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
216
+ return fitsResult(result, renderUpdate) ? result : failure("output_too_large", RECEIPT_TOO_LONG);
226
217
  }
227
218
  export const notesUpdate = {
228
219
  name: "notes_update", label: "Notes update",
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}`,
220
+ description: `Edit a note, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
230
221
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
231
222
  async execute(params, identity, renderDiff) {
232
223
  try {
@@ -257,17 +248,17 @@ function renderReadData(data) {
257
248
  }
258
249
  export const notesRead = {
259
250
  name: "notes_read", label: "Notes read",
260
- description: `Read a note's metadata and body, without frontmatter. ${ADDRESS_DESCRIPTION}`,
251
+ description: `Read a note. ${ADDRESS_DESCRIPTION}`,
261
252
  parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
262
253
  async execute(params, identity) {
263
254
  try {
264
255
  const note = await createNotesStore(identity).read(params.address);
256
+ const resolved = noteIdentity(identity, params.address);
265
257
  if (!note)
266
- return failure("not_found", "note not found");
258
+ return failure("not_found", `No note at ${resolved.address}.`);
267
259
  const totalChars = Array.from(note.body).length;
268
260
  if (params.offset_chars !== undefined && params.offset_chars > totalChars)
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)`);
270
- const resolved = noteIdentity(identity, params.address);
261
+ return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
271
262
  const metadata = noteMetadata(note.meta);
272
263
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
273
264
  }
@@ -346,7 +337,7 @@ export const notesSearch = {
346
337
  async execute(params, identity) {
347
338
  try {
348
339
  const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
349
- const files = rows.sort(byRecent).map(row => ({
340
+ const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
350
341
  ...listedFile(row, identity),
351
342
  matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
352
343
  }));
@@ -1,11 +1,10 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
2
  export declare const TOOL_OUTPUT_MAX_BYTES: number;
3
+ /** The per-call limit as the model reads it in refusals. */
4
+ export declare const TOOL_OUTPUT_LIMIT = "32 KB";
4
5
  export declare const DEFAULT_READ_WINDOW_CHARS = 12000;
5
6
  export declare const MAX_READ_WINDOW_CHARS = 50000;
6
7
  export declare const HISTORY_PREVIEW_CHARS = 1200;
7
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
8
- export declare function withinTextBudget(text: string, budget?: number): boolean;
9
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
10
9
  export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
11
10
  /**
@@ -1,16 +1,10 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
3
+ /** The per-call limit as the model reads it in refusals. */
4
+ export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
4
5
  export const DEFAULT_READ_WINDOW_CHARS = 12000;
5
6
  export const MAX_READ_WINDOW_CHARS = 50000;
6
7
  export const HISTORY_PREVIEW_CHARS = 1200;
7
- function json(value) {
8
- return JSON.stringify(value);
9
- }
10
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
11
- export function withinTextBudget(text, budget = TOOL_OUTPUT_MAX_BYTES) {
12
- return Buffer.byteLength(text, "utf8") <= budget;
13
- }
14
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
15
9
  export function prefixFit(text, fits) {
16
10
  if (fits(text))
@@ -35,5 +29,5 @@ export function prefixFit(text, fits) {
35
29
  * undefined unless the tool has metadata worth persisting.
36
30
  */
37
31
  export function output(value, details, terminate = false) {
38
- return { content: [{ type: "text", text: json(value) }], details, terminate };
32
+ return { content: [{ type: "text", text: JSON.stringify(value) }], details, terminate };
39
33
  }
@@ -17,6 +17,7 @@ export type Outcome<T> = {
17
17
  export declare function success<T>(data: T): Outcome<T>;
18
18
  /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
19
19
  export declare const ERROR_MESSAGE_MAX_CHARS = 2000;
20
+ /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
20
21
  export declare function failure(code: string, message: string): Outcome<never>;
21
22
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
22
23
  export declare const WireErrorSchema: Type.TObject<{
@@ -1,6 +1,6 @@
1
1
  /** Internal outcomes, compact wire results, and bounded read windows. */
2
2
  import { Type } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
3
+ import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES } from "./output.js";
4
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(),
@@ -11,12 +11,11 @@ export function success(data) {
11
11
  }
12
12
  /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
13
13
  export const ERROR_MESSAGE_MAX_CHARS = 2000;
14
- function boundedMessage(message) {
15
- const chars = Array.from(message);
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]`;
17
- }
14
+ /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
18
15
  export function failure(code, message) {
19
- return { ok: false, error: { code, message: boundedMessage(message) } };
16
+ const chars = Array.from(message);
17
+ 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]`;
18
+ return { ok: false, error: { code, message: bounded } };
20
19
  }
21
20
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
22
21
  export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
@@ -42,7 +41,7 @@ export function structuredBytes(value) {
42
41
  * measure covers everything the renderer puts around the payload, headers and footers included.
43
42
  */
44
43
  export function fitsResult(result, render) {
45
- return withinTextBudget(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
44
+ return Buffer.byteLength(render(result), "utf8") <= TOOL_OUTPUT_MAX_BYTES && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
46
45
  }
47
46
  /** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
48
47
  export const TextWindowSchema = Type.Object({
@@ -71,7 +70,8 @@ export function readTextWindow(text, offset, limit, makeData, render) {
71
70
  const requested = offset ?? 0;
72
71
  const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
73
72
  const requestedChars = limit ?? DEFAULT_READ_WINDOW_CHARS;
74
- const range = Math.min(requestedChars, chars.length - start);
73
+ // A start past the end (a caller that skipped its own offset check) has nothing to deliver.
74
+ const range = Math.max(0, Math.min(requestedChars, chars.length - start));
75
75
  const window = (delivered) => {
76
76
  const end = start + delivered;
77
77
  return {
@@ -81,21 +81,15 @@ export function readTextWindow(text, offset, limit, makeData, render) {
81
81
  };
82
82
  };
83
83
  const fits = (delivered) => fitsResult(success(makeData(window(delivered))), render);
84
- // Test the full range first: its footer can disappear at the end of the document.
84
+ // Test the full range first: its footer can disappear at the end of the document, and an
85
+ // empty source is a complete window rather than a refusal.
85
86
  if (fits(range))
86
87
  return success(makeData(window(range)));
87
- let low = 0;
88
- let high = range;
89
- while (low < high) {
90
- const mid = Math.ceil((low + high) / 2);
91
- if (fits(mid))
92
- low = mid;
93
- else
94
- high = mid - 1;
95
- }
96
- if (low === 0)
97
- return failure("output_too_large", "The response metadata leaves no room for a progressing read window.");
98
- return success(makeData(window(low)));
88
+ // The kept count is monotone in the serialized size, so the shared prefix search owns the shrink.
89
+ const delivered = Array.from(prefixFit(window(range).text, (candidate) => fits(Array.from(candidate).length))).length;
90
+ if (delivered === 0)
91
+ return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
92
+ return success(makeData(window(delivered)));
99
93
  }
100
94
  /** The continuation line never becomes part of `window.text`, and a complete window has none. */
101
95
  export function renderTextWindow(window) {
@@ -1,6 +1,5 @@
1
1
  import { Type } from "typebox";
2
2
  export declare const nullableString: (description?: string) => Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
3
- export declare const positiveInteger: () => Type.TOptional<Type.TInteger>;
4
3
  export declare const historyRoles: () => Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
5
4
  /** Search query parameter: one literal, or several literals combined with OR. */
6
5
  export declare const searchQuery: (description?: string) => Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
@@ -1,7 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import { HistoryRoleSchema } from "../history/history.js";
3
3
  export const nullableString = (description) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
4
- export const positiveInteger = () => Type.Optional(Type.Integer({ minimum: 1 }));
5
4
  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
5
  /** Search query parameter: one literal, or several literals combined with OR. */
7
6
  export const searchQuery = (description) => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })], description === undefined ? {} : { description });
@@ -22,10 +21,10 @@ export class InvalidQueryError extends Error {
22
21
  export function searchQueries(query) {
23
22
  const candidates = typeof query === "string" ? [query] : query;
24
23
  if (!Array.isArray(candidates) || candidates.length === 0)
25
- throw new InvalidQueryError("query must be a string or a non-empty array of strings");
24
+ throw new InvalidQueryError("`query` must be a string or a non-empty list of strings.");
26
25
  if (!candidates.every((candidate) => typeof candidate === "string"))
27
- throw new InvalidQueryError("query array elements must be strings");
26
+ throw new InvalidQueryError("Every item in the `query` list must be a string.");
28
27
  if (candidates.some((candidate) => candidate === ""))
29
- throw new InvalidQueryError("query strings must be non-empty: an empty query matches everything");
28
+ throw new InvalidQueryError("`query` can't be an empty string; it would match everything.");
30
29
  return candidates;
31
30
  }
@@ -8,8 +8,7 @@ import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, Mod
8
8
  import notesoup, { createNotesoup } from "../src/pi/extension.js";
9
9
  import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../src/pi/entries.js";
10
10
  import { CONTEXT_WINDOW_OPEN_TAG } from "../src/boot/text.js";
11
- import { CONTINUATION, WARNING_CONTENT, WARNING_PROMPT } from "../src/pi/reset/text.js";
12
- import { GUIDANCE_OPEN_TAG } from "../src/budget/text.js";
11
+ import { CONTINUATION, GUIDANCE_OPEN_TAG, WARNING_CONTENT, WARNING_PROMPT } from "../src/budget/text.js";
13
12
  async function openFixture(options) {
14
13
  const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
15
14
  const ownsDir = options.cwd === undefined;
@@ -6,7 +6,7 @@ import test from "node:test";
6
6
  import { historyFromSession } from "../src/pi/history.js";
7
7
  import { BOOT_TYPE, GUIDANCE_TYPE, RESET_MARKER_TYPE } from "../src/pi/entries.js";
8
8
  import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
9
- import { CONTINUATION } from "../src/pi/reset/text.js";
9
+ import { CONTINUATION } from "../src/budget/text.js";
10
10
  import { listNotes } from "./helpers/notes.js";
11
11
  import { CONTINUATION_TYPE, MANUAL_WIPE_TYPE } from "../src/pi/entries.js";
12
12
  import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultData, resultJson, resultRead, runContextHook, runContextWithSystemHook, runHandlers, runManualCompact, runCommand, sentOf, } from "./helpers/extension.js";