notesoup 0.59.2 → 0.60.1

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 (78) 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/dream/git.js +12 -13
  8. package/dist/src/history/history.d.ts +10 -11
  9. package/dist/src/history/history.js +8 -19
  10. package/dist/src/history/query.d.ts +3 -14
  11. package/dist/src/history/query.js +73 -85
  12. package/dist/src/index.d.ts +1 -1
  13. package/dist/src/index.js +1 -1
  14. package/dist/src/notes/address.js +3 -3
  15. package/dist/src/notes/project-namespace.js +39 -73
  16. package/dist/src/notes/store.d.ts +2 -4
  17. package/dist/src/notes/store.js +1 -2
  18. package/dist/src/sqlite-lock.d.ts +2 -0
  19. package/dist/src/sqlite-lock.js +17 -0
  20. package/dist/src/tools/dream.d.ts +2 -4
  21. package/dist/src/tools/dream.js +15 -16
  22. package/dist/src/tools/history.d.ts +4 -6
  23. package/dist/src/tools/history.js +69 -29
  24. package/dist/src/tools/notes.d.ts +18 -78
  25. package/dist/src/tools/notes.js +39 -50
  26. package/dist/src/tools/schema.d.ts +0 -1
  27. package/dist/src/tools/schema.js +0 -1
  28. package/dist/test/claude-history.test.js +5 -6
  29. package/dist/test/claude-mod.test.js +6 -7
  30. package/dist/test/codex-history.test.js +1 -1
  31. package/dist/test/codex-plugin.test.js +1 -2
  32. package/dist/test/dependencies.test.js +2 -2
  33. package/dist/test/dream-tools.test.js +42 -14
  34. package/dist/test/dsh.test.js +2 -2
  35. package/dist/test/history-corpus.test.js +21 -36
  36. package/dist/test/history-summary-cache.test.js +3 -3
  37. package/dist/test/history.integration.test.js +53 -106
  38. package/dist/test/host-neutral.test.js +1 -1
  39. package/dist/test/note-policy.test.js +5 -5
  40. package/dist/test/notes-cwd.test.js +5 -5
  41. package/dist/test/notes-query-namespaces.test.js +2 -6
  42. package/dist/test/notes.integration.test.js +33 -42
  43. package/dist/test/notes.test.js +12 -14
  44. package/dist/test/project-namespace.test.js +36 -91
  45. package/docs/architecture.md +3 -3
  46. package/docs/claude-code-mod.md +2 -2
  47. package/docs/codex.md +1 -1
  48. package/docs/dsh.md +2 -2
  49. package/docs/history-sessions.md +8 -9
  50. package/docs/notes-library.md +9 -3
  51. package/docs/skills.md +2 -6
  52. package/docs/tool-results.md +12 -6
  53. package/package.json +1 -1
  54. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  55. package/plugins/claude/dist/claude/helper.js +212 -211
  56. package/plugins/claude/skills/memory/SKILL.md +6 -6
  57. package/plugins/claude/src/helper.ts +1 -2
  58. package/plugins/codex/README.md +1 -1
  59. package/plugins/codex/dist/codex/notesoup.js +211 -210
  60. package/plugins/codex/src/mcp.ts +1 -2
  61. package/plugins/dsh/tools.ts +1 -2
  62. package/plugins/pi/notes/tools.ts +2 -3
  63. package/skills/memory/SKILL.md +6 -6
  64. package/src/dream/git.ts +11 -11
  65. package/src/history/history.ts +11 -16
  66. package/src/history/query.ts +67 -99
  67. package/src/index.ts +1 -1
  68. package/src/notes/address.ts +2 -2
  69. package/src/notes/project-namespace.ts +37 -59
  70. package/src/notes/store.ts +3 -6
  71. package/src/sqlite-lock.ts +14 -0
  72. package/src/tools/dream.ts +15 -14
  73. package/src/tools/history.ts +60 -29
  74. package/src/tools/notes.ts +39 -54
  75. package/src/tools/schema.ts +0 -1
  76. package/dist/src/dream/lock.d.ts +0 -14
  77. package/dist/src/dream/lock.js +0 -29
  78. package/src/dream/lock.ts +0 -28
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join, resolve, sep } from "node:path";
4
+ import { trySqliteLock } from "../sqlite-lock.js";
4
5
  import { slugify } from "./paths.js";
