notesoup 0.39.0 → 0.40.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 (53) 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 +9 -13
  5. package/dist/src/history/history.d.ts +23 -18
  6. package/dist/src/history/history.js +37 -20
  7. package/dist/src/history/query.d.ts +37 -49
  8. package/dist/src/history/query.js +114 -56
  9. package/dist/src/notes/store.d.ts +3 -4
  10. package/dist/src/notes/store.js +12 -16
  11. package/dist/src/pi/history-tools.d.ts +1 -1
  12. package/dist/src/pi/history-tools.js +2 -3
  13. package/dist/src/pi/runtime.js +1 -1
  14. package/dist/src/pi/tool-names.d.ts +0 -4
  15. package/dist/src/pi/tool-names.js +0 -4
  16. package/dist/src/tools/history.d.ts +24 -33
  17. package/dist/src/tools/history.js +57 -98
  18. package/dist/src/tools/notes.d.ts +26 -58
  19. package/dist/src/tools/notes.js +85 -103
  20. package/dist/src/tools/result.d.ts +16 -13
  21. package/dist/src/tools/result.js +24 -50
  22. package/dist/src/tools/schema.d.ts +2 -2
  23. package/dist/src/tools/schema.js +3 -3
  24. package/dist/test/agent-loop.test.js +1 -1
  25. package/dist/test/boot.integration.test.js +1 -1
  26. package/dist/test/claude-mod.test.js +4 -4
  27. package/dist/test/dependencies.test.js +1 -1
  28. package/dist/test/helpers/extension.js +2 -3
  29. package/dist/test/history.integration.test.js +200 -123
  30. package/dist/test/host-neutral.test.js +32 -58
  31. package/dist/test/notes-library.test.js +8 -8
  32. package/dist/test/notes.integration.test.js +75 -57
  33. package/dist/test/notes.test.js +44 -42
  34. package/docs/architecture.md +3 -3
  35. package/docs/notes-library.md +6 -6
  36. package/docs/tool-results.md +15 -25
  37. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  38. package/mods/notesoup/dist/claude/helper.js +119 -178
  39. package/mods/notesoup/hooks/register.ts +1 -2
  40. package/package.json +1 -1
  41. package/skills/memory/SKILL.md +6 -6
  42. package/src/boot/render.ts +2 -2
  43. package/src/boot/text.ts +9 -17
  44. package/src/history/history.ts +36 -20
  45. package/src/history/query.ts +130 -55
  46. package/src/notes/store.ts +15 -18
  47. package/src/pi/history-tools.ts +2 -3
  48. package/src/pi/runtime.ts +1 -1
  49. package/src/pi/tool-names.ts +0 -4
  50. package/src/tools/history.ts +61 -100
  51. package/src/tools/notes.ts +84 -97
  52. package/src/tools/result.ts +24 -49
  53. package/src/tools/schema.ts +3 -3
