notesoup 0.59.2 → 0.60.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 (62) hide show
  1. package/README.md +3 -17
  2. package/dist/plugins/claude/src/helper.js +1 -2
  3. package/dist/plugins/codex/src/mcp.js +1 -2
  4. package/dist/plugins/dsh/tools.js +1 -2
  5. package/dist/plugins/pi/notes/tools.d.ts +1 -1
  6. package/dist/plugins/pi/notes/tools.js +2 -3
  7. package/dist/src/history/history.d.ts +10 -11
  8. package/dist/src/history/history.js +8 -19
  9. package/dist/src/history/query.d.ts +3 -14
  10. package/dist/src/history/query.js +73 -85
  11. package/dist/src/index.d.ts +1 -1
  12. package/dist/src/index.js +1 -1
  13. package/dist/src/notes/address.js +3 -3
  14. package/dist/src/notes/store.d.ts +2 -4
  15. package/dist/src/notes/store.js +1 -2
  16. package/dist/src/tools/history.d.ts +4 -6
  17. package/dist/src/tools/history.js +69 -29
  18. package/dist/src/tools/notes.d.ts +18 -78
  19. package/dist/src/tools/notes.js +39 -50
  20. package/dist/src/tools/schema.d.ts +0 -1
  21. package/dist/src/tools/schema.js +0 -1
  22. package/dist/test/claude-history.test.js +5 -6
  23. package/dist/test/claude-mod.test.js +6 -7
  24. package/dist/test/codex-history.test.js +1 -1
  25. package/dist/test/codex-plugin.test.js +1 -2
  26. package/dist/test/dependencies.test.js +2 -2
  27. package/dist/test/dsh.test.js +2 -2
  28. package/dist/test/history-corpus.test.js +21 -36
  29. package/dist/test/history-summary-cache.test.js +3 -3
  30. package/dist/test/history.integration.test.js +53 -106
  31. package/dist/test/host-neutral.test.js +1 -1
  32. package/dist/test/note-policy.test.js +5 -5
  33. package/dist/test/notes-cwd.test.js +5 -5
  34. package/dist/test/notes-query-namespaces.test.js +2 -6
  35. package/dist/test/notes.integration.test.js +30 -35
  36. package/dist/test/notes.test.js +12 -14
  37. package/dist/test/project-namespace.test.js +3 -3
  38. package/docs/architecture.md +3 -3
  39. package/docs/claude-code-mod.md +2 -2
  40. package/docs/codex.md +1 -1
  41. package/docs/dsh.md +2 -2
  42. package/docs/history-sessions.md +8 -9
  43. package/docs/notes-library.md +3 -3
  44. package/docs/tool-results.md +12 -6
  45. package/package.json +1 -1
  46. package/plugins/claude/dist/claude/helper.js +162 -153
  47. package/plugins/claude/skills/memory/SKILL.md +6 -6
  48. package/plugins/claude/src/helper.ts +1 -2
  49. package/plugins/codex/README.md +1 -1
  50. package/plugins/codex/dist/codex/notesoup.js +161 -152
  51. package/plugins/codex/src/mcp.ts +1 -2
  52. package/plugins/dsh/tools.ts +1 -2
  53. package/plugins/pi/notes/tools.ts +2 -3
  54. package/skills/memory/SKILL.md +6 -6
  55. package/src/history/history.ts +11 -16
  56. package/src/history/query.ts +67 -99
  57. package/src/index.ts +1 -1
  58. package/src/notes/address.ts +2 -2
  59. package/src/notes/store.ts +3 -6
  60. package/src/tools/history.ts +60 -29
  61. package/src/tools/notes.ts +39 -54
  62. package/src/tools/schema.ts +0 -1
@@ -38,15 +38,15 @@ Keep notes focused on what is true now; if a piece of past context still matters
38
38
 
39
39
  ## Finding things again
40
40
 
41
- For list/search, omit `glob` or use the collection alias `@default` for this session and current shared notebooks. Use `**` for all notebooks or `@sessions/*/**` for all sessions. Results carry readable note addresses; `@default` itself is not a read/write address.
41
+ In `notes_list`, omit `glob` for this session and the current shared notebooks. Use `**` for all notebooks or `@sessions/*/**` for all sessions.
42
42
 