5
6
  function errno(error) {
6
7
  return typeof error === "object" && error !== null ? error.code : undefined;
@@ -135,85 +136,50 @@ function updateMarker(namespace, marker) {
135
136
  }
136
137
  return { ...namespace, ...marker };
137
138
  }
138
- const claimSleep = new Int32Array(new SharedArrayBuffer(4));
139
- function awaitClaim(path, attempt) {
140
- const deadline = performance.now() + 5_000;
141
- for (;;) {
142
- const result = attempt();
143
- if (result !== undefined)
144
- return result;
145
- const remaining = deadline - performance.now();
146
- if (remaining <= 0)
147
- throw new Error(`Timed out waiting for project claim at ${path}`);
148
- Atomics.wait(claimSleep, 0, 0, Math.min(10, remaining));
149
- }
139
+ function checkoutMarker(cwd) {
140
+ const path = canonicalRoot(cwd);
141
+ return { id: originRemote(path) ?? path, path };
150
142
  }
151
143
  /** Resolve and claim the readable notebook for one repository identity. */
152
144
  export function resolveProjectNamespace(cwd, home) {
153
- mkdirSync(projectRoot(home), { recursive: true });
154
- // Serialize the scan as well as publication: an unmarked directory seen under
155
- // this lock is legacy, not another resolver between mkdir and marker write.
156
- const lock = join(home, ".project-claim");
157
- awaitClaim(lock, () => {
158
- try {
159
- mkdirSync(lock);
160
- return true;
161
- }
162
- catch (error) {
163
- if (errno(error) === "EEXIST")
164
- return undefined;
165
- throw error;
166
- }
167
- });
145
+ const expected = checkoutMarker(cwd);
146
+ const current = projectNamespaces(home).find(candidate => candidate.id === expected.id);
147
+ if (current?.path === expected.path)
148
+ return current;
149
+ const root = projectRoot(home);
150
+ mkdirSync(root, { recursive: true });
151
+ const lockPath = join(home, ".project-claim.sqlite");
152
+ const release = trySqliteLock(lockPath, 5000);
153
+ if (!release)
154
+ throw new Error(`Timed out waiting for project claim at ${lockPath}`);
168
155
  try {
169
- return claimProjectNamespace(cwd, home);
170
- }
171
- finally {
172
- rmdirSync(lock);
173
- }
174
- }
175
- function claimProjectNamespace(cwd, home) {
176
- const root = canonicalRoot(cwd);
177
- const remote = originRemote(root);
178
- const id = remote ?? root;
179
- const markerRoot = projectRoot(home);
180
- mkdirSync(markerRoot, { recursive: true });
181
- const namespaces = projectNamespaces(home);
182
- let found = namespaces.find(candidate => candidate.id === id);
183
- if (!found && remote) {
184
- found = namespaces.find(candidate => candidate.id === root);
156
+ // The checkout may have gained an origin and a peer may have already adopted it.
157
+ const marker = checkoutMarker(cwd);
158
+ const { id, path } = marker;
159
+ const namespaces = projectNamespaces(home);
160
+ const found = namespaces.find(candidate => candidate.id === id) ?? namespaces.find(candidate => candidate.id === path);
185
161
  if (found)
186
- found = updateMarker(found, { id: remote, path: root });
187
- }
188
- if (found) {
189
- if (found.path !== root)
190
- found = updateMarker(found, { id: found.id, path: root });
191
- return found;
192
- }
193
- const base = slugify(basename(root));
194
- // The claim lock makes this a stable snapshot of legacy, unmarked names.
195
- const taken = new Set(readdirSync(markerRoot));
196
- for (let suffix = 0;; suffix++) {
197
- const name = suffix === 0 ? base : `${base}-${suffix}`;
198
- if (taken.has(name))
199
- continue;
200
- const dir = join(markerRoot, name);
201
- try {
202
- mkdirSync(dir);
203
- }
204
- catch (error) {
205
- if (errno(error) !== "EEXIST")
162
+ return found.id === id && found.path === path ? found : updateMarker(found, marker);
163
+ const base = slugify(basename(path));
164
+ for (let suffix = 0;; suffix++) {
165
+ const name = suffix === 0 ? base : `${base}-${suffix}`;
166
+ const dir = join(root, name);
167
+ if (lstatSync(dir, { throwIfNoEntry: false }))
168
+ continue; // Includes unmarked legacy names.
169
+ const staged = mkdtempSync(join(home, ".project-pending-"));
170
+ try {
171
+ writeFileSync(join(staged, ".project"), JSON.stringify(marker));
172
+ renameSync(staged, dir);
173
+ }
174
+ catch (error) {
175
+ rmSync(staged, { recursive: true, force: true });
206
176
  throw error;
207
- // A writer outside this protocol may have won after the snapshot.
208
- // Never mistake its incomplete publication for a different identity.
209
- let winner = awaitClaim(join(dir, ".project"), () => readMarker(dir));
210
- if (winner.id !== id && !(remote && winner.id === root))
211
- continue;
212
- if (winner.id !== id || winner.path !== root)
213
- winner = updateMarker(winner, { id, path: root });
214
- return winner;
177
+ }
178
+ return { name, dir, ...marker };
215
179
  }
216
- return updateMarker({ name, dir, id, path: root }, { id, path: root });
180
+ }
181
+ finally {
182
+ release();
217
183
  }
218
184
  }
219
185
  /** Existing root discovery, including linked worktrees, without invoking Git. */
@@ -38,11 +38,9 @@ export type EditOptions = NotePolicyFields & {
38
38
  replaceAll?: boolean;
39
39
  renameTo?: string;
40
40
  };
41
- /** Omitted/null/empty glob or bare @default selects current notebooks; explicit globs match full addresses.
42
- * A pattern without `@` or `/` matches filenames at any depth; relative paths with `/` match the current session.
43
- */
41
+ /** Omit glob for current notebooks. A pattern without `@` or `/` matches filenames at any depth. */
44
42
  export type NotesQuery = {
45
- glob?: string | null;
43
+ glob?: string;
46
44
  crumpled?: boolean;
47
45
  };
48
46
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
@@ -471,8 +471,7 @@ export function createNotesStore(input) {
471
471
  }));