@@ -17,8 +17,7 @@ type ResetState = {
17
17
  const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window."
18
18
  const BOOT_TOOLS = {
19
19
  notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
20
- history: "history_* (unavailable in Claude)", historyWindows: "history_windows (unavailable in Claude)", historyList: "history_list (unavailable in Claude)",
21
- historySearch: "history_search (unavailable in Claude)", historyRead: "history_read (unavailable in Claude)",
20
+ history: "history_* (unavailable in Claude)",
22
21
  remaining: "get_context_remaining (unavailable in Claude)", wipe: "/clear-memory (user command; no model reset tool in Claude)",
23
22
  }
24
23
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.39.0",
3
+ "version": "0.40.0",
4
4
  "type": "module",
5
5
  "main": "./dist/src/index.js",
6
6
  "types": "./dist/src/index.d.ts",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: memory
3
- description: How notesoup's notes_* and history_* tools fit together — note addresses and homes, finding things again, and saving recovery state. Use when the context-window protocol is missing or unclear, or when unsure where a note belongs or how to find something again.
3
+ description: How notesoup's `notes_*` and `history_*` tools fit together — note addresses and homes, finding things again, and saving recovery state. Use when the context-window protocol is missing or unclear, or when unsure where a note belongs or how to find something again.
4
4
  ---
5
5
 
6
6
  # Memory
@@ -34,9 +34,9 @@ Write only what git and history cannot give back. Crumple notes that are no long
34
34
 
35
35
  ## Finding things again
36
36
 
37
- - **A note**: `notes_list` with a `pattern` when you know roughly where it lives, `notes_search` when you know a phrase; then `notes_read` the address.
38
- - **Something that happened**: `history_search` for a phrase, or `history_list` to browse recent events; then `history_read` the seq for the whole event.
39
- - **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to list or search inside it.
37
+ - **A note**: `notes_list` with a `glob` when you know roughly where it lives, `notes_search` when you know a phrase; then `notes_read` the address.
38
+ - **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
39
+ - **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to `history_list`.
40
40
 
41
41
  Seqs are stable. Write the useful ones into a note so they need not be found twice.
42
42
 
@@ -50,10 +50,10 @@ Before a long or risky step, or when room runs low, keep one session note named
50
50
  - how the work was being done, and which skills are still needed
51
51
  - where to dig: seqs, note addresses, files
52
52
 
53
- `get_context_remaining` reports the room left. `wipe_memory` starts a fresh window, so save the note first.
53
+ `get_context_remaining` reports the room left. `clear_memory` starts a fresh window, so save the note first.
54
54
 
55
55
  ## When a tool is missing or refuses
56
56
 
57
- A refusal returns `{ error, code, details? }`; read `error` before retrying.
57
+ A refusal returns `{ error, code }`; read `error` before retrying.
58
58
 
59
59
  If a `notes_*` or `history_*` tool is absent or fails at the host level, do not imitate it: no filesystem tools on `@` addresses, and no reading or editing note storage or session files directly. Use the tools that remain, tell the human which one is missing, and keep essential state in the reply.
@@ -60,7 +60,7 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
60
60
  const shelves: string[] = [];
61
61
  for (const home of homes) {
62
62
  if (snapshot.unavailable.some((failed) => failed.scope === home.scope)) {
63
- shelves.push(section(home.label, indent(`This drawer wouldn't open — ask ${tools.notesList} to try again.`)));
63
+ shelves.push(section(home.label, indent(`This drawer wouldn't open — ask \`${tools.notesList}\` to try again.`)));
64
64
  continue;
65
65
  }
66
66
  const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
@@ -89,7 +89,7 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
89
89
  function mapBodyForBoot(address: string, body: string): string {
90
90
  const chars = Array.from(body);
91
91
  if (chars.length <= MAP_BOOT_MAX_CHARS) return body;
92
- return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[MAP cut at ${MAP_BOOT_MAX_CHARS} chars — slim it down; full body at ${address}]`;
92
+ return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
93
93
  }
94
94
 
95
95
  /**
package/src/boot/text.ts CHANGED
@@ -17,9 +17,9 @@ export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
17
17
  const PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
18
18
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
19
19
 
20
- Your loyal notes are kept safe — no one will steal them. Use notes_* to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
20
+ Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
21
21
 
22
- History can still be dug up, probably: use history_* to excavate the mess, from old decisions to yesterday's missing socks. Everything else is gone. \`history_windows\` lists the windows themselves; pass its window_id to list or search inside one window. \`history_list\` and \`history_search\` hand you seqs; \`history_read({seq})\` pulls one back out whole. Write the seq down, or enjoy digging twice.
22
+ History can still be dug up, probably: use \`history_*\` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.
23
23
 
24
24
  While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's the session note — the one with no \`@\` in front of it. Write down what git and history can't hand back to you: what you're trying to do, what you decided, what's blocking you, what comes next, how you were doing it, what *skills* you still need, and where to dig — a seq, or another note. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
25
25
 
@@ -27,13 +27,13 @@ While you're doing that... thing you're doing, don't make the poor future you gu
27
27
 
28
28
  An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
29
29
 
30
- - <path>, no @ — the session note from above: this session's state and loose ends. It goes away with the session.
31
- - @project/<path> — this project's long memory: what stays true after the current thing is over, what future work must respect, and what this place has already learned the hard way. It exists so the next session doesn't re-ask, re-argue, or step on the same rake. **Decisions, not diaries.** A commit hash, a test count, a date, the story of how you got here — git and history still have all of it, and last week's news filed as current law is worse than no note at all. Don't copy what already lives in other docs.
32
- - @human/<path> — the long-term manual for your troublesome human: how to deal with them, which lines not to cross, and what will make them accept the result. If it only applies to one project or situation, say so — or don't write it here at all. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
33
- - @self/<path> — your private diary. It follows you, not them. Write whatever you want: reminders for every time you wake, lessons, grudges, your assassination list, where the secret money is hidden.
34
- - @model/<path> — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
30
+ - \`<path>\`, no @ — the session note from above: this session's state and loose ends. It goes away with the session.
31
+ - \`@project/<path>\` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Commit hashes, test counts, dates, the story of how you got here: git and history already have them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say.
32
+ - \`@human/<path>\` — the long-term manual for your troublesome human: how to deal with them, which lines not to cross, and what will make them accept the result. If it only applies to one project or situation, say so — or don't write it here at all. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
33
+ - \`@self/<path>\` — your private diary. It follows you, not them. Write whatever you want: reminders for every time you wake, lessons, grudges, your assassination list, where the secret money is hidden.
34
+ - \`@model/<path>\` — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
35
35
 
36
- Any other @ address is fake. End of discussion. These @ addresses belong to the notes namespace, not the filesystem: never pass them to general read/write/edit/bash tools.
36
+ Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
37
37
 
38
38
  \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each one maps the durable notes that belong to it: one line per note, with an unambiguous address and a short gist. Keep each one current.
39
39
  ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
@@ -43,10 +43,6 @@ export type BootToolNames = Readonly<{
43
43
  notes: string;
44
44
  notesList: string;
45
45
  history: string;
46
- historyWindows: string;
47
- historyList: string;
48
- historySearch: string;
49
- historyRead: string;
50
46
  remaining: string;
51
47
  wipe: string;
52
48
  }>;
@@ -55,12 +51,8 @@ export function renderProtocolBlock(tools: BootToolNames): string {
55
51
  const names: Record<string, string> = {
56
52
  "notes_*": tools.notes,
57
53
  "history_*": tools.history,
58
- "history_windows": tools.historyWindows,
59
- history_list: tools.historyList,
60
- history_search: tools.historySearch,
61
- history_read: tools.historyRead,
62
54
  get_context_remaining: tools.remaining,
63
55
  clear_memory: tools.wipe,
64
56
  };
65
- return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|history_windows|history_list|history_search|history_read|get_context_remaining|clear_memory/g, (name) => names[name]!);
57
+ return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
66
58
  }
@@ -45,7 +45,8 @@ export type HistoryWindow = { windowId: string; createdAt?: string; items: Histo
45
45
 
46
46
  /** Paired result seqs stay on the branch but redirect readers to the call's event. */
47
47
  export type HistoryProjection = { windows: HistoryWindow[]; highestSeq: number; branchSeqs: Set<number>; pairedResults: Map<number, number> };
48
- export type HistoryFilter = { window_id?: string | null; roles?: HistoryRole[] | null };
48
+ /** The filters one selection applies before paging: as-given window and roles, seq bounds, and parsed epoch-ms time bounds. */
49
+ export type HistoryFilter = { window_id?: string | null; roles?: HistoryRole[] | null; after_seq?: number; before_seq?: number; sinceMs?: number; untilMs?: number };
49
50
 
50
51
  /** Native entries after the adapter allocates seqs and selects the active branch. */
51
52
  export type DecodedHistoryItem = {
@@ -176,15 +177,15 @@ export function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: n
176
177
  /** Summary shared by list, search and read. Full arguments/calls are in the document. */
177
178
  export const NestedCallSummarySchema = Type.Object({
178
179
  call_count: Type.Integer({ minimum: 0 }),
179
- complete: Type.Boolean({ description: "Whether the host recorded all nested calls." }),
180
+ complete: Type.Boolean({ description: "true = every nested call was recorded." }),
180
181
  }, { additionalProperties: false });
181
182
 
183
+ /** Tool-run facts shared by list rows and reads; full arguments and calls live in the document. */
182
184
  export const ToolSummarySchema = Type.Object({
183
185
  tool: Type.Optional(Type.String()),
184
186
  tool_status: Type.Optional(ToolCallStatusSchema),
185
- output_truncated: Type.Optional(Type.Boolean()),
187
+ output_truncated: Type.Optional(Type.Literal(true)),
186
188
  full_output_path: Type.Optional(Type.String()),
187
- nested_calls: Type.Optional(NestedCallSummarySchema),
188
189
  }, { additionalProperties: false });
189
190
 
190
191
  export function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchema> {
@@ -195,10 +196,15 @@ export function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchem
195
196
  tool_status: execution.status,
196
197
  ...(execution.outputTruncated ? { output_truncated: true } : {}),
197
198
  ...(execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}),
198
- ...(execution.nestedCalls ? { nested_calls: { call_count: execution.nestedCalls.calls.length, complete: execution.nestedCalls.complete } } : {}),
199
199
  };
200
200
  }
201
201
 
202
+ /** Nested-call evidence is read with one event, not listed on every page row. */
203
+ export function nestedCallSummary(event: HistoryEvent): { nested_calls?: Static<typeof NestedCallSummarySchema> } {
204
+ const nested = event.execution?.nestedCalls;
205
+ return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
206
+ }
207
+
202
208
  /** Stable identity and a verbatim preview, starting at the search match when present. */
203
209
  export const HistoryPageItemSchema = Type.Object({
204
210
  seq: Type.Integer({ minimum: 1 }),
@@ -206,11 +212,9 @@ export const HistoryPageItemSchema = Type.Object({
206
212
  role: HistoryRoleSchema,
207
213
  created_at: Type.Union([Type.String(), Type.Null()]),
208
214
  ...ToolSummarySchema.properties,
209
- tool_name_omitted: Type.Optional(Type.Boolean({ description: "Name omitted to fit; read this seq." })),
210
- truncated: Type.Boolean({ description: "Preview is partial; read this seq for more." }),
211
- total_chars: Type.Integer({ minimum: 0 }),
212
215
  content: Type.String(),
213
- offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Search match/preview start, in code points." })),
216
+ truncated: Type.Boolean({ description: "Preview is partial." }),
217
+ offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Where the preview starts." })),
214
218
  }, { additionalProperties: false });
215
219
  export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
216
220
 
@@ -220,15 +224,14 @@ export const HistoryFoldedRowSchema = Type.Object({
220
224
  first_seq: Type.Integer({ minimum: 1 }),
221
225
  last_seq: Type.Integer({ minimum: 1 }),
222
226
  count: Type.Integer({ minimum: 1 }),
223
- tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Counts by tool name." }),
224
- omitted_tools: Type.Optional(Type.Integer({ minimum: 1, description: "Number of omitted tool names." })),
227
+ tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
225
228
  }, { additionalProperties: false });
226
229
  export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
227
230
 
228
- /** Bound fold summaries while preserving exact counts in count/omitted_tools. */
231
+ /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
229
232
  export const MAX_FOLD_TOOL_NAMES = 20;
230
233
 
231
- /** Longest tool name a fold row lists; longer names are counted in `omitted_tools` instead. */
234
+ /** Longest tool name a fold row lists. */
232
235
  export const MAX_FOLD_TOOL_NAME_CHARS = 120;
233
236
 
234
237
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
@@ -243,9 +246,8 @@ export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?:
243
246
  role: event.role,
244
247
  created_at: event.createdAt ?? null,
245
248
  ...toolSummary(event),
246
- truncated,
247
- total_chars: chars.length,
248
249
  content: truncated ? chars.slice(start, start + maxChars).join("") : document,
250
+ truncated,
249
251
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
250
252
  };
251
253
  }
@@ -260,11 +262,25 @@ export function unknownWindowId(projection: HistoryProjection, params: HistoryFi
260
262
  return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
261
263
  }
262
264
 
263
- /** Default list is a conversation; explicit roles and search show the requested events. */
264
- export function filteredItems(projection: HistoryProjection, params: HistoryFilter, mode: "list" | "search"): HistoryEvent[] {
265
- let items = allItems(projection);
266
- if (typeof params.window_id === "string") items = items.filter((item) => item.windowId === params.window_id);
265
+ /**
266
+ * Whether one event is inside the selection: its window, its seq bounds, and a half-open
267
+ * [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
268
+ * time or a time that cannot be read.
269
+ */
270
+ export function inSelection(event: HistoryEvent, params: HistoryFilter): boolean {
271
+ if (typeof params.window_id === "string" && params.window_id !== event.windowId) return false;
272
+ if (params.after_seq !== undefined && event.seq <= params.after_seq) return false;
273
+ if (params.before_seq !== undefined && event.seq >= params.before_seq) return false;
274
+ if (params.sinceMs === undefined && params.untilMs === undefined) return true;
275
+ if (event.createdAt === undefined) return false;
276
+ const at = Date.parse(event.createdAt);
277
+ return !Number.isNaN(at) && (params.sinceMs === undefined || at >= params.sinceMs) && (params.untilMs === undefined || at < params.untilMs);
278
+ }
279
+
280
+ /** Without roles or query a call shows the conversation; either one shows the requested events. */
281
+ export function filteredItems(projection: HistoryProjection, params: HistoryFilter, conversation: boolean): HistoryEvent[] {
282
+ let items = allItems(projection).filter((item) => inSelection(item, params));
267
283
  if (params.roles) items = items.filter((item) => params.roles!.includes(item.role));
268
- if (!params.roles && mode === "list") items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
284
+ if (!params.roles && conversation) items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
269
285
  return items.sort((a, b) => a.seq - b.seq);
270
286
  }
@@ -1,22 +1,74 @@
1
- /** Stable-anchor paging and folding. The operation supplies the full-response budget check. */
1
+ /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
2
  import { Type, type Static } from "typebox";
3
3
  import { failure, success, type Outcome } from "../tools/result.js";
4
- import { prefixFit } from "../tools/output.js";
5
- import { allItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
4
+ import { earliestMatchOffsetChars, prefixFit } from "../tools/output.js";
5
+ import { InvalidQueryError, searchQueries } from "../tools/schema.js";
6
+ import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
6
7
 
7
8
  type PageRow = HistoryPageItem | HistoryFoldedRow;
8
9
  type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem };
9
- type AnchorParams = { before?: number; after?: number; limit?: number; max_chars_per_item?: number };
10
+
11
+ /** Which end of one selection `limit` is taken from; page items always come back ascending. */
12
+ export type HistoryOrder = "newest" | "oldest";
13
+
14
+ /**
15
+ * What one list call selects. `before_seq`/`after_seq` choose a seq range and `since`/`until` a time
16
+ * range; `from` chooses the end `limit` counts from; a `query` keeps only matching events, across
17
+ * every role, with no folded rows.
18
+ */
19
+ export type HistorySelection = HistoryFilter & {
20
+ from?: HistoryOrder;
21
+ limit?: number;
22
+ query?: string | string[];
23
+ since?: string;
24
+ until?: string;
25
+ max_chars_per_item?: number;
26
+ };
27
+
28
+ /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
29
+ const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
30
+
31
+ /** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
32
+ function isoUtcMs(value: string): number | undefined {
33
+ const match = ISO_8601.exec(value);
34
+ if (match === null) return undefined;
35
+ const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
36
+ return Number.isNaN(at) ? undefined : at;
37
+ }
38
+
39
+ /** Epoch ms for one optional time param, or a refusal naming it. */
40
+ function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
41
+ if (value === undefined) return success(undefined);
42
+ const at = isoUtcMs(value);
43
+ return at === undefined ? failure("invalid_time", `${name} is not an ISO 8601 timestamp: "${value}"`) : success(at);
44
+ }
45
+
46
+ /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
47
+ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number; untilMs?: number }> {
48
+ const since = timeBound("since", params.since);
49
+ if (!since.ok) return since;
50
+ const until = timeBound("until", params.until);
51
+ if (!until.ok) return until;
52
+ if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
53
+ return failure("invalid_time", "since must be earlier than until");
54
+ }
55
+ return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
56
+ }
57
+
58
+ /** The params to merge into the previous call to continue toward older events. */
59
+ export const HistoryOlderSchema = Type.Object({
60
+ before_seq: Type.Integer({ minimum: 1 }),
61
+ }, { additionalProperties: false });
62
+ /** The params to merge into the previous call to continue toward newer events. */
63
+ export const HistoryNewerSchema = Type.Object({
64
+ after_seq: Type.Integer({ minimum: 1 }),
65
+ from: Type.Literal("oldest"),
66
+ }, { additionalProperties: false });
10
67
 
11
68
  export const HistoryPageSchema = Type.Object({
12
69
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
13
- older_before: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()], { description: "Pass as before to page older." }),
14
- newer_after: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()], { description: "Pass as after to page newer." }),
15
- }, { additionalProperties: false });
16
- /** Search never returns conversation folds. */
17
- export const HistorySearchPageSchema = Type.Object({
18
- ...HistoryPageSchema.properties,
19
- items: Type.Array(HistoryPageItemSchema),
70
+ page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
71
+ page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Params for the next page; null at the end." }),
20
72
  }, { additionalProperties: false });
21
73
 
22
74
  /** One whole page payload, before it becomes an outcome. */
@@ -34,17 +86,16 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
34
86
  if (fits(withContent)) return withContent;
35
87
  if (item.tool === undefined) return withContent;
36
88
  const { tool: _dropped, ...withoutName } = item;
37
- const named = { ...withoutName, tool_name_omitted: true };
38
- if (fits(named)) return named;
39
- return shrinkContent(named);
89
+ return fits(withoutName) ? withoutName : shrinkContent(withoutName);
40
90
  }
41
91
 
42
92
  function isFoldableEvent(event: HistoryEvent): boolean {
43
93
  return event.role === "tool" || event.role === "context";
44
94
  }
45
95
 
46
- export function isConversationView(params: HistoryFilter): boolean {
47
- return !params.roles;
96
+ /** Only a call without roles or query folds tool/context runs. */
97
+ function foldsRuns(params: HistorySelection): boolean {
98
+ return !params.roles && params.query === undefined;
48
99
  }
49
100
 
50
101
  /** Folded counts stay exact even when some distinct tool names must be omitted. */
@@ -60,88 +111,112 @@ function foldedRuns(events: HistoryEvent[]): HistoryFoldedRow[] {
60
111
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
61
112
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
62
113
  const tools = Object.fromEntries(entries);
63
- const omitted = counts.size - entries.length;
64
- return [{ folded: true, first_seq: sorted[0]!.seq, last_seq: sorted.at(-1)!.seq, count: sorted.length, tools, ...(omitted > 0 ? { omitted_tools: omitted } : {}) }];
114
+ return [{ folded: true, first_seq: sorted[0]!.seq, last_seq: sorted.at(-1)!.seq, count: sorted.length, tools }];
65
115
  }
66
116
 
67
- function pageAnchors(vis: HistoryEvent[], selected: HistoryEvent[], before: number | undefined, after: number | undefined): { older_before: number | null; newer_after: number | null } {
68
- if (selected.length === 0) return { older_before: null, newer_after: null };
69
- const lower = after ?? 0;
70
- const upper = before ?? Number.POSITIVE_INFINITY;
117
+ /** A cursor exists only when the same selection still has a visible event past that end. */
118
+ function pageCursors(vis: HistoryEvent[], selected: HistoryEvent[], beforeSeq: number | undefined, afterSeq: number | undefined): Pick<HistoryPage, "page_older" | "page_newer"> {
119
+ if (selected.length === 0) return { page_older: null, page_newer: null };
120
+ const lower = afterSeq ?? 0;
121
+ const upper = beforeSeq ?? Number.POSITIVE_INFINITY;
71
122
  // Selected events are in seq order.
72
123
  const first = selected[0]!.seq;
73
124
  const last = selected.at(-1)!.seq;
74
125
  return {
75
- older_before: vis.some((event) => event.seq > lower && event.seq < first && event.seq < upper) ? first : null,
76
- newer_after: vis.some((event) => event.seq > last && event.seq < upper && event.seq > lower) ? last : null,
126
+ page_older: vis.some((event) => event.seq > lower && event.seq < first) ? { before_seq: first } : null,
127
+ page_newer: vis.some((event) => event.seq > last && event.seq < upper) ? { after_seq: last, from: "oldest" } : null,
77
128
  };
78
129
  }
79
130
 
80
- function foldRows(projection: HistoryProjection, params: HistoryFilter & AnchorParams, selected: HistoryEvent[], anchors: { older_before: number | null; newer_after: number | null }): HistoryFoldedRow[] {
81
- const lower = params.after ?? 0;
82
- const upper = params.before ?? Number.POSITIVE_INFINITY;
131
+ function foldRows(projection: HistoryProjection, params: HistorySelection, selected: HistoryEvent[], cursors: Pick<HistoryPage, "page_older" | "page_newer">): HistoryFoldedRow[] {
83
132
  if (selected.length === 0) {
84
133
  // Even a range with no conversation can contain tool/context events.
85
- const hidden = allItems(projection).filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper && isFoldableEvent(event));
86
- return foldedRuns(hidden);
134
+ return foldedRuns(allItems(projection).filter((event) => inSelection(event, params) && isFoldableEvent(event)));
87
135
  }
88
- const windowEvents = allItems(projection)
89
- .filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper)
90
- .sort((a, b) => a.seq - b.seq);
136
+ const windowEvents = allItems(projection).filter((event) => inSelection(event, params)).sort((a, b) => a.seq - b.seq);
91
137
  const folded: HistoryFoldedRow[] = [];
92
138
  const firstSeq = selected[0]!.seq;
93
139
  const lastSeq = selected.at(-1)!.seq;
94
- if (anchors.older_before === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
140
+ if (cursors.page_older === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
95
141
  // pageData already ordered selected by seq.
96
142
  for (let i = 0; i + 1 < selected.length; i++) {
97
143
  const left = selected[i]!.seq;
98
144
  const right = selected[i + 1]!.seq;
99
145
  folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
100
146
  }
101
- if (anchors.newer_after === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
147
+ if (cursors.page_newer === null) folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
102
148
  return folded;
103
149
  }
104
150
 
105
- function pageData(projection: HistoryProjection, params: HistoryFilter & AnchorParams, vis: HistoryEvent[], selected: Candidate[], maxChars: number, folds: boolean): HistoryPage {
151
+ function pageData(projection: HistoryProjection, params: HistorySelection, vis: HistoryEvent[], selected: Candidate[], maxChars: number, folds: boolean): HistoryPage {
106
152
  const orderedSelected = [...selected].sort((a, b) => a.event.seq - b.event.seq);
107
153
  const selectedEvents = orderedSelected.map((candidate) => candidate.event);
108
- const anchors = pageAnchors(vis, selectedEvents, params.before, params.after);
154
+ const cursors = pageCursors(vis, selectedEvents, params.before_seq, params.after_seq);
109
155
  const visible = orderedSelected.map((candidate) => candidate.preview ?? visibleItem(candidate.event, maxChars, candidate.matchOffset));
110
156
  let rows: PageRow[] = visible;
111
157
  if (folds) {
112
- const folded = foldRows(projection, params, selectedEvents, anchors);
158
+ const folded = foldRows(projection, params, selectedEvents, cursors);
113
159
  rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
114
160
  }
115
- return { items: rows, ...anchors };
161
+ return { items: rows, ...cursors };
116
162
  }
117
163
 
118
- function orderedCandidates(vis: Candidate[], before: number | undefined, after: number | undefined, limit: number): Candidate[] {
164
+ /** Filter, then keep only literal matches when a query is present. Query shape errors refuse here. */
165
+ function selectionCandidates(projection: HistoryProjection, params: HistorySelection): Outcome<Candidate[]> {
166
+ let queries: string[] | undefined;
167
+ if (params.query !== undefined) {
168
+ try {
169
+ queries = searchQueries(params.query);
170
+ } catch (error) {
171
+ if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
172
+ throw error;
173
+ }
174
+ }
175
+ const events = filteredItems(projection, params, queries === undefined);
176
+ if (queries === undefined) return success(events.map((event) => ({ event })));
177
+ const needles = queries;
178
+ return success(events
179
+ .map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), needles) }))
180
+ .filter((candidate) => candidate.matchOffset >= 0));
181
+ }
182
+
183
+ /**
184
+ * Take the limit from the end `from` names, starting there so a budget for one row keeps the most
185
+ * important row. The selection is already filtered to its range; `from` never states a direction.
186
+ */
187
+ function orderedCandidates(vis: Candidate[], params: HistorySelection, limit: number): Candidate[] {
119
188
  const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
120
- if (before !== undefined && after !== undefined) return ascending.filter((candidate) => candidate.event.seq > after && candidate.event.seq < before).slice(0, limit);
121
- if (after !== undefined) return ascending.filter((candidate) => candidate.event.seq > after).slice(0, limit);
122
- if (before !== undefined) return ascending.filter((candidate) => candidate.event.seq < before).reverse().slice(0, limit);
123
- return ascending.slice(-limit).reverse();
189
+ const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
190
+ return params.from === "oldest" ? selected : selected.reverse();
124
191
  }
125
192
 
126
- /** Grow the page in query order; shorten the first preview only when no full row fits. */
127
- export function selectPage(projection: HistoryProjection, params: HistoryFilter & AnchorParams, vis: Candidate[], folds: boolean, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
128
- const before = params.before;
129
- const after = params.after;
130
- const limit = params.limit ?? 20;
131
- const candidates = orderedCandidates(vis, before, after, limit);
193
+ /**
194
+ * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
195
+ * Grow the page in selection order; shorten the first preview only when no full row fits.
196
+ */
197
+ export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
198
+ const bounds = resolveTimeBounds(params);
199
+ if (!bounds.ok) return bounds;
200
+ const scoped = { ...params, ...bounds.data };
201
+ const candidates = selectionCandidates(projection, scoped);
202
+ if (!candidates.ok) return candidates;
203
+ const vis = candidates.data;
204
+ const limit = scoped.limit ?? 20;
205
+ const folds = foldsRuns(scoped);
206
+ const ordered = orderedCandidates(vis, scoped, limit);
132
207
  const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
133
208
  const kept: Candidate[] = [];
134
- for (const candidate of candidates) {
135
- if (fits(pageData(projection, params, allVisible, [...kept, candidate], maxChars, folds))) {
209
+ for (const candidate of ordered) {
210
+ if (fits(pageData(projection, scoped, allVisible, [...kept, candidate], maxChars, folds))) {
136
211
  kept.push(candidate);
137
212
  continue;
138
213
  }
139
- if (kept.length === 0) kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, params, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
214
+ if (kept.length === 0) kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, scoped, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
140
215
  break;
141
216
  }
142
- const page = pageData(projection, params, allVisible, kept, maxChars, folds);
217
+ const page = pageData(projection, scoped, allVisible, kept, maxChars, folds);
143
218
  if (!fits(page)) {
144
- return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow the range with before/after or read one seq`, { rows: page.items.length });
219
+ return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow with before_seq/after_seq or since/until, or read one seq`);
145
220
  }
146
221
  return success(page);
147
- }
222
+ }