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
@@ -5,7 +5,7 @@ import { CallToolRequestSchema, ListToolsRequestSchema, type CallToolResult, typ
5
5
  import { Check } from "typebox/value";
6
6
  import { paramProblem } from "../../../src/tools/schema.js";
7
7
  import type { TSchema } from "typebox";
8
- import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
8
+ import { notesList, notesRead, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
9
9
  import { historyList, historyRead } from "../../../src/tools/history.js";
10
10
  import type { Outcome } from "../../../src/result.js";
11
11
  import { wireResult, type Operation } from "../../../src/tools/result.js";
@@ -25,7 +25,6 @@ const OPERATIONS: Record<string, Bound> = {
25
25
  notes_update: { operation: notesUpdate as unknown as Bound["operation"], history: false },
26
26
  notes_read: { operation: notesRead as unknown as Bound["operation"], history: false },
27
27
  notes_list: { operation: notesList as unknown as Bound["operation"], history: false },
28
- notes_search: { operation: notesSearch as unknown as Bound["operation"], history: false },
29
28
  history_list: { operation: historyList as unknown as Bound["operation"], history: true },
30
29
  history_read: { operation: historyRead as unknown as Bound["operation"], history: true },
31
30
  };
@@ -4,7 +4,7 @@ import { HarnessError } from "@deepseek-ai/dsh-llm";
4
4
  import { defineTool, type JsonSchemaNode, type ObjectJsonSchema, type ToolRunContext } from "@deepseek-ai/dsh-tools";
5
5
  import type { Static, TSchema } from "typebox";
6
6
  import { Check, Errors } from "typebox/value";
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 { success } from "../../src/result.js";
10
10
  import type { Operation } from "../../src/tools/result.js";
@@ -75,7 +75,6 @@ export function registerTools(ctx: Context, engine: NotesoupCompactionEngine): v
75
75
  register(ctx, notesUpdate, (agent) => [toolContext(agent)] as const);
76
76
  register(ctx, notesRead, (agent) => [toolContext(agent)] as const);
77
77
  register(ctx, notesList, (agent) => [toolContext(agent)] as const);
78
- register(ctx, notesSearch, (agent) => [toolContext(agent)] as const);
79
78
  register(ctx, historyList, (agent) => [historyContext(ctx, agent.session.id)] as const);
80
79
  register(ctx, historyRead, (agent) => [historyContext(ctx, agent.session.id)] as const);
81
80
  ctx.tools.register(defineTool({
@@ -1,5 +1,5 @@
1
1
  import { generateDiffString, type ExtensionAPI, type ExtensionContext } 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, type DreamState } from "../../../src/tools/dream.js";
4
4
  import { notesIdentityFromPi } from "./adapter.js";
5
5
  import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
@@ -11,7 +11,7 @@ function renderDiff(change: NoteChange): string {
11
11
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
12
12
  }
13
13
 
14
- /** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
14
+ /** Register the shared note operations and the three hidden dream tools; an open dream widens the note identity. */
15
15
  export function registerNotesTools(pi: ExtensionAPI) {
16
16
  // One pending or open dream per session: shutdown releases ownership without the end commit.
17
17
  const dreams = new Map<string, DreamState>();
@@ -35,7 +35,6 @@ export function registerNotesTools(pi: ExtensionAPI) {
35
35
  }, NOTES_NAMESPACE, notesUpdateRenderers);
36
36
  registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, toolContext(ctx)), NOTES_NAMESPACE, notesReadRenderers);
37
37
  registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
38
- registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
39
38
  registerOperation(pi, dreamBegin, (params, ctx) => dreamBegin.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
40
39
  registerOperation(pi, dreamForget, (params, ctx) => dreamForget.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
41
40
  registerOperation(pi, dreamEnd, (params, ctx) => dreamEnd.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
@@ -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
 
package/src/dream/git.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { execFileSync, spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { errorMessage } from "../error-message.js";
5
5
 
@@ -9,18 +9,18 @@ export type AuditResult =
9
9
  | { ok: false; error: string };
10
10
 
11
11
  /** Lock runtime artifacts are not notes and must not appear in snapshots or `git status`. */
12
- const RUNTIME_IGNORE = ".dream.lock*";
12
+ const RUNTIME_IGNORE = ["/.dream.lock*", "/.project-claim.sqlite", "/.project-claim.sqlite-*", "/.project-pending-*/"];
13
13
 
14
- /** Add the runtime-artifact pattern to the repository's local exclude, once. */
14
+ /** Install root-only excludes before staging; fail the audit rather than snapshot runtime files. */
15
15
  function ensureRuntimeIgnored(home: string): void {
16
- try {
17
- const exclude = join(home, ".git", "info", "exclude");
18
- const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
19
- if (current.split(/\r?\n/).includes(RUNTIME_IGNORE)) return;
20
- mkdirSync(dirname(exclude), { recursive: true });
21
- const prefix = current.length > 0 && !current.endsWith("\n") ? `${current}\n` : current;
22
- writeFileSync(exclude, `${prefix}${RUNTIME_IGNORE}\n`);
23
- } catch { /* best effort: an unignored lock only adds noise to the audit */ }
16
+ const exclude = join(home, ".git", "info", "exclude");
17
+ const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
18
+ const lines = new Set(current.split(/\r?\n/));
19
+ const missing = RUNTIME_IGNORE.filter(pattern => !lines.has(pattern));
20
+ if (!missing.length) return;
21
+ mkdirSync(dirname(exclude), { recursive: true });
22
+ const prefix = current.length && !current.endsWith("\n") ? "\n" : "";
23
+ appendFileSync(exclude, prefix + missing.join("\n") + "\n");
24
24
  }
25
25
 
26
26
  /** Snapshot at begin and end; a repository without HEAD gets an empty baseline commit. */
@@ -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
  }
@@ -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
 
6
7
  export type ProjectMarker = { id: string; path: string };
@@ -115,70 +116,47 @@ function updateMarker(namespace: ProjectNamespace, marker: ProjectMarker): Proje
115
116
  return { ...namespace, ...marker };
116
117
  }
117
118
 
118
- const claimSleep = new Int32Array(new SharedArrayBuffer(4));
119
-
120
- function awaitClaim<T>(path: string, attempt: () => T | undefined): T {
121
- const deadline = performance.now() + 5_000;
122
- for (;;) {
123
- const result = attempt();
124
- if (result !== undefined) return result;
125
- const remaining = deadline - performance.now();
126
- if (remaining <= 0) throw new Error(`Timed out waiting for project claim at ${path}`);
127
- Atomics.wait(claimSleep, 0, 0, Math.min(10, remaining));
128
- }
119
+ function checkoutMarker(cwd: string): ProjectMarker {
120
+ const path = canonicalRoot(cwd);
121
+ return { id: originRemote(path) ?? path, path };
129
122
  }
130
123
 
131
124
  /** Resolve and claim the readable notebook for one repository identity. */
132
125
  export function resolveProjectNamespace(cwd: string, home: string): ProjectNamespace {
133
- mkdirSync(projectRoot(home), { recursive: true });
134
- // Serialize the scan as well as publication: an unmarked directory seen under
135
- // this lock is legacy, not another resolver between mkdir and marker write.
136
- const lock = join(home, ".project-claim");
137
- awaitClaim(lock, () => {
138
- try { mkdirSync(lock); return true; } catch (error) {
139
- if (errno(error) === "EEXIST") return undefined;
140
- throw error;
141
- }
142
- });
143
- try { return claimProjectNamespace(cwd, home); } finally { rmdirSync(lock); }
144
- }
126
+ const expected = checkoutMarker(cwd);
127
+ const current = projectNamespaces(home).find(candidate => candidate.id === expected.id);
128
+ if (current?.path === expected.path) return current;
145
129
 
146
- function claimProjectNamespace(cwd: string, home: string): ProjectNamespace {
147
- const root = canonicalRoot(cwd);
148
- const remote = originRemote(root);
149
- const id = remote ?? root;
150
- const markerRoot = projectRoot(home);
151
- mkdirSync(markerRoot, { recursive: true });
152
- const namespaces = projectNamespaces(home);
153
- let found = namespaces.find(candidate => candidate.id === id);
154
- if (!found && remote) {
155
- found = namespaces.find(candidate => candidate.id === root);
156
- if (found) found = updateMarker(found, { id: remote, path: root });
157
- }
158
- if (found) {
159
- if (found.path !== root) found = updateMarker(found, { id: found.id, path: root });
160
- return found;
161
- }
162
-
163
- const base = slugify(basename(root));
164
- // The claim lock makes this a stable snapshot of legacy, unmarked names.
165
- const taken = new Set(readdirSync(markerRoot));
166
- for (let suffix = 0; ; suffix++) {
167
- const name = suffix === 0 ? base : `${base}-${suffix}`;
168
- if (taken.has(name)) continue;
169
- const dir = join(markerRoot, name);
170
- try {
171
- mkdirSync(dir);
172
- } catch (error) {
173
- if (errno(error) !== "EEXIST") throw error;
174
- // A writer outside this protocol may have won after the snapshot.
175
- // Never mistake its incomplete publication for a different identity.
176
- let winner = awaitClaim(join(dir, ".project"), () => readMarker(dir));
177
- if (winner.id !== id && !(remote && winner.id === root)) continue;
178
- if (winner.id !== id || winner.path !== root) winner = updateMarker(winner, { id, path: root });
179
- return winner;
130
+ const root = projectRoot(home);
131
+ mkdirSync(root, { recursive: true });
132
+ const lockPath = join(home, ".project-claim.sqlite");
133
+ const release = trySqliteLock(lockPath, 5000);
134
+ if (!release) throw new Error(`Timed out waiting for project claim at ${lockPath}`);
135
+ try {
136
+ // The checkout may have gained an origin and a peer may have already adopted it.
137
+ const marker = checkoutMarker(cwd);
138
+ const { id, path } = marker;
139
+ const namespaces = projectNamespaces(home);
140
+ const found = namespaces.find(candidate => candidate.id === id) ?? namespaces.find(candidate => candidate.id === path);
141
+ if (found) return found.id === id && found.path === path ? found : updateMarker(found, marker);
142
+
143
+ const base = slugify(basename(path));
144
+ for (let suffix = 0; ; suffix++) {
145
+ const name = suffix === 0 ? base : `${base}-${suffix}`;
146
+ const dir = join(root, name);
147
+ if (lstatSync(dir, { throwIfNoEntry: false })) continue; // Includes unmarked legacy names.
148
+ const staged = mkdtempSync(join(home, ".project-pending-"));
149
+ try {
150
+ writeFileSync(join(staged, ".project"), JSON.stringify(marker));
151
+ renameSync(staged, dir);
152
+ } catch (error) {
153
+ rmSync(staged, { recursive: true, force: true });
154
+ throw error;
155
+ }
156
+ return { name, dir, ...marker };
180
157
  }
181
- return updateMarker({ name, dir, id, path: root }, { id, path: root });
158
+ } finally {
159
+ release();
182
160
  }
183
161
  }
184
162
 
@@ -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);
@@ -0,0 +1,14 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export function trySqliteLock(path: string, waitMs: 0 | 5000): (() => void) | undefined {
3
+ const sqlite = process.getBuiltinModule?.("node:sqlite") as typeof import("node:sqlite") | undefined;
4
+ if (!sqlite?.DatabaseSync) throw new Error("Notesoup locks require built-in node:sqlite (Node 22.13+).");
5
+ const db = new sqlite.DatabaseSync(path);
6
+ try {
7
+ db.exec(`PRAGMA busy_timeout = ${waitMs}; BEGIN IMMEDIATE`);
8
+ } catch (error) {
9
+ db.close();
10
+ if (error instanceof Error && "errcode" in error && error.errcode === 5) return undefined; // SQLITE_BUSY
11
+ throw error;
12
+ }
13
+ return () => db.close(); // Closing rolls back the empty transaction.
14
+ }