472
472
  }
473
473
  async function* scan(options, status) {
474
- const glob = assertGlobPattern(options.glob);
475
- const pattern = glob === "@default" ? undefined : glob;
474
+ const pattern = assertGlobPattern(options.glob);
476
475
  const normalized = normalizePattern(pattern, identity);
477
476
  const matcher = normalized === undefined ? undefined : globToRegExp(normalized);
478
477
  const namespaces = await namespacesForPattern(pattern, identity, status);
@@ -0,0 +1,2 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export declare function trySqliteLock(path: string, waitMs: 0 | 5000): (() => void) | undefined;
@@ -0,0 +1,17 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export function trySqliteLock(path, waitMs) {
3
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
4
+ if (!sqlite?.DatabaseSync)
5
+ throw new Error("Notesoup locks require built-in node:sqlite (Node 22.13+).");
6
+ const db = new sqlite.DatabaseSync(path);
7
+ try {
8
+ db.exec(`PRAGMA busy_timeout = ${waitMs}; BEGIN IMMEDIATE`);
9
+ }
10
+ catch (error) {
11
+ db.close();
12
+ if (error instanceof Error && "errcode" in error && error.errcode === 5)
13
+ return undefined; // SQLITE_BUSY
14
+ throw error;
15
+ }
16
+ return () => db.close(); // Closing rolls back the empty transaction.
17
+ }
@@ -1,17 +1,15 @@
1
- /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
1
  import { Type, type Static } from "typebox";
3
2
  import { type NotesIdentity } from "../notes/index.js";
4
- import { type DreamLock } from "../dream/lock.js";
5
3
  import { type Outcome } from "../result.js";
6
4
  /** The one open dream per session; the host owns where it lives. */
7
5
  type DreamOpening = {
8
6
  project: string;
9
- lock: DreamLock;
7
+ release: () => void;
10
8
  generation: number;
11
9
  };
12
10
  export type DreamState = {
13
11
  project?: string;
14
- lock?: DreamLock;
12
+ release?: () => void;
15
13
  pending?: DreamOpening;
16
14
  generation?: number;
17
15
  };
@@ -1,10 +1,11 @@
1
1
  /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
+ import { join } from "node:path";
2
3
  import { Type } from "typebox";
3
4
  import { localIso } from "../notes/frontmatter.js";
4
5
  import { createNotesStore, noteIdentity } from "../notes/index.js";
5
6
  import { projectNamespaces } from "../notes/project-namespace.js";
6
7
  import { gitCommit } from "../dream/git.js";
7
- import { acquireDreamLock, dreamLockPath, releaseDreamLock } from "../dream/lock.js";
8
+ import { trySqliteLock } from "../sqlite-lock.js";
8
9
  import { failure, success } from "../result.js";
9
10
  import { renderOutcome, resultSchema } from "./result.js";
10
11
  import { failureOf, listedFile, ListedFileSchema, NoteIdentitySchema, renderListData, snapshot, SnapshotSchema } from "./notes.js";
@@ -18,21 +19,19 @@ function nextGeneration(state) {
18
19
  }
19
20
  /** Drop an open dream without an end commit, e.g. when its session shuts down. */
20
21
  export function abandonDream(state) {
21
- const pending = state.pending;
22
- if (pending)
23
- releaseDreamLock(pending.lock);
24
- if (state.lock && state.lock !== pending?.lock)
25
- releaseDreamLock(state.lock);
22
+ state.pending?.release();
23
+ state.release?.();
26
24
  nextGeneration(state);
27
25
  delete state.project;
28
- delete state.lock;
26
+ delete state.release;
29
27
  delete state.pending;
30
28
  }
31
29
  /** Release an opening without disturbing a newer opening in the same state. */
32
30
  function releaseOpening(state, opening) {
33
- releaseDreamLock(opening.lock);
34
- if (currentOpening(state, opening))
35
- delete state.pending;
31
+ if (!currentOpening(state, opening))
32
+ return;
33
+ opening.release();
34
+ delete state.pending;
36
35
  }
37
36
  function cancelledOpening(state, opening) {
38
37
  releaseOpening(state, opening);
@@ -67,11 +66,11 @@ export const dreamBegin = {
67
66
  if (project !== identity.projectKey && !projectNamespaces(identity.home).some(namespace => namespace.name === project)) {
68
67
  return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
69
68
  }
70
- const lock = acquireDreamLock(dreamLockPath(identity.home));
71
- if (!lock)
72
- return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home)}. If none is running, delete that file by hand.`);
73
- // Publish ownership before the first await. Shutdown can therefore release this exact token.
74
- const opening = { project, lock, generation: nextGeneration(state) };
69
+ const release = trySqliteLock(join(identity.home, ".dream.lock.sqlite"), 0);
70
+ if (!release)
71
+ return failure("already_dreaming", "Another dream is open in this notes home.");
72
+ // Publish ownership before the first await so shutdown can release this transaction.
73
+ const opening = { project, release, generation: nextGeneration(state) };
75
74
  state.pending = opening;
76
75
  try {
77
76
  const store = createNotesStore({ ...identity, dreaming: project });
@@ -102,7 +101,7 @@ export const dreamBegin = {
102
101
  if (!currentOpening(state, opening))
103
102
  return cancelledOpening(state, opening);
104
103
  state.project = opening.project;
105
- state.lock = opening.lock;
104
+ state.release = opening.release;
106
105
  delete state.pending;
107
106
  return success({ project, baseline: baseline.commit, ...listed.data });
108
107
  }
@@ -27,13 +27,11 @@ type HistoryReadData = Static<typeof HistoryReadDataSchema>;
27
27
  export type HistoryTextWrapper = (text: string) => string;
28
28
  export declare const historyListParameters: Type.TObject<{
29
29
  session: Type.TOptional<Type.TString>;
30
- query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
31
30
  roles: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
32
- before_seq: Type.TOptional<Type.TInteger>;
33
- after_seq: Type.TOptional<Type.TInteger>;
34
- since: Type.TOptional<Type.TString>;
35
- until: Type.TOptional<Type.TString>;
36
- from: Type.TOptional<Type.TUnion<[Type.TLiteral<"newest">, Type.TLiteral<"oldest">]>>;
31
+ query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
32
+ after: Type.TOptional<Type.TUnion<[Type.TString, Type.TNumber]>>;
33
+ before: Type.TOptional<Type.TUnion<[Type.TString, Type.TNumber]>>;
34
+ context: Type.TOptional<Type.TInteger>;
37
35
  limit: Type.TOptional<Type.TInteger>;
38
36
  max_chars_per_item: Type.TOptional<Type.TInteger>;
39
37
  }>;
@@ -4,7 +4,8 @@ import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from
4
4
  import { failure, success } from "../result.js";
5
5
  import { fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
6
6
  import { historyRoles, searchQuery } from "./schema.js";
7
- import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage } from "../history/query.js";
7
+ import { InvalidQueryError, searchQueries } from "../text-match.js";
8
+ import { HistoryPageSchema, CorpusCollector, isMultiPage, markMultiPage, selectPage } from "../history/query.js";
8
9
  import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity } from "../history/corpus.js";
9
10
  import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema } from "../history/history.js";
10
11
  /** One read: identity, tool summary and a flat document slice. */
@@ -35,7 +36,7 @@ function toolHeader(item) {
35
36
  }
36
37
  function renderPageItem(item) {
37
38
  const tool = toolHeader(item);
38
- const lines = tool === undefined ? [header(item)] : [header(item), tool];
39
+ const lines = [header(item) + (item.context ? " | search context" : ""), ...(tool ? [tool] : [])];
39
40
  if (item.truncated)
40
41
  lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
41
42
  lines.push(item.content);
@@ -44,7 +45,7 @@ function renderPageItem(item) {
44
45
  function renderFoldedRow(row) {
45
46
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
46
47
  const identity = row.session === undefined ? {} : { session: row.session };
47
- const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
48
+ const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] })}`;
48
49
  return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
49
50
  }
