notesoup 0.59.1 → 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 (79) hide show
  1. package/README.md +3 -17
  2. package/dist/plugins/claude/src/helper.js +3 -4
  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/claude.d.ts +3 -1
  8. package/dist/src/history/claude.js +40 -4
  9. package/dist/src/history/history.d.ts +10 -11
  10. package/dist/src/history/history.js +8 -19
  11. package/dist/src/history/prefilter.d.ts +1 -1
  12. package/dist/src/history/prefilter.js +14 -9
  13. package/dist/src/history/query.d.ts +3 -14
  14. package/dist/src/history/query.js +73 -85
  15. package/dist/src/index.d.ts +1 -1
  16. package/dist/src/index.js +1 -1
  17. package/dist/src/notes/address.js +3 -3
  18. package/dist/src/notes/store.d.ts +2 -4
  19. package/dist/src/notes/store.js +1 -2
  20. package/dist/src/tools/history.d.ts +4 -6
  21. package/dist/src/tools/history.js +69 -29
  22. package/dist/src/tools/notes.d.ts +18 -78
  23. package/dist/src/tools/notes.js +39 -50
  24. package/dist/src/tools/schema.d.ts +0 -1
  25. package/dist/src/tools/schema.js +0 -1
  26. package/dist/test/claude-history.test.js +27 -6
  27. package/dist/test/claude-mod.test.js +19 -8
  28. package/dist/test/codex-history.test.js +1 -1
  29. package/dist/test/codex-plugin.test.js +1 -2
  30. package/dist/test/dependencies.test.js +2 -2
  31. package/dist/test/dsh.test.js +2 -2
  32. package/dist/test/history-corpus.test.js +21 -36
  33. package/dist/test/history-prefilter.test.js +5 -0
  34. package/dist/test/history-summary-cache.test.js +3 -3
  35. package/dist/test/history.integration.test.js +53 -106
  36. package/dist/test/host-neutral.test.js +1 -1
  37. package/dist/test/note-policy.test.js +5 -5
  38. package/dist/test/notes-cwd.test.js +5 -5
  39. package/dist/test/notes-query-namespaces.test.js +2 -6
  40. package/dist/test/notes.integration.test.js +30 -35
  41. package/dist/test/notes.test.js +12 -14
  42. package/dist/test/project-namespace.test.js +3 -3
  43. package/docs/architecture.md +3 -3
  44. package/docs/claude-code-mod.md +5 -3
  45. package/docs/codex.md +1 -1
  46. package/docs/dsh.md +2 -2
  47. package/docs/history-sessions.md +9 -10
  48. package/docs/notes-library.md +3 -3
  49. package/docs/tool-results.md +12 -6
  50. package/package.json +1 -1
  51. package/plugins/claude/dist/claude/helper.js +214 -173
  52. package/plugins/claude/hooks/register.ts +8 -6
  53. package/plugins/claude/skills/memory/SKILL.md +6 -6
  54. package/plugins/claude/src/helper.ts +3 -4
  55. package/plugins/codex/README.md +1 -1
  56. package/plugins/codex/dist/codex/notesoup.js +176 -160
  57. package/plugins/codex/src/mcp.ts +1 -2
  58. package/plugins/dsh/tools.ts +1 -2
  59. package/plugins/paseo/README.md +16 -0
  60. package/plugins/paseo/client/brain-empty-card.tsx +5 -3
  61. package/plugins/paseo/client/markdown-core.tsx +189 -0
  62. package/plugins/paseo/client/markdown.tsx +38 -135
  63. package/plugins/paseo/client/notes-op-card.tsx +15 -12
  64. package/plugins/paseo/client/paper-card.tsx +1 -3
  65. package/plugins/paseo/client/sticky-card.tsx +2 -1
  66. package/plugins/paseo/client/typography.ts +24 -0
  67. package/plugins/paseo/test/markdown-core.test.ts +75 -0
  68. package/plugins/pi/notes/tools.ts +2 -3
  69. package/skills/memory/SKILL.md +6 -6
  70. package/src/history/claude.ts +31 -4
  71. package/src/history/history.ts +11 -16
  72. package/src/history/prefilter.ts +13 -9
  73. package/src/history/query.ts +67 -99
  74. package/src/index.ts +1 -1
  75. package/src/notes/address.ts +2 -2
  76. package/src/notes/store.ts +3 -6
  77. package/src/tools/history.ts +60 -29
  78. package/src/tools/notes.ts +39 -54
  79. package/src/tools/schema.ts +0 -1