43
- - **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.
44
- - **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
45
- - **An earlier window**: use its seq range from the boot window tree with `history_list`'s `before_seq` / `after_seq` bounds, or search for a remembered phrase.
43
+ - **A note**: add `glob` to narrow where `notes_list` looks, and `query` if you remember a phrase. Then use `notes_read` with the address and, for a match, its `offset_chars`.
44
+ - **Something that happened**: `history_list` browses or searches this session's events. Add `context: 1` with a `query` to include neighboring events. Use `history_read` with the seq for the whole event.
45
+ - **An earlier window**: use its seq range from the boot window tree with `history_list`'s exclusive `after` / `before` bounds, or search for a remembered phrase. With `after` you page forward; otherwise you page back from the newest eligible end.
46
46
  - **Another session**: pass `session: "<id-or-prefix>"` or `"pi:<id>"`, `"claude:<id>"`, `"codex:<id>"`, `"dsh:<id>"`. An unqualified selector checks this harness first. If ambiguous, use a longer ID or a harness prefix; never pick a candidate blindly.
47
- - **A phrase across sessions**: `history_list({ session: "*", query: "remembered phrase" })`, or restrict to a harness with `"pi:*"`. A wildcard cannot use `before_seq`/`after_seq` or `history_read`. Query results cover every role unless `roles` narrows them, are chronological, and have no paging cursors; narrow by time, role, query or session pattern instead. DSH sessions are discoverable only from DSH.
47
+ - **A phrase across sessions**: `history_list({ session: "*", query: "remembered phrase" })`, or restrict to a harness with `"pi:*"`. A wildcard takes ISO 8601 times only in `after` / `before` and cannot use `history_read`. Hits cover every role unless `roles` narrows them. Results are chronological and have no paging cursors; narrow by time, role, query or session pattern instead. DSH sessions are discoverable only from DSH.
48
48
 
49
- - **Recent sessions, no remembered phrase**: `history_list({ session: "*" })` returns one representative event per session, preferring its first visible user prompt, up to `limit` (default 20). Sessions are chosen newest-modified first (`from: "oldest"` reverses that), then results are sorted chronologically. Empty queries also browse. Role/time filters apply before choosing representatives; with `roles`, the latest matching event represents each session. No paging cursors.
49
+ - **Recent sessions, no remembered phrase**: `history_list({ session: "*" })` returns one representative event per session, preferring its first visible user prompt, up to `limit` (default 20). Sessions are chosen newest-modified first (oldest-modified first with `after`), then results are sorted chronologically. Empty queries also browse. Role/time filters apply before choosing representatives; with `roles`, the latest matching event represents each session. No paging cursors.
50
50
 
51
51
  Seqs are stable **within a session**. When a hit carries `session`, copy it together with `seq` into `history_read` and save both in your note. The paging/expand/neighborhood recipes already preserve the resolved session. Omit `session` only when you mean your current host session. A single unreadable or unsupported local transcript refuses explicitly; wildcards skip individual sessions that cannot load. An empty result is not proof the remembered event never happened.
52
52
 