50
51
  function renderPage(page) {
@@ -54,19 +55,20 @@ function renderPage(page) {
54
55
  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");
55
56
  if (isMultiPage(page)) {
56
57
  const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
57
- return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
58
+ return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with time bounds (after/before), query, roles or the session pattern` : "");
58
59
  }
59
- const first = page.items[0];
60
- const last = page.items.at(-1);
60
+ const hits = page.items.filter(item => !item.context);
61
+ const first = hits[0];
62
+ const last = hits.at(-1);
61
63
  const cursors = [
62
- page.has_older ? `→ older: ${JSON.stringify({ ...(first.session === undefined ? {} : { session: first.session }), before_seq: first.seq })}` : "",
63
- page.has_newer ? `→ newer: ${JSON.stringify({ ...(last.session === undefined ? {} : { session: last.session }), after_seq: last.seq })}` : "",
64
+ page.has_older ? `→ older: ${JSON.stringify({ session: first.session, before: first.seq })}` : "",
65
+ page.has_newer ? `→ newer: ${JSON.stringify({ session: last.session, after: last.seq })}` : "",
64
66
  ].filter((line) => line !== "");
65
67
  return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
66
68
  }
67
69
  function renderRead(data) {
68
70
  const tool = toolHeader(data);
69
- 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 })})`;
71
+ const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), after: Math.max(0, data.seq - 10), before: data.seq + 10 })})`;
70
72
  return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
71
73
  }
72
74
  const plainText = (text) => text;
@@ -75,22 +77,57 @@ function pageOutcome(result) {
75
77
  if (!("pageTooLarge" in result))
76
78
  return result;
77
79
  const { count, multi } = result.pageTooLarge;
78
- 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";
80
+ 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";
79
81
  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}.`);