package/README.md CHANGED
@@ -31,23 +31,9 @@ pi -e npm:notesoup
31
31
  - **Durable context windows.** `/fresh-window` (alias `/empty`) clears and stops, with any command text available for close-out notes. Separate human input received during emptying continues in the fresh window. The model can also request a window itself with `empty_brain`, and a budget close-out fires automatically before the window runs out. Abort and ordinary errors never count as completion; the raw conversation stays in the session, just out of the next context.
32
32
  - **A boot block at every window head.** Pi keeps the window identity and notes snapshot in a hidden user-role boot; its fixed recovery protocol and pinned-page teaching live in a named system section. Every note body, including `@human` pins, stays user-role data. Claude, Codex and dsh keep their existing combined boot injection.
33
33
  - **`get_context_remaining`** — how much room the brain has left before the hard-reserve wipe, including the warning runway.
34
- - **Seven history/notes tools**, flattened from the original Codex actions:
35
-
36
- | Codex action | Pi tool |
37
- | --- | --- |
38
- | `history.list_items` | `history_list` |
39
- | `history.read_item` | `history_read` |
40
- | `history.search_contents` | `history_list` (`query`) |
41
- | `notes.write` | `notes_write` |
42
- | `notes.update` | `notes_update` |
43
- | `notes.rename` | `notes_update` (`rename_to`) |
44
- | `notes.read` | `notes_read` |
45
- | `notes.list` | `notes_list` |
46
- | `notes.search` | `notes_search` |
47
-
48
- - **Migration**: `history_search` is gone; pass `query` to `history_list`.
49
- - **Cross-session history**: both history tools accept `session: "<id-or-prefix>"` or `"<harness>:<id>"` (`pi`, `claude`, `codex`, `dsh`). `history_list({ session: "*", query: "phrase" })` searches local transcripts across harnesses; hits carry the session to copy into `history_read`. Omit `session` for unchanged current-session behavior. See [cross-session history](docs/history-sessions.md) for discovery roots, refusals and offline limits.
50
- - **Migration (0.40.0)**: parameters renamed: `order` → `from`, `before`/`after` → `before_seq`/`after_seq`, `limit_chars` → `max_chars`, `wastebasket` → `crumpled`, `pattern` → `glob` (the standalone library's options included), and `notes_update`'s `change_kind` value `file` → `moved`. Old names are refused.
34
+ - **Notes:** `notes_list` browses current notebooks by default. Add `glob` to select notebooks or paths and `query` for literal, case-insensitive matches with lines and read offsets. Open a page with `notes_read`, create or replace one with `notes_write`, and edit, move or crumple it with `notes_update`.
35
+ - **History:** `history_list` browses or searches with `query`. Page with exclusive `after` / `before` seqs or ISO 8601 times; add `context` to see neighboring events around hits. `history_read` opens one event by seq.
36
+ - **Cross-session history:** both history tools accept `session: "<id-or-prefix>"` or `"<harness>:<id>"` (`pi`, `claude`, `codex`, `dsh`). `history_list({ session: "*", query: "phrase" })` searches local transcripts across harnesses; hits carry the session to copy into `history_read`. Omit `session` to use the current session. See [cross-session history](docs/history-sessions.md) for discovery roots, refusals and offline limits.
51
37
 
52
38
  - **Runtime toggle** — `/notesoup off` stops new automatic resets; `/notesoup on` re-enables them; bare `/notesoup` reports the state.
53
39
  - **Context cap (Pi and Claude)** — `/notesoup cap 100k` limits the capacity used by notesoup's budget to `min(model window, 100000)`. Existing reserves and warning margins are deducted from that capacity; 100k is not the used-token reset point. `/notesoup cap` shows the configured cap and `/notesoup cap off` removes it. Whole tokens and decimal `k`/`m` suffixes are accepted; caps too small for the host's reserves are refused. The cap applies only to the running session, survives notesoup resets and model changes, and is lost on reload/restart/session switch. It never writes host settings or environment variables, changes the provider's advertised model window, or enables disabled automatic resets.
@@ -2,7 +2,7 @@ import { realpathSync } from "node:fs";
2
2
  import { pathToFileURL } from "node:url";
3
3
  import { Check } from "typebox/value";
4
4
  import { paramProblem } from "../../../src/tools/schema.js";
5
- import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
5
+ import { notesList, notesRead, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
6
6
  import { historyList, historyRead } from "../../../src/tools/history.js";
7
7
  import { localHistoryCorpus } from "../../../src/history/local.js";
8
8
  import { readClaudeHistory } from "./history.js";
@@ -38,7 +38,6 @@ const OPERATIONS = {
38
38
  notes_update: boundOperation(notesUpdate),
39
39
  notes_read: boundOperation(notesRead),
40
40
  notes_list: boundOperation(notesList),
41
- notes_search: boundOperation(notesSearch),
42
41
  };
43
42
  const HISTORY_OPERATIONS = {
44
43
  history_list: boundOperation(historyList),
@@ -94,8 +93,8 @@ export async function dispatch(request, historyOptions = {}) {
94
93
  const id = identity(value.identity);
95
94
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
96
95
  const tool = value.tool;
96
+ const current = () => readClaudeHistory(historySource(value.history, id.sessionId), { waitForHead: true });
97
97
  if (value.params.session !== undefined) {
98
- const current = () => readClaudeHistory(historySource(value.history, id.sessionId));
99
98
  const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id.sessionId, async load() {
100
99
  const projection = await current();
101
100
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
@@ -103,7 +102,7 @@ export async function dispatch(request, historyOptions = {}) {
103
102
  } } });
104
103
  return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
105
104
  }
106
- const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
105
+ const projection = await current();
107
106
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
108
107
  const wrapText = (text) => notice + text;
109
108
  const params = value.params;
@@ -4,7 +4,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
4
4
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5
5
  import { Check } from "typebox/value";
6
6
  import { paramProblem } from "../../../src/tools/schema.js";
7
- import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
7
+ import { notesList, notesRead, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
8
8
  import { historyList, historyRead } from "../../../src/tools/history.js";
9
9
  import { wireResult } from "../../../src/tools/result.js";
10
10
  import { CodexIdentityError, notesIdentityFor, pluginDataRoot, readBinding, rootSessionIdOf, safeThreadId, turnModel } from "./identity.js";
@@ -17,7 +17,6 @@ const OPERATIONS = {
17
17
  notes_update: { operation: notesUpdate, history: false },
18
18
  notes_read: { operation: notesRead, history: false },
19
19
  notes_list: { operation: notesList, history: false },
20
- notes_search: { operation: notesSearch, history: false },
21
20
  history_list: { operation: historyList, history: true },
22
21
  history_read: { operation: historyRead, history: true },
23
22
  };
@@ -1,7 +1,7 @@
1
1
  import { HarnessError } from "@deepseek-ai/dsh-llm";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
3
  import { Check, Errors } from "typebox/value";
4
- import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../src/tools/notes.js";
4
+ import { notesList, notesRead, notesUpdate, notesWrite } from "../../src/tools/notes.js";
5
5
  import { historyList, historyRead } from "../../src/tools/history.js";
6
6
  import { success } from "../../src/result.js";
7
7
  import { historyContext } from "./history.js";
@@ -78,7 +78,6 @@ export function registerTools(ctx, engine) {
78
78
  register(ctx, notesUpdate, (agent) => [toolContext(agent)]);
79
79
  register(ctx, notesRead, (agent) => [toolContext(agent)]);
80
80
  register(ctx, notesList, (agent) => [toolContext(agent)]);
81
- register(ctx, notesSearch, (agent) => [toolContext(agent)]);
82
81
  register(ctx, historyList, (agent) => [historyContext(ctx, agent.session.id)]);
83
82
  register(ctx, historyRead, (agent) => [historyContext(ctx, agent.session.id)]);
84
83
  ctx.tools.register(defineTool({
@@ -1,3 +1,3 @@
1
1
  import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
2
+ /** Register the shared note operations and the three hidden dream tools; an open dream widens the note identity. */
3
3
  export declare function registerNotesTools(pi: ExtensionAPI): void;
@@ -1,5 +1,5 @@
1
1
  import { generateDiffString } from "@earendil-works/pi-coding-agent";
2
- import { notesWrite, notesUpdate, notesRead, notesList, notesSearch } from "../../../src/tools/notes.js";
2
+ import { notesWrite, notesUpdate, notesRead, notesList } from "../../../src/tools/notes.js";
3
3
  import { abandonDream, dreamBegin, dreamEnd, dreamForget, dreamingIdentity } from "../../../src/tools/dream.js";
4
4
  import { notesIdentityFromPi } from "./adapter.js";
5
5
  import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
@@ -8,7 +8,7 @@ import { notesToolContext } from "../../../src/tools/notes-context.js";
8
8
  function renderDiff(change) {
9
9
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
10
10
  }
11
- /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
11
+ /** Register the shared note operations and the three hidden dream tools; an open dream widens the note identity. */
12
12
  export function registerNotesTools(pi) {
13
13
  // One pending or open dream per session: shutdown releases ownership without the end commit.
14
14
  const dreams = new Map();
@@ -34,7 +34,6 @@ export function registerNotesTools(pi) {
34
34
  }, NOTES_NAMESPACE, notesUpdateRenderers);
35
35
  registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, toolContext(ctx)), NOTES_NAMESPACE, notesReadRenderers);
36
36
  registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
37
- registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
38
37
  registerOperation(pi, dreamBegin, (params, ctx) => dreamBegin.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
39
38
  registerOperation(pi, dreamForget, (params, ctx) => dreamForget.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
40
39
  registerOperation(pi, dreamEnd, (params, ctx) => dreamEnd.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
@@ -15,4 +15,6 @@ export declare function claudeHistoryFromJsonl(text: string, source: Omit<Claude
15
15
  export declare function offlineClaudeHead(text: string): string;
16
16
  /** Select an offline head and build its projection from the same decoded records. */
17
17
  export declare function offlineClaudeHistoryFromJsonl(text: string, sessionId: string): ClaudeHistoryProjection;
18
- export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
18
+ export declare function readClaudeHistory(source: ClaudeHistorySource, { waitForHead }?: {
19
+ waitForHead?: boolean | undefined;
20
+ }): Promise<ClaudeHistoryProjection>;
@@ -1,7 +1,11 @@
1
1
  /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
- import { readFile } from "node:fs/promises";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { setTimeout as sleep } from "node:timers/promises";
3
4
  import { isDeepStrictEqual } from "node:util";
4
5
  import { contentText, projectHistory } from "./history.js";
6
+ class UnpersistedClaudeHead extends Error {
7
+ constructor() { super("Claude history active head is not persisted yet; retry after the transcript write"); }
8
+ }
5
9
  const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
6
10
  const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
7
11
  function object(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
@@ -199,7 +203,7 @@ function claudeHistoryFromRows(rows, source) {
199
203
  if (!source.headUuid)
200
204
  throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
201
205
  if (!nodes.has(source.headUuid))
202
- throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
206
+ throw new UnpersistedClaudeHead();
203
207
  // The inference tree uses the latest rewritten parents. At a compact boundary the logical
204
208
  // parent and preserved segments use ORIGINAL ancestry: the old context is still history.
205
209
  const selected = new Set(), visited = new Set(), visiting = new Set();
@@ -345,8 +349,40 @@ export function offlineClaudeHistoryFromJsonl(text, sessionId) {
345
349
  const rows = rowsOf(text);
346
350
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
347
351
  }
348
- export async function readClaudeHistory(source) {
352
+ export async function readClaudeHistory(source, { waitForHead = false } = {}) {
349
353
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
350
354
  throw new Error("Claude history transcript_path is unavailable");
351
- return claudeHistoryFromJsonl(await readFile(source.transcriptPath, "utf8"), source);
355
+ const snapshot = { ...source };
356
+ const read = async () => claudeHistoryFromJsonl(await readFile(snapshot.transcriptPath, "utf8"), snapshot);
357
+ if (!waitForHead || !snapshot.headUuid)
358
+ return read();
359
+ const revision = async () => {
360
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot.transcriptPath, { bigint: true });
361
+ return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
362
+ };
363
+ let seen = await revision();
364
+ try {
365
+ return await read();
366
+ }
367
+ catch (error) {
368
+ if (!(error instanceof UnpersistedClaudeHead))
369
+ throw error;
370
+ // A kept append can reach the tool before its disk write. Only retry that same
371
+ // head, and only reparse on file changes. Never fall back to an offline leaf.
372
+ for (const delay of [50, 100, 200, 300, 350]) {
373
+ await sleep(delay);
374
+ const current = await revision();
375
+ if (current === seen)
376
+ continue;
377
+ seen = current;
378
+ try {
379
+ return await read();
380
+ }
381
+ catch (retry) {
382
+ if (!(retry instanceof UnpersistedClaudeHead))
383
+ throw retry;
384
+ }
385
+ }
386
+ throw error;
387
+ }
352
388
  }
@@ -52,12 +52,15 @@ export type HistoryProjection = {
52
52
  pairedResults: Map<number, number>;
53
53
  };
54
54
  /** The filters one selection applies before paging: roles, seq bounds, and parsed epoch-ms time bounds. */
55
+ export type HistoryBound = {
56
+ seq: number;
57
+ } | {
58
+ at: number;
59
+ };
55
60
  export type HistoryFilter = {
56
- roles?: HistoryRole[] | null;
57
- after_seq?: number;
58
- before_seq?: number;
59
- sinceMs?: number;
60
- untilMs?: number;
61
+ roles?: HistoryRole[];
62
+ after?: HistoryBound;
63
+ before?: HistoryBound;
61
64
  };
62
65
  /** Native entries after the adapter allocates seqs and selects the active branch. */
63
66
  export type DecodedHistoryItem = {
@@ -136,6 +139,7 @@ export declare const HistoryPageItemSchema: Type.TObject<{
136
139
  count: Type.TInteger;
137
140
  tools: Type.TRecord<"^.*$", Type.TInteger>;
138
141
  }>>;
142
+ context: Type.TOptional<Type.TLiteral<true>>;
139
143
  seq: Type.TInteger;
140
144
  role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
141
145
  created_at: Type.TUnion<[Type.TString, Type.TNull]>;
@@ -148,11 +152,6 @@ export declare const MAX_FOLD_TOOL_NAME_CHARS = 120;
148
152
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
149
153
  export declare function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?: number): HistoryPageItem;
150
154
  export declare function allItems(projection: HistoryProjection): HistoryEvent[];
151
- /**
152
- * Whether one event is inside the selection: its seq bounds, and a half-open
153
- * [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
154
- * time or a time that cannot be read.
155
- */
156
- export declare function inSelection(event: HistoryEvent, params: HistoryFilter): boolean;
155
+ export declare function matchesFilter(event: HistoryEvent, { after, before, roles }: HistoryFilter): boolean;
157
156
  /** Ordered events inside the requested seq/time range and optional roles, before folding. */
158
157
  export declare function filteredItems(projection: HistoryProjection, params: HistoryFilter): HistoryEvent[];
@@ -146,6 +146,7 @@ export const HistoryFoldedRowSchema = Type.Object({
146
146
  export const HistoryPageItemSchema = Type.Object({
147
147
  session: Type.Optional(Type.String()),
148
148
  folded_before: Type.Optional(HistoryFoldedRowSchema),
149
+ context: Type.Optional(Type.Literal(true, { description: "A neighbor of a search hit, not a hit in this page." })),
149
150
  seq: Type.Integer({ minimum: 1 }),
150
151
  role: HistoryRoleSchema,
151
152
  created_at: Type.Union([Type.String(), Type.Null()]),
@@ -179,26 +180,14 @@ export function visibleItem(event, maxChars, matchOffset) {
179
180
  export function allItems(projection) {
180
181
  return projection.windows.flatMap((current) => current.items);
181
182
  }
182
- /**
183
- * Whether one event is inside the selection: its seq bounds, and a half-open
184
- * [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
185
- * time or a time that cannot be read.
186
- */
187
- export function inSelection(event, params) {
188
- if (params.after_seq !== undefined && event.seq <= params.after_seq)
189
- return false;
190
- if (params.before_seq !== undefined && event.seq >= params.before_seq)
191
- return false;
192
- if (params.sinceMs === undefined && params.untilMs === undefined)
193
- return true;
194
- if (event.createdAt === undefined)
195
- return false;
196
- const at = Date.parse(event.createdAt);
197
- return !Number.isNaN(at) && (params.sinceMs === undefined || at >= params.sinceMs) && (params.untilMs === undefined || at < params.untilMs);
183
+ function compareBound(event, bound) {
184
+ return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
185
+ }
186
+ export function matchesFilter(event, { after, before, roles }) {
187
+ return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0)
188
+ && (!roles || roles.includes(event.role));
198
189
  }
199
190
  /** Ordered events inside the requested seq/time range and optional roles, before folding. */
200
191
  export function filteredItems(projection, params) {
201
- return allItems(projection)
202
- .filter((item) => inSelection(item, params) && (!params.roles || params.roles.includes(item.role)))
203
- .sort((a, b) => a.seq - b.seq);
192
+ return allItems(projection).filter(event => matchesFilter(event, params)).sort((a, b) => a.seq - b.seq);
204
193
  }
@@ -1,4 +1,4 @@
1
- export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
1
+ export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean, stopOnHit?: boolean) => Promise<boolean>;
2
2
  /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
3
3
  export declare function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter;
4
4
  /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
@@ -24,7 +24,7 @@ export function createHistoryPrefilter(queries) {
24
24
  }));
25
25
  // No safe tokens (or generated text alone) cannot prove a miss.
26
26
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
27
- return async (chunks, codex = false) => {
27
+ return async (chunks, codex = false, stopOnHit = false) => {
28
28
  const decoder = new StringDecoder("utf8");
29
29
  const seen = alternatives.map((tokens) => tokens.map(() => false));
30
30
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
@@ -59,9 +59,12 @@ export function createHistoryPrefilter(queries) {
59
59
  rawTail = raw.slice(-overlap);
60
60
  normalizedTail = normalized.slice(-overlap);
61
61
  };
62
- for await (const chunk of chunks)
62
+ for await (const chunk of chunks) {
63
63
  if (!possible)
64
64
  scan(decoder.write(chunk));
65
+ if (possible && stopOnHit)
66
+ return true;
67
+ }
65
68
  if (!possible)
66
69
  scan(decoder.end(), true);
67
70
  return possible;
@@ -69,13 +72,15 @@ export function createHistoryPrefilter(queries) {
69
72
  }
70
73
  /** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
71
74
  export async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
72
- if (codex) {
73
- const info = await stat(path);
74
- if (!info.isFile() || info.size > maxBytes)
75
- throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
76
- }
77
- // Native Codex compression is zstd; no decoded file or full Buffer is materialized.
78
- const compressed = codex && path.endsWith(".jsonl.zst");
75
+ // Plain Pi/Claude files will be read and validated by the strict decoder on a possible
76
+ // hit. Don't drain a potentially huge file just to read it from the beginning again.
77
+ if (!codex)
78
+ return prefilter(createReadStream(path), false, true);
79
+ const info = await stat(path);
80
+ if (!info.isFile() || info.size > maxBytes)
81
+ throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
82
+ // Native Codex compression is zstd; scan through EOF to enforce the decoded size limit.
83
+ const compressed = path.endsWith(".jsonl.zst");
79
84
  if (compressed && typeof zlib.createZstdDecompress !== "function")
80
85
  throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
81
86
  const input = createReadStream(path);
@@ -4,21 +4,11 @@ import { type Outcome } from "../result.js";
4
4
  import { type HistoryEvent, type HistoryFilter, type HistoryProjection } from "./history.js";
5
5
  export declare function isMultiPage(page: HistoryPage): boolean;
6
6
  export declare function markMultiPage(page: HistoryPage): HistoryPage;
7
- /** Which end of one selection `limit` is taken from; page items always come back ascending. */
8
- export type HistoryOrder = "newest" | "oldest";
9
- /**
10
- * What one list call selects. `before_seq`/`after_seq` choose a seq range and `since`/`until` a time
11
- * range; `from` chooses the end `limit` counts from; a `query` keeps only matching events, across
12
- * every role, with no folded rows.
13
- */
14
7
  export type HistorySelection = HistoryFilter & {
15
8
  session?: string;
16
- from?: HistoryOrder;
17
9
  limit?: number;
18
- query?: string | string[];
19
- since?: string;
20
- until?: string;
21
- max_chars_per_item?: number;
10
+ query?: string[];
11
+ context?: number;
22
12
  };
23
13
  export declare const HistoryPageSchema: Type.TObject<{
24
14
  notice: Type.TOptional<Type.TString>;
@@ -38,6 +28,7 @@ export declare const HistoryPageSchema: Type.TObject<{
38
28
  count: Type.TInteger;
39
29
  tools: Type.TRecord<"^.*$", Type.TInteger>;
40
30
  }>>;
31
+ context: Type.TOptional<Type.TLiteral<true>>;
41
32
  seq: Type.TInteger;
42
33
  role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
43
34
  created_at: Type.TUnion<[Type.TString, Type.TNull]>;
@@ -63,8 +54,6 @@ export type HistoryPageResult = Outcome<HistoryPage> | {
63
54
  };
64
55
  };
65
56
  export declare function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult;
66
- /** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
67
- export declare function corpusSelection(params: HistorySelection): Outcome<HistorySelection>;
68
57
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
69
58
  export declare function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined;
70
59
  /** Keep only the requested end of the globally ordered selection while sessions are released. */
@@ -1,37 +1,14 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
2
  import { Type } from "typebox";
3
- import { failure, success } 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 } from "./history.js";
3
+ import { success } 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 } from "./history.js";
6
6
  const multiPages = new WeakSet();
7
7
  export function isMultiPage(page) { return multiPages.has(page); }
8
8
  export function markMultiPage(page) {
9
9
  multiPages.add(page);
10
10
  return page;
11
11
  }
12
- /** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
13
- const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
14
- /** Epoch ms for one optional time param, or a refusal naming it. */
15
- function timeBound(name, value) {
16
- if (value === undefined)
17
- return success(undefined);
18
- const match = ISO_8601.exec(value);
19
- const at = match === null ? undefined : Date.parse(match[1] === undefined ? `${value}Z` : value);
20
- return at === undefined || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
21
- }
22
- /** Parse `since`/`until`; a malformed or inverted pair refuses here. */
23
- function resolveTimeBounds(params) {
24
- const since = timeBound("since", params.since);
25
- if (!since.ok)
26
- return since;
27
- const until = timeBound("until", params.until);
28
- if (!until.ok)
29
- return until;
30
- if (since.data !== undefined && until.data !== undefined && since.data >= until.data) {
31
- return failure("invalid_time", "`since` must be earlier than `until`.");
32
- }
33
- return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
34
- }
35
12
  export const HistoryPageSchema = Type.Object({
36
13
  notice: Type.Optional(Type.String()),
37
14
  items: Type.Array(HistoryPageItemSchema),
@@ -72,26 +49,34 @@ function foldedRun(events, session) {
72
49
  const tools = Object.fromEntries(entries);
73
50
  return { ...(session === undefined ? {} : { session }), first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
74
51
  }
75
- /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
52
+ // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
53
+ const visible = (event) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "";
54
+ function* queryHits(projection, params, session) {
55
+ const { query, context } = params;
56
+ const events = filteredItems(projection, context ? {} : params).filter(visible);
57
+ for (const [index, event] of events.entries()) {
58
+ if (context && !matchesFilter(event, params))
59
+ continue;
60
+ const matchOffset = earliestMatchOffsetChars(eventDocument(event), query);
61
+ if (matchOffset >= 0)
62
+ yield { event, session, matchOffset, neighbors: context ? { events, index } : undefined };
63
+ }
64
+ }
76
65
  function prepareSelection(projection, params) {
77
- const folds = !params.roles && params.query === undefined;
66
+ const { query, roles, session } = params;
67
+ if (query)
68
+ return { candidates: [...queryHits(projection, params, session)] };
78
69
  const candidates = [];
79
70
  let run = [];
80
- for (const event of filteredItems(projection, params)) {
81
- if (folds && (event.role === "tool" || event.role === "context")) {
71
+ for (const event of filteredItems(projection, params).filter(visible)) {
72
+ if (!roles && (event.role === "tool" || event.role === "context"))
82
73
  run.push(event);
83
- continue;
74
+ else {
75
+ candidates.push({ event, session, before: foldedRun(run, session) });
76
+ run = [];
84
77
  }
85
- // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
86
- if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "")
87
- continue;
88
- const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query);
89
- if (matchOffset !== undefined && matchOffset < 0)
90
- continue;
91
- candidates.push({ event, ...(params.session === undefined ? {} : { session: params.session }), matchOffset, before: foldedRun(run, params.session) });
92
- run = [];
93
78
  }
94
- return { candidates, session: params.session, tail: foldedRun(run, params.session) };
79
+ return { candidates, tail: foldedRun(run, session) };
95
80
  }
96
81
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
97
82
  function pageData(prepared, start, end, maxChars, preview) {
@@ -105,52 +90,60 @@ function pageData(prepared, start, end, maxChars, preview) {
105
90
  const page = {
106
91
  items,
107
92
  ...(end === candidates.length && tail ? { folded_after: tail } : {}),
108
- has_older: (start > 0 && start < end) || (!!prepared.discarded && prepared.from !== "oldest"),
109
- has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && prepared.from === "oldest"),
93
+ has_older: (start > 0 && start < end) || (!!prepared.discarded && !prepared.forward),
94
+ has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && !!prepared.forward),
110
95
  };
111
96
  return prepared.multi ? markMultiPage(page) : page;
112
97
  }
113
- /**
114
- * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
115
- * Grow the page in selection order; shorten the first preview only when no full row fits.
116
- */
117
- function resolveSelection(params) {
118
- const bounds = resolveTimeBounds(params);
119
- if (!bounds.ok)
120
- return bounds;
121
- try {
122
- const queries = searchQueries(params.query);
123
- return success({ ...params, ...bounds.data, query: queries.length ? queries : undefined });
124
- }
125
- catch (error) {
126
- if (error instanceof InvalidQueryError)
127
- return failure("invalid_query", error.message);
128
- throw error;
129
- }
130
- }
131
98
  export function selectPage(projection, params, fits, maxChars) {
132
- const scoped = resolveSelection(params);
133
- if (!scoped.ok)
134
- return scoped;
135
- return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
136
- }
137
- /** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
138
- export function corpusSelection(params) {
139
- if (params.before_seq !== undefined || params.after_seq !== undefined)
140
- return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
141
- return resolveSelection(params);
99
+ return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
142
100
  }
143
101
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
144
102
  export function sessionRepresentative(projection, scoped) {
145
- const events = filteredItems(projection, scoped).filter((event) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "");
103
+ const events = filteredItems(projection, scoped).filter(visible);
146
104
  if (scoped.roles)
147
105
  return events.at(-1);
148
106
  return events.find((event) => event.role === "user")
149
107
  ?? events.filter((event) => event.role === "assistant").at(-1)
150
108
  ?? events.at(-1);
151
109
  }
152
- const eventTime = (event) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
153
- const compareCorpus = (a, b) => eventTime(a.event) - eventTime(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
110
+ function eventTime(timestamp) {
111
+ const at = Date.parse(timestamp ?? "");
112
+ return Number.isNaN(at) ? -Infinity : at;
113
+ }
114
+ const compareCorpus = (a, b) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
115
+ /** Fill the remaining budget nearest first. Shared session/seq keys merge overlapping windows. */
116
+ function addContext(page, hits, radius, fits, maxChars) {
117
+ const key = (session, seq) => `${session ?? ""}\0${seq}`;
118
+ const seen = new Set(page.items.map(item => key(item.session, item.seq)));
119
+ const compare = (a, b) => (isMultiPage(page) ? eventTime(a.created_at) - eventTime(b.created_at) || a.session.localeCompare(b.session) : 0) || a.seq - b.seq;
120
+ for (let distance = 1; distance <= radius; distance++) {
121
+ let found = false;
122
+ for (const { neighbors, session } of hits) {
123
+ if (!neighbors)
124
+ continue;
125
+ for (const index of [neighbors.index - distance, neighbors.index + distance]) {
126
+ const event = neighbors.events[index];
127
+ if (!event)
128
+ continue;
129
+ found = true;
130
+ const id = key(session, event.seq);
131
+ if (seen.has(id))
132
+ continue;
133
+ const item = { ...visibleItem(event, maxChars), ...(session === undefined ? {} : { session }), context: true };
134
+ const previous = page.items;
135
+ page.items = [...previous, item].sort(compare);
136
+ if (!fits(page)) {
137
+ page.items = previous;
138
+ return;
139
+ }
140
+ seen.add(id);
141
+ }
142
+ }
143
+ if (!found)
144
+ return;
145
+ }
146
+ }
154
147
  /** Keep only the requested end of the globally ordered selection while sessions are released. */
155
148
  export class CorpusCollector {
156
149
  scoped;
@@ -173,7 +166,7 @@ export class CorpusCollector {
173
166
  }
174
167
  if (this.candidates.length === this.limit) {
175
168
  this.discarded = true;
176
- if (this.scoped.from === "oldest") {
169
+ if (this.scoped.after) {
177
170
  if (low === this.limit)
178
171
  return;
179
172
  this.candidates.pop();
@@ -198,25 +191,18 @@ export class CorpusCollector {
198
191
  add(session, projection) {
199
192
  if (this.scoped.query === undefined)
200
193
  return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
201
- for (const event of filteredItems(projection, this.scoped)) {
202
- const document = eventDocument(event);
203
- if ((event.role === "user" || event.role === "assistant") && document === "")
204
- continue;
205
- const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
206
- if (matchOffset >= 0)
207
- this.admit({ session, event, matchOffset });
208
- }
194
+ for (const hit of queryHits(projection, this.scoped, session))
195
+ this.admit(hit);
209
196
  return true;
210
197
  }
211
198
  page(fits, maxChars, unvisited = false) {
212
- return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
199
+ return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
213
200
  }
214
201
  }
215
202
  function selectPrepared(prepared, scoped, fits, maxChars) {
216
203
  const { candidates } = prepared;
217
204
  // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
218
- const from = scoped.from ?? (scoped.after_seq !== undefined ? "oldest" : "newest");
219
- const newest = from === "newest";
205
+ const newest = scoped.after === undefined;
220
206
  let start = newest ? candidates.length : 0;
221
207
  let end = start;
222
208
  const limit = Math.max(1, scoped.limit ?? 20);
@@ -239,5 +225,7 @@ function selectPrepared(prepared, scoped, fits, maxChars) {
239
225
  const page = pageData(prepared, start, end, maxChars);
240
226
  if (!fits(page))
241
227
  return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
228
+ if (scoped.context)
229
+ addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
242
230
  return success(page);
243
231
  }
@@ -19,7 +19,7 @@ export { renderBootBlock } from "./boot/render.js";
19
19
  export type { BootRenderData, BootWindowTree } from "./boot/render.js";
20
20
  export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
21
21
  export type { BootToolNames } from "./boot/text.js";
22
- export { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "./tools/notes.js";
22
+ export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
23
23
  export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
24
24
  export { historyList, historyRead } from "./tools/history.js";
25
25
  export { projectHistory } from "./history/history.js";