@@ -46,7 +46,8 @@ export type HistoryWindow = { windowId: string; createdAt?: string; items: Histo
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
48
  /** The filters one selection applies before paging: roles, seq bounds, and parsed epoch-ms time bounds. */
49
- export type HistoryFilter = { roles?: HistoryRole[] | null; after_seq?: number; before_seq?: number; sinceMs?: number; untilMs?: number };
49
+ export type HistoryBound = { seq: number } | { at: number };
50
+ export type HistoryFilter = { roles?: HistoryRole[]; after?: HistoryBound; before?: HistoryBound };
50
51
 
51
52
  /** Native entries after the adapter allocates seqs and selects the active branch. */
52
53
  export type DecodedHistoryItem = {
@@ -221,6 +222,7 @@ export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
221
222
  export const HistoryPageItemSchema = Type.Object({
222
223
  session: Type.Optional(Type.String()),
223
224
  folded_before: Type.Optional(HistoryFoldedRowSchema),
225
+ context: Type.Optional(Type.Literal(true, { description: "A neighbor of a search hit, not a hit in this page." })),
224
226
  seq: Type.Integer({ minimum: 1 }),
225
227
  role: HistoryRoleSchema,
226
228
  created_at: Type.Union([Type.String(), Type.Null()]),
@@ -260,23 +262,16 @@ export function allItems(projection: HistoryProjection): HistoryEvent[] {
260
262
  return projection.windows.flatMap((current) => current.items);
261
263
  }
262
264
 
263
- /**
264
- * Whether one event is inside the selection: its seq bounds, and a half-open
265
- * [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
266
- * time or a time that cannot be read.
267
- */
268
- export function inSelection(event: HistoryEvent, params: HistoryFilter): boolean {
269
- if (params.after_seq !== undefined && event.seq <= params.after_seq) return false;
270
- if (params.before_seq !== undefined && event.seq >= params.before_seq) return false;
271
- if (params.sinceMs === undefined && params.untilMs === undefined) return true;
272
- if (event.createdAt === undefined) return false;
273
- const at = Date.parse(event.createdAt);
274
- return !Number.isNaN(at) && (params.sinceMs === undefined || at >= params.sinceMs) && (params.untilMs === undefined || at < params.untilMs);
265
+ function compareBound(event: HistoryEvent, bound: HistoryBound): number {
266
+ return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
267
+ }
268
+
269
+ export function matchesFilter(event: HistoryEvent, { after, before, roles }: HistoryFilter): boolean {
270
+ return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0)
271
+ && (!roles || roles.includes(event.role));
275
272
  }
276
273
 
277
274
  /** Ordered events inside the requested seq/time range and optional roles, before folding. */
278
275
  export function filteredItems(projection: HistoryProjection, params: HistoryFilter): HistoryEvent[] {
279
- return allItems(projection)
280
- .filter((item) => inSelection(item, params) && (!params.roles || params.roles.includes(item.role)))
281
- .sort((a, b) => a.seq - b.seq);
276
+ return allItems(projection).filter(event => matchesFilter(event, params)).sort((a, b) => a.seq - b.seq);
282
277
  }
@@ -1,11 +1,11 @@
1
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
- import { failure, success, type Outcome } from "../result.js";
4
- import { earliestMatchOffsetChars, InvalidQueryError, prefixFit, searchQueries } from "../text-match.js";
5
- import { eventDocument, filteredItems, 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";
3
+ import { success, type Outcome } from "../result.js";
4
+ import { earliestMatchOffsetChars, prefixFit } from "../text-match.js";
5
+ import { eventDocument, filteredItems, matchesFilter, 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
6
 
7
- type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
8
- type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; session?: string; multi?: boolean; discarded?: boolean; from?: HistoryOrder };
7
+ type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow; neighbors?: { events: HistoryEvent[]; index: number } };
8
+ type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; multi?: boolean; discarded?: boolean; forward?: boolean };
9
9
  const multiPages = new WeakSet<HistoryPage>();
10
10
  export function isMultiPage(page: HistoryPage): boolean { return multiPages.has(page); }
11
11
  export function markMultiPage(page: HistoryPage): HistoryPage {
@@ -13,46 +13,7 @@ export function markMultiPage(page: HistoryPage): HistoryPage {
13
13
  return page;
14
14
  }
15
15
 
16
- /** Which end of one selection `limit` is taken from; page items always come back ascending. */
17
- export type HistoryOrder = "newest" | "oldest";
18
-
19
- /**
20
- * What one list call selects. `before_seq`/`after_seq` choose a seq range and `since`/`until` a time
21
- * range; `from` chooses the end `limit` counts from; a `query` keeps only matching events, across
22
- * every role, with no folded rows.
23
- */
24
- export type HistorySelection = HistoryFilter & {
25
- session?: string;
26
- from?: HistoryOrder;
27
- limit?: number;
28
- query?: string | string[];
29
- since?: string;
30
- until?: string;
31
- max_chars_per_item?: number;
32
- };
33
-
34
- /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
35
- const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
36
-
37
- /** Epoch ms for one optional time param, or a refusal naming it. */
38
- function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
39
- if (value === undefined) return success(undefined);
40
- const match = ISO_8601.exec(value);
41
- const at = match === null ? undefined : Date.parse(match[1] === undefined ? `${value}Z` : value);
42
- return at === undefined || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
43
- }
44
-
45
- /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
46
- function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number; untilMs?: number }> {
47
- const since = timeBound("since", params.since);
48
- if (!since.ok) return since;
49
- const until = timeBound("until", params.until);
50
- if (!until.ok) return until;
51
- if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
52
- return failure("invalid_time", "`since` must be earlier than `until`.");
53
- }
54
- return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
55
- }
16
+ export type HistorySelection = HistoryFilter & { session?: string; limit?: number; query?: string[]; context?: number };
56
17
 
57
18
  export const HistoryPageSchema = Type.Object({
58
19
  notice: Type.Optional(Type.String()),
@@ -97,24 +58,32 @@ function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow |
97
58
  return { ...(session === undefined ? {} : { session }), first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
98
59
  }
99
60
 
100
- /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
61
+ // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
62
+ const visible = (event: HistoryEvent) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "";
63
+
64
+ function* queryHits(projection: HistoryProjection, params: HistorySelection, session?: string): Generator<Candidate> {
65
+ const { query, context } = params;
66
+ const events = filteredItems(projection, context ? {} : params).filter(visible);
67
+ for (const [index, event] of events.entries()) {
68
+ if (context && !matchesFilter(event, params)) continue;
69
+ const matchOffset = earliestMatchOffsetChars(eventDocument(event), query!);
70
+ if (matchOffset >= 0) yield { event, session, matchOffset, neighbors: context ? { events, index } : undefined };
71
+ }
72
+ }
73
+
101
74
  function prepareSelection(projection: HistoryProjection, params: HistorySelection): PreparedSelection {
102
- const folds = !params.roles && params.query === undefined;
75
+ const { query, roles, session } = params;
76
+ if (query) return { candidates: [...queryHits(projection, params, session)] };
103
77
  const candidates: Candidate[] = [];
104
78
  let run: HistoryEvent[] = [];
105
- for (const event of filteredItems(projection, params)) {
106
- if (folds && (event.role === "tool" || event.role === "context")) {
107
- run.push(event);
108
- continue;
79
+ for (const event of filteredItems(projection, params).filter(visible)) {
80
+ if (!roles && (event.role === "tool" || event.role === "context")) run.push(event);
81
+ else {
82
+ candidates.push({ event, session, before: foldedRun(run, session) });
83
+ run = [];
109
84
  }
110
- // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
111
- if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "") continue;
112
- const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query as string[]);
113
- if (matchOffset !== undefined && matchOffset < 0) continue;
114
- candidates.push({ event, ...(params.session === undefined ? {} : { session: params.session }), matchOffset, before: foldedRun(run, params.session) });
115
- run = [];
116
85
  }
117
- return { candidates, session: params.session, tail: foldedRun(run, params.session) };
86
+ return { candidates, tail: foldedRun(run, session) };
118
87
  }
119
88
 
120
89
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
@@ -129,52 +98,56 @@ function pageData(prepared: PreparedSelection, start: number, end: number, maxCh
129
98
  const page = {
130
99
  items,
131
100
  ...(end === candidates.length && tail ? { folded_after: tail } : {}),
132
- has_older: (start > 0 && start < end) || (!!prepared.discarded && prepared.from !== "oldest"),
133
- has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && prepared.from === "oldest"),
101
+ has_older: (start > 0 && start < end) || (!!prepared.discarded && !prepared.forward),
102
+ has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && !!prepared.forward),
134
103
  };
135
104
  return prepared.multi ? markMultiPage(page) : page;
136
105
  }
137
106
 
138
- /**
139
- * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
140
- * Grow the page in selection order; shorten the first preview only when no full row fits.
141
- */
142
- function resolveSelection(params: HistorySelection): Outcome<HistorySelection> {
143
- const bounds = resolveTimeBounds(params);
144
- if (!bounds.ok) return bounds;
145
- try {
146
- const queries = searchQueries(params.query);
147
- return success({ ...params, ...bounds.data, query: queries.length ? queries : undefined });
148
- } catch (error) {
149
- if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
150
- throw error;
151
- }
152
- }
153
-
154
107
  export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
155
- const scoped = resolveSelection(params);
156
- if (!scoped.ok) return scoped;
157
- return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
158
- }
159
-
160
- /** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
161
- export function corpusSelection(params: HistorySelection): Outcome<HistorySelection> {
162
- if (params.before_seq !== undefined || params.after_seq !== undefined) return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
163
- return resolveSelection(params);
108
+ return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
164
109
  }
165
110
 
166
111
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
167
112
  export function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined {
168
- const events = filteredItems(projection, scoped).filter((event) =>
169
- (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "");
113
+ const events = filteredItems(projection, scoped).filter(visible);
170
114
  if (scoped.roles) return events.at(-1);
171
115
  return events.find((event) => event.role === "user")
172
116
  ?? events.filter((event) => event.role === "assistant").at(-1)
173
117
  ?? events.at(-1);
174
118
  }
175
119
 
176
- const eventTime = (event: HistoryEvent) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
177
- const compareCorpus = (a: Candidate, b: Candidate) => eventTime(a.event) - eventTime(b.event) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq;
120
+ function eventTime(timestamp?: string | null): number {
121
+ const at = Date.parse(timestamp ?? "");
122
+ return Number.isNaN(at) ? -Infinity : at;
123
+ }
124
+ const compareCorpus = (a: Candidate, b: Candidate) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq;
125
+
126
+ /** Fill the remaining budget nearest first. Shared session/seq keys merge overlapping windows. */
127
+ function addContext(page: HistoryPage, hits: Candidate[], radius: number, fits: (page: HistoryPage) => boolean, maxChars: number): void {
128
+ const key = (session: string | undefined, seq: number) => `${session ?? ""}\0${seq}`;
129
+ const seen = new Set(page.items.map(item => key(item.session, item.seq)));
130
+ const compare = (a: HistoryPageItem, b: HistoryPageItem) => (isMultiPage(page) ? eventTime(a.created_at) - eventTime(b.created_at) || a.session!.localeCompare(b.session!) : 0) || a.seq - b.seq;
131
+ for (let distance = 1; distance <= radius; distance++) {
132
+ let found = false;
133
+ for (const { neighbors, session } of hits) {
134
+ if (!neighbors) continue;
135
+ for (const index of [neighbors.index - distance, neighbors.index + distance]) {
136
+ const event = neighbors.events[index];
137
+ if (!event) continue;
138
+ found = true;
139
+ const id = key(session, event.seq);
140
+ if (seen.has(id)) continue;
141
+ const item: HistoryPageItem = { ...visibleItem(event, maxChars), ...(session === undefined ? {} : { session }), context: true };
142
+ const previous = page.items;
143
+ page.items = [...previous, item].sort(compare);
144
+ if (!fits(page)) { page.items = previous; return; }
145
+ seen.add(id);
146
+ }
147
+ }
148
+ if (!found) return;
149
+ }
150
+ }
178
151
 