80
82
  }
81
83
  /* ------------------------------------------------------------------ history_list */
84
+ const boundParameter = (description) => 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.` }));
82
85
  export const historyListParameters = Type.Object({
83
86
  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." })),
84
- query: Type.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
85
87
  roles: historyRoles(),
86
- before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "Only entries before this seq." })),
87
- after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "Only entries after this seq; 0 starts from the first page." })),
88
- since: Type.Optional(Type.String({ minLength: 1, description: "Only entries at or after this time (ISO 8601; UTC without an offset)." })),
89
- until: Type.Optional(Type.String({ minLength: 1, description: "Only entries before this time (ISO 8601; UTC without an offset)." })),
90
- 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." })),
91
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "How many entries per page; folded runs don't count." })),
88
+ query: Type.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
89
+ after: boundParameter("Start strictly after this bound, paging forward; 0 starts at the oldest event."),
90
+ before: boundParameter("Stop strictly before this bound; without `after`, take the newest eligible events."),
91
+ 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." })),
92
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "How many events or hits per page; folds and search context don't count." })),
92
93
  max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." })),
93
94
  }, { additionalProperties: false });
95
+ const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
96
+ function parseBound(name, value) {
97
+ if (value === undefined)
98
+ return success(undefined);
99
+ if (typeof value === "number" || /^\d+$/.test(value)) {
100
+ const seq = Number(value);
101
+ if (Number.isSafeInteger(seq) && seq >= 0)
102
+ return success({ seq });
103
+ }
104
+ else if (typeof value === "string") {
105
+ const match = ISO_8601.exec(value);
106
+ const at = match ? Date.parse(match[1] ? value : `${value}Z`) : NaN;
107
+ if (!Number.isNaN(at) && new Date(value.slice(0, 10)).toISOString().startsWith(value.slice(0, 10)))
108
+ return success({ at });
109
+ }
110
+ return failure("invalid_bounds", `\`${name}\` must be a non-negative integer seq or an ISO 8601 time; got ${JSON.stringify(value)}.`);
111
+ }
112
+ function parseSelection(params) {
113
+ const after = parseBound("after", params.after);
114
+ if (!after.ok)
115
+ return after;
116
+ const before = parseBound("before", params.before);
117
+ if (!before.ok)
118
+ return before;
119
+ try {
120
+ const query = searchQueries(params.query);
121
+ if (!query.length && params.context !== undefined)
122
+ return failure("invalid_params", "`context` requires a non-empty `query`.");
123
+ return success({ after: after.data, before: before.data, query: query.length ? query : undefined, roles: params.roles, context: params.context, limit: params.limit });
124
+ }
125
+ catch (error) {
126
+ if (error instanceof InvalidQueryError)
127
+ return failure("invalid_query", error.message);
128
+ throw error;
129
+ }
130
+ }
94
131
  export const historyList = {
95
132
  name: "history_list",
96
133
  label: "History list items",
@@ -98,32 +135,35 @@ export const historyList = {
98
135
  parameters: historyListParameters,
99
136
  outputSchema: resultSchema(HistoryPageSchema),
100
137
  async execute(params, context, wrapText = plainText) {
138
+ const selection = parseSelection(params);
139
+ if (!selection.ok)
140
+ return selection;
141
+ const scoped = selection.data;
101
142
  // Charge wrapped rendering, identities, notices and recipes, not only event previews.
102
143
  const fits = (page) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
103
144
  const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
104
145
  if (params.session === undefined)
105
- return pageOutcome(selectPage(await currentHistory(context), params, fits, maxChars));
146
+ return pageOutcome(selectPage(await currentHistory(context), scoped, fits, maxChars));
106
147
  const selector = parseSessionSelector(params.session);
107
148
  if (!selector.ok)
108
149
  return selector;
109
150
  const corpus = "corpus" in context ? context.corpus : undefined;
110
151
  if (selector.data.wildcard) {
111
- const scoped = corpusSelection(params);
112
- if (!scoped.ok)
113
- return scoped;
152
+ const { after, before, query, roles } = scoped;
153
+ if ((after && "seq" in after) || (before && "seq" in before))
154
+ return failure("invalid_bounds", "Wildcard history requires times, not seqs, for `after` and `before`.");
114
155
  if (corpus === undefined)
115
156
  return failure("unknown_session", "This host supplied no cross-session history corpus.");
116
157
  const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
117
- const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
118
- if (!queries)
119
- sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
120
- const representative = !queries && scoped.data.roles === undefined && scoped.data.since === undefined && scoped.data.until === undefined;
121
- const collector = new CorpusCollector(scoped.data);
158
+ if (!query)
159
+ 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);
122
162
  let qualifying = 0;
123
163
  const notices = [];
124
164
  let unvisited = false;
125
165
  for (const [index, session] of sessions.entries()) {
126
- const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
166
+ const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, query);
127
167
  if (!result.ok || !result.data)
128
168
  continue;
129
169
  const added = "projection" in result.data ? collector.add(sessionIdentity(session), result.data.projection) : collector.addRepresentative(sessionIdentity(session), result.data.event);
@@ -132,7 +172,7 @@ export const historyList = {
132
172
  qualifying++;
133
173
  if (result.data.notice)
134
174
  notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
135
- if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
175
+ if (!query && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
136
176
  unvisited = index + 1 < sessions.length;
137
177
  break;
138
178
  }
@@ -148,7 +188,7 @@ export const historyList = {
148
188
  if (!loaded.ok)
149
189
  return loaded;
150
190
  const notice = loaded.data.notice === undefined ? {} : { notice: loaded.data.notice };
151
- const result = pageOutcome(selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
191
+ const result = pageOutcome(selectPage(loaded.data.projection, { ...scoped, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
152
192
  return result.ok ? success({ ...result.data, ...notice }) : result;
153
193
  },
154
194
  render: (result) => renderOutcome(result, renderPage),
@@ -117,31 +117,11 @@ export declare const NotesListDataSchema: Type.TObject<{
117
117
  more: Type.TInteger;
118
118
  namespaces_unavailable: Type.TArray<Type.TString>;
119
119
  files: Type.TArray<Type.TObject<{
120
- updated_at: Type.TString;
121
- crumpled_at: Type.TOptional<Type.TString>;
122
- warnings: Type.TArray<Type.TString>;
123
- pinned: Type.TBoolean;
124
- budget: Type.TInteger;
125
- readonly: Type.TBoolean;
126
- project_root: Type.TOptional<Type.TString>;
127
- project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
128
- name: Type.TString;
129
- path: Type.TString;
130
- }>>>;
131
- address: Type.TString;
132
- project_key: Type.TOptional<Type.TString>;
133
- }>>;
134
- }>;
135
- export type NotesListData = Static<typeof NotesListDataSchema>;
136
- export declare const NotesSearchDataSchema: Type.TObject<{
137
- more: Type.TInteger;
138
- namespaces_unavailable: Type.TArray<Type.TString>;
139
- files: Type.TArray<Type.TObject<{
140
- matches: Type.TArray<Type.TObject<{
120
+ matches: Type.TOptional<Type.TArray<Type.TObject<{
141
121
  line: Type.TInteger;
142
122
  text: Type.TString;
143
123
  offset_chars: Type.TInteger;
144
- }>>;
124
+ }>>>;
145
125
  more_matches: Type.TOptional<Type.TInteger>;
146
126
  updated_at: Type.TString;
147
127
  crumpled_at: Type.TOptional<Type.TString>;
@@ -158,7 +138,8 @@ export declare const NotesSearchDataSchema: Type.TObject<{
158
138
  project_key: Type.TOptional<Type.TString>;
159
139
  }>>;
160
140
  }>;
161
- export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
141
+ export type NotesListData = Static<typeof NotesListDataSchema>;
142
+ type ListedFile = Static<typeof ListedFileSchema>;
162
143
  type Snapshot<T> = Omit<NotesListData, "files"> & {
163
144
  files: T[];
164
145
  };
@@ -169,7 +150,7 @@ export declare function snapshot<T extends {
169
150
  export declare function listedFile(row: Pick<NoteRow, "address" | "meta"> & {
170
151
  body?: string;
171
152
  warnings?: string[];
172
- }, identity: NotesIdentity): NotesListData["files"][number];
153
+ }, identity: NotesIdentity): ListedFile;
173
154
  export declare const notesWriteParameters: Type.TObject<{
174
155
  cwd: Type.TOptional<Type.TString>;
175
156
  pinned: Type.TOptional<Type.TBoolean>;
@@ -316,80 +297,39 @@ export declare const notesRead: {
316
297
  readonly render: (result: Outcome<NotesReadData>) => string;
317
298
  };
318
299
  export declare const notesListParameters: Type.TObject<{
319
- glob: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
320
- limit: Type.TOptional<Type.TInteger>;
300
+ glob: Type.TOptional<Type.TString>;
301
+ query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
302
+ max_matches_per_file: Type.TOptional<Type.TInteger>;
321
303
  crumpled: Type.TOptional<Type.TBoolean>;
304
+ limit: Type.TOptional<Type.TInteger>;
322
305
  cwd: Type.TOptional<Type.TString>;
323
306
  }>;
324
307
  export declare function renderListData(data: Snapshot<NotesListData["files"][number] & {
325
308
  last_accessed?: string;
326
309
  }>): string;
310
+ /** A shortened match line still ends with a marker, so its own text says it was cut. */
311
+ export declare const MATCH_SHORTENED_MARKER = " [truncated]";
327
312
  export declare const notesList: {
328
313
  readonly name: "notes_list";
329
314
  readonly label: "Notes list";
330
- readonly description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile — narrow `glob`.";
331
- readonly parameters: Type.TObject<{
332
- glob: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
333
- limit: Type.TOptional<Type.TInteger>;
334
- crumpled: Type.TOptional<Type.TBoolean>;
335
- cwd: Type.TOptional<Type.TString>;
336
- }>;
337
- readonly outputSchema: Type.TUnion<[Type.TObject<{
338
- more: Type.TInteger;
339
- namespaces_unavailable: Type.TArray<Type.TString>;
340
- files: Type.TArray<Type.TObject<{
341
- updated_at: Type.TString;
342
- crumpled_at: Type.TOptional<Type.TString>;
343
- warnings: Type.TArray<Type.TString>;
344
- pinned: Type.TBoolean;
345
- budget: Type.TInteger;
346
- readonly: Type.TBoolean;
347
- project_root: Type.TOptional<Type.TString>;
348
- project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
349
- name: Type.TString;
350
- path: Type.TString;
351
- }>>>;
352
- address: Type.TString;
353
- project_key: Type.TOptional<Type.TString>;
354
- }>>;
355
- }>, Type.TObject<{
356
- error: Type.TString;
357
- code: Type.TString;
358
- }>]>;
359
- readonly execute: (params: Static<typeof notesListParameters>, context: NotesToolContext) => Promise<Outcome<NotesListData>>;
360
- readonly render: (result: Outcome<NotesListData>) => string;
361
- };
362
- export declare const notesSearchParameters: Type.TObject<{
363
- query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
364
- glob: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
365
- limit: Type.TOptional<Type.TInteger>;
366
- max_matches_per_file: Type.TOptional<Type.TInteger>;
367
- crumpled: Type.TOptional<Type.TBoolean>;
368
- cwd: Type.TOptional<Type.TString>;
369
- }>;
370
- /** A shortened match line still ends with a marker, so its own text says it was cut. */
371
- export declare const MATCH_SHORTENED_MARKER = " [truncated]";
372
- export declare const notesSearch: {
373
- readonly name: "notes_search";
374
- readonly label: "Notes search";
375
- readonly description: "Run a finger down every page for some text, case doesn't matter. Returns the lines it hits and where they sit; no query just lists the pages. One pass; `more` counts pages left on the pile — narrow `glob`.";
315
+ readonly description: "List or search notes, newest pages on top. A query matches literal text (ignoring case) and returns hit lines and read offsets. One pass; `more` counts pages left on the pile — narrow `glob`.";
376
316
  readonly parameters: Type.TObject<{
317
+ glob: Type.TOptional<Type.TString>;
377
318
  query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
378
- glob: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
379
- limit: Type.TOptional<Type.TInteger>;
380
319
  max_matches_per_file: Type.TOptional<Type.TInteger>;
381
320
  crumpled: Type.TOptional<Type.TBoolean>;
321
+ limit: Type.TOptional<Type.TInteger>;
382
322
  cwd: Type.TOptional<Type.TString>;
383
323
  }>;
384
324
  readonly outputSchema: Type.TUnion<[Type.TObject<{
385
325
  more: Type.TInteger;
386
326
  namespaces_unavailable: Type.TArray<Type.TString>;
387
327
  files: Type.TArray<Type.TObject<{
388
- matches: Type.TArray<Type.TObject<{
328
+ matches: Type.TOptional<Type.TArray<Type.TObject<{
389
329
  line: Type.TInteger;
390
330
  text: Type.TString;
391
331
  offset_chars: Type.TInteger;
392
- }>>;
332
+ }>>>;
393
333
  more_matches: Type.TOptional<Type.TInteger>;
394
334
  updated_at: Type.TString;
395
335
  crumpled_at: Type.TOptional<Type.TString>;
@@ -409,7 +349,7 @@ export declare const notesSearch: {
409
349
  error: Type.TString;
410
350
  code: Type.TString;
411
351
  }>]>;
412
- readonly execute: (params: Static<typeof notesSearchParameters>, context: NotesToolContext) => Promise<Outcome<NotesSearchData>>;
413
- readonly render: (result: Outcome<NotesSearchData>) => string;
352
+ readonly execute: (params: Static<typeof notesListParameters>, context: NotesToolContext) => Promise<Outcome<NotesListData>>;
353
+ readonly render: (result: Outcome<NotesListData>) => string;
414
354
  };
415
355
  export {};