179
152
  /** Keep only the requested end of the globally ordered selection while sessions are released. */
180
153
  export class CorpusCollector {
@@ -195,7 +168,7 @@ export class CorpusCollector {
195
168
  }
196
169
  if (this.candidates.length === this.limit) {
197
170
  this.discarded = true;
198
- if (this.scoped.from === "oldest") {
171
+ if (this.scoped.after) {
199
172
  if (low === this.limit) return;
200
173
  this.candidates.pop();
201
174
  } else {
@@ -217,25 +190,19 @@ export class CorpusCollector {
217
190
  /** Returns whether this session contributes an overview representative. */
218
191
  add(session: string, projection: HistoryProjection): boolean {
219
192
  if (this.scoped.query === undefined) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
220
- for (const event of filteredItems(projection, this.scoped)) {
221
- const document = eventDocument(event);
222
- if ((event.role === "user" || event.role === "assistant") && document === "") continue;
223
- const matchOffset = earliestMatchOffsetChars(document, this.scoped.query as string[]);
224
- if (matchOffset >= 0) this.admit({ session, event, matchOffset });
225
- }
193
+ for (const hit of queryHits(projection, this.scoped, session)) this.admit(hit);
226
194
  return true;
227
195
  }
228
196
 
229
197
  page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited = false): HistoryPageResult {
230
- return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
198
+ return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
231
199
  }
232
200
  }
233
201
 
234
202
  function selectPrepared(prepared: PreparedSelection, scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
235
203
  const { candidates } = prepared;
236
204
  // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
237
- const from = scoped.from ?? (scoped.after_seq !== undefined ? "oldest" : "newest");
238
- const newest = from === "newest";
205
+ const newest = scoped.after === undefined;
239
206
  let start = newest ? candidates.length : 0;
240
207
  let end = start;
241
208
  const limit = Math.max(1, scoped.limit ?? 20);
@@ -257,5 +224,6 @@ function selectPrepared(prepared: PreparedSelection, scoped: HistorySelection, f
257
224
  }
258
225
  const page = pageData(prepared, start, end, maxChars);
259
226
  if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
227
+ if (scoped.context) addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
260
228
  return success(page);
261
229
  }
package/src/index.ts CHANGED
@@ -42,7 +42,7 @@ export type { BootToolNames } from "./boot/text.js";
42
42
 
43
43
  // Operations: the schemas and typed outcomes a host registers as its own tools, over a
44
44
  // host-supplied notes tool context or decoded history projection/lazy corpus context.
45
- export { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "./tools/notes.js";
45
+ export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
46
46
  export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
47
47
  export { historyList, historyRead } from "./tools/history.js";
48
48
  export { projectHistory } from "./history/history.js";
@@ -48,8 +48,8 @@ export function globToRegExp(pattern: string): RegExp {
48
48
 
49
49
  /** Glob patterns are not virtual paths (`*` is legal), so they get their own guard. */
50
50
  export function assertGlobPattern(value: unknown): string | undefined {
51
- if (value === undefined || value === null || value === "") return undefined;
52
- if (typeof value !== "string") throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a string.`);
51
+ if (value === undefined) return undefined;
52
+ if (typeof value !== "string" || !value) throw new NoteError("invalid_pattern", `glob ${shown(value)} must be a non-empty string; omit it for the current notebooks.`);
53
53
  if (value.includes("\0") || value.includes("\\")) throw new NoteError("invalid_pattern", `glob ${shown(value)} can't contain "\\" or NUL.`);
54
54
  return value;
55
55
  }
@@ -29,10 +29,8 @@ export type NoteSearchRow = { address: string; scope: Scope; path: string; meta:
29
29
  export type EditOperation = { oldText: string; newText: string };
30
30
  export type WriteOptions = NotePolicyFields & { origin?: Origin };
31
31
  export type EditOptions = NotePolicyFields & { origin?: Origin; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
32
- /** Omitted/null/empty glob or bare @default selects current notebooks; explicit globs match full addresses.
33
- * A pattern without `@` or `/` matches filenames at any depth; relative paths with `/` match the current session.
34
- */
35
- export type NotesQuery = { glob?: string | null; crumpled?: boolean };
32
+ /** Omit glob for current notebooks. A pattern without `@` or `/` matches filenames at any depth. */
33
+ export type NotesQuery = { glob?: string; crumpled?: boolean };
36
34
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
37
35
  export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope };
38
36
  export type NoteWriteResult = { meta: NoteMeta; warnings: string[]; outcome: "created" | "overwrote" | "uncrumpled" };
@@ -480,8 +478,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
480
478
  }
481
479
 
482
480
  async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
483
- const glob = assertGlobPattern(options.glob);
484
- const pattern = glob === "@default" ? undefined : glob;
481
+ const pattern = assertGlobPattern(options.glob);
485
482
  const normalized = normalizePattern(pattern, identity);
486
483
  const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
487
484
  const namespaces = await namespacesForPattern(pattern, identity, status);
@@ -4,9 +4,10 @@ import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from
4
4
  import { failure, success, type Outcome } from "../result.js";
5
5
  import { fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, TextWindowRequestSchema, TextWindowSchema, type Operation } from "./result.js";
6
6
  import { historyRoles, searchQuery } from "./schema.js";
7
- import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage, type HistoryPage, type HistoryPageResult } from "../history/query.js";
7
+ import { InvalidQueryError, searchQueries } from "../text-match.js";
8
+ import { HistoryPageSchema, CorpusCollector, isMultiPage, markMultiPage, selectPage, type HistoryPage, type HistoryPageResult, type HistorySelection } from "../history/query.js";
8
9
  import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
9
- import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFoldedRow, type HistoryPageItem } from "../history/history.js";
10
+ import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryBound, type HistoryFoldedRow, type HistoryPageItem } from "../history/history.js";
10
11
 
11
12
  /** One read: identity, tool summary and a flat document slice. */
12
13
  const HistoryReadDataSchema = Type.Object({
@@ -39,7 +40,7 @@ function toolHeader(item: { role: string; tool?: string; tool_status?: string; o
39
40
 
40
41
  function renderPageItem(item: HistoryPageItem): string {
41
42
  const tool = toolHeader(item);
42
- const lines = tool === undefined ? [header(item)] : [header(item), tool];
43
+ const lines = [header(item) + (item.context ? " | search context" : ""), ...(tool ? [tool] : [])];
43
44
  if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
44
45
  lines.push(item.content);
45
46
  return lines.join("\n");
@@ -48,7 +49,7 @@ function renderPageItem(item: HistoryPageItem): string {
48
49
  function renderFoldedRow(row: HistoryFoldedRow): string {
49
50
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
50
51
  const identity = row.session === undefined ? {} : { session: row.session };
51
- const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
52
+ const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] })}`;
52
53
  return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
53
54
  }
54
55
 
@@ -58,21 +59,21 @@ function renderPage(page: HistoryPage): string {
58
59
  const body = [...page.items.flatMap((item) => [...(item.folded_before ? [renderFoldedRow(item.folded_before)] : []), renderPageItem(item)]), ...(page.folded_after ? [renderFoldedRow(page.folded_after)] : [])].join("\n\n");
59
60
  if (isMultiPage(page)) {
60
61
  const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
61
- return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
62
+ return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with time bounds (after/before), query, roles or the session pattern` : "");
62
63
  }
63
- const first = page.items[0]!;
64
- const last = page.items.at(-1)!;
65
-
64
+ const hits = page.items.filter(item => !item.context);
65
+ const first = hits[0]!;
66
+ const last = hits.at(-1)!;
66
67
  const cursors = [
67
- page.has_older ? `→ older: ${JSON.stringify({ ...(first.session === undefined ? {} : { session: first.session }), before_seq: first.seq })}` : "",
68
- page.has_newer ? `→ newer: ${JSON.stringify({ ...(last.session === undefined ? {} : { session: last.session }), after_seq: last.seq })}` : "",
68
+ page.has_older ? `→ older: ${JSON.stringify({ session: first.session, before: first.seq })}` : "",
69
+ page.has_newer ? `→ newer: ${JSON.stringify({ session: last.session, after: last.seq })}` : "",
69
70
  ].filter((line) => line !== "");
70
71
  return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
71
72
  }
72
73
 
73
74
  function renderRead(data: HistoryReadData): string {
74
75
  const tool = toolHeader(data);
75
- const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), after_seq: Math.max(0, data.seq - 10), before_seq: data.seq + 10 })})`;
76
+ const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), after: Math.max(0, data.seq - 10), before: data.seq + 10 })})`;
76
77
  return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
77
78
  }
78
79
 
@@ -86,25 +87,53 @@ const plainText: HistoryTextWrapper = (text) => text;
86
87
  function pageOutcome(result: HistoryPageResult): Outcome<HistoryPage> {
87
88
  if (!("pageTooLarge" in result)) return result;
88
89
  const { count, multi } = result.pageTooLarge;
89
- const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
90
+ const narrow = multi ? "narrow the session pattern, query, roles or time bounds (`after`/`before`), or read one session/seq with `history_read`" : "narrow with `after`/`before`, pass `roles` to skip folding, or `history_read` one seq";
90
91
  return failure("page_too_large", `Even trimmed to their shortest, these ${count} rows${multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
91
92
  }
92
93
 
93
94
  /* ------------------------------------------------------------------ history_list */
94
95
 
96
+ const boundParameter = (description: string) => Type.Optional(Type.Union([Type.String(), Type.Number()], { description: `${description} Use a seq (number or digits) or ISO 8601 time (UTC without offset); wildcards take only times.` }));
95
97
  export const historyListParameters = Type.Object({
96
98
  session: Type.Optional(Type.String({ minLength: 1, description: "Whose record: a session ID or prefix (pi:, claude:, codex:, dsh: allowed). Leave it out for this one. `*` means every recent session." })),
97
- query: Type.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
98
99
  roles: historyRoles(),
99
- before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "Only entries before this seq." })),
100
- after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "Only entries after this seq; 0 starts from the first page." })),
101
- since: Type.Optional(Type.String({ minLength: 1, description: "Only entries at or after this time (ISO 8601; UTC without an offset)." })),
102
- until: Type.Optional(Type.String({ minLength: 1, description: "Only entries before this time (ISO 8601; UTC without an offset)." })),
103
- from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "Which end `limit` counts from: newest or oldest. Entries still read oldest first." })),
104
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "How many entries per page; folded runs don't count." })),
100
+ query: Type.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
101
+ after: boundParameter("Start strictly after this bound, paging forward; 0 starts at the oldest event."),
102
+ before: boundParameter("Stop strictly before this bound; without `after`, take the newest eligible events."),
103
+ context: Type.Optional(Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Neighboring events on each side of a hit in its own session; requires a query." })),
104
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "How many events or hits per page; folds and search context don't count." })),
105
105
  max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." })),
106
106
  }, { additionalProperties: false });
107
107
 
108
+ const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
109
+ function parseBound(name: "after" | "before", value?: number | string): Outcome<HistoryBound | undefined> {
110
+ if (value === undefined) return success(undefined);
111
+ if (typeof value === "number" || /^\d+$/.test(value)) {
112
+ const seq = Number(value);
113
+ if (Number.isSafeInteger(seq) && seq >= 0) return success({ seq });
114
+ } else if (typeof value === "string") {
115
+ const match = ISO_8601.exec(value);
116
+ const at = match ? Date.parse(match[1] ? value : `${value}Z`) : NaN;
117
+ if (!Number.isNaN(at) && new Date(value.slice(0, 10)).toISOString().startsWith(value.slice(0, 10))) return success({ at });
118
+ }
119
+ return failure("invalid_bounds", `\`${name}\` must be a non-negative integer seq or an ISO 8601 time; got ${JSON.stringify(value)}.`);
120
+ }
121
+
122
+ function parseSelection(params: Static<typeof historyListParameters>): Outcome<HistorySelection> {
123
+ const after = parseBound("after", params.after);
124
+ if (!after.ok) return after;
125
+ const before = parseBound("before", params.before);
126
+ if (!before.ok) return before;
127
+ try {
128
+ const query = searchQueries(params.query);
129
+ if (!query.length && params.context !== undefined) return failure("invalid_params", "`context` requires a non-empty `query`.");
130
+ return success({ after: after.data, before: before.data, query: query.length ? query : undefined, roles: params.roles, context: params.context, limit: params.limit });
131
+ } catch (error) {
132
+ if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
133
+ throw error;
134
+ }
135
+ }
136
+
108
137
  export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryContext, HistoryTextWrapper?]> = {
109
138
  name: "history_list",
110
139
  label: "History list items",
@@ -112,33 +141,35 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
112
141
  parameters: historyListParameters,
113
142
  outputSchema: resultSchema(HistoryPageSchema),
114
143
  async execute(params, context, wrapText = plainText) {
144
+ const selection = parseSelection(params);
145
+ if (!selection.ok) return selection;
146
+ const scoped = selection.data;
115
147
  // Charge wrapped rendering, identities, notices and recipes, not only event previews.
116
148
  const fits = (page: HistoryPage) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
117
149
  const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
118
- if (params.session === undefined) return pageOutcome(selectPage(await currentHistory(context), params, fits, maxChars));
150
+ if (params.session === undefined) return pageOutcome(selectPage(await currentHistory(context), scoped, fits, maxChars));
119
151
  const selector = parseSessionSelector(params.session);
120
152
  if (!selector.ok) return selector;
121
153
  const corpus = "corpus" in context ? context.corpus : undefined;
122
154
  if (selector.data.wildcard) {
123
- const scoped = corpusSelection(params);
124
- if (!scoped.ok) return scoped;
155
+ const { after, before, query, roles } = scoped;
156
+ if ((after && "seq" in after) || (before && "seq" in before)) return failure("invalid_bounds", "Wildcard history requires times, not seqs, for `after` and `before`.");
125
157
  if (corpus === undefined) return failure("unknown_session", "This host supplied no cross-session history corpus.");
126
158
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
127
- const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
128
- if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
129
- const representative = !queries && scoped.data.roles === undefined && scoped.data.since === undefined && scoped.data.until === undefined;
130
- const collector = new CorpusCollector(scoped.data);
159
+ if (!query) sessions.sort((a, b) => (after ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
160
+ const representative = !query && !roles && !after && !before;
161
+ const collector = new CorpusCollector(scoped);
131
162
  let qualifying = 0;
132
163
  const notices: string[] = [];
133
164
  let unvisited = false;
134
165
  for (const [index, session] of sessions.entries()) {
135
- const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
166
+ const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, query);
136
167
  if (!result.ok || !result.data) continue;
137
168
  const added = "projection" in result.data ? collector.add(sessionIdentity(session), result.data.projection) : collector.addRepresentative(sessionIdentity(session), result.data.event);
138
169
  if (!added) continue;
139
170
  qualifying++;
140
171
  if (result.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
141
- if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
172
+ if (!query && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
142
173
  unvisited = index + 1 < sessions.length;
143
174
  break;
144
175
  }
@@ -152,7 +183,7 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
152
183
  const loaded = await loadHistorySession(target.data);
153
184
  if (!loaded.ok) return loaded;
154
185
  const notice = loaded.data.notice === undefined ? {} : { notice: loaded.data.notice };
155
- const result = pageOutcome(selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
186
+ const result = pageOutcome(selectPage(loaded.data.projection, { ...scoped, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
156
187
  return result.ok ? success({ ...result.data, ...notice }) : result;
157
188
  },
158
189
  render: (result) => renderOutcome(result, renderPage),