notesoup 0.61.0 → 0.62.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 (200) hide show
  1. package/.agents/plugins/marketplace.json +15 -0
  2. package/README.md +14 -11
  3. package/dist/plugins/antigravity/src/cli.d.ts +1 -0
  4. package/dist/plugins/antigravity/src/cli.js +23 -0
  5. package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
  6. package/dist/plugins/antigravity/src/hooks.js +53 -0
  7. package/dist/plugins/antigravity/src/identity.d.ts +26 -0
  8. package/dist/plugins/antigravity/src/identity.js +129 -0
  9. package/dist/plugins/claude/src/helper.js +2 -1
  10. package/dist/plugins/codex/src/hooks.js +1 -0
  11. package/dist/plugins/codex/src/identity.d.ts +6 -1
  12. package/dist/plugins/codex/src/identity.js +13 -1
  13. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  14. package/dist/plugins/codex/src/mcp.js +26 -88
  15. package/dist/plugins/codex/src/text.js +3 -3
  16. package/dist/plugins/dsh/tools.js +8 -4
  17. package/dist/plugins/mcp/operations.d.ts +15 -0
  18. package/dist/plugins/mcp/operations.js +43 -0
  19. package/dist/plugins/mcp/server.d.ts +14 -0
  20. package/dist/plugins/mcp/server.js +13 -0
  21. package/dist/plugins/pi/budget.d.ts +1 -1
  22. package/dist/plugins/pi/budget.js +3 -2
  23. package/dist/plugins/pi/entries.d.ts +1 -0
  24. package/dist/plugins/pi/entries.js +1 -0
  25. package/dist/plugins/pi/history-tools.js +2 -1
  26. package/dist/plugins/pi/history.js +18 -1
  27. package/dist/plugins/pi/notes/tools.js +7 -3
  28. package/dist/plugins/pi/render.d.ts +7 -1
  29. package/dist/plugins/pi/render.js +2 -2
  30. package/dist/plugins/pi/reset/lifecycle.d.ts +1 -1
  31. package/dist/plugins/pi/reset/lifecycle.js +8 -9
  32. package/dist/plugins/pi/runtime.js +102 -61
  33. package/dist/plugins/pi/tool-result.js +7 -7
  34. package/dist/plugins/pi/window.d.ts +33 -3
  35. package/dist/plugins/pi/window.js +209 -9
  36. package/dist/src/boot/render.js +18 -15
  37. package/dist/src/boot/text.d.ts +3 -1
  38. package/dist/src/boot/text.js +22 -20
  39. package/dist/src/budget/text.d.ts +2 -2
  40. package/dist/src/budget/text.js +13 -13
  41. package/dist/src/history/claude.d.ts +2 -0
  42. package/dist/src/history/claude.js +46 -0
  43. package/dist/src/history/codex-transcript.js +7 -5
  44. package/dist/src/history/codex.js +3 -0
  45. package/dist/src/history/corpus.d.ts +28 -1
  46. package/dist/src/history/corpus.js +40 -0
  47. package/dist/src/history/history.d.ts +37 -46
  48. package/dist/src/history/history.js +21 -40
  49. package/dist/src/history/local.js +67 -32
  50. package/dist/src/history/pi.d.ts +2 -1
  51. package/dist/src/history/pi.js +122 -48
  52. package/dist/src/history/prefilter.js +76 -19
  53. package/dist/src/history/query.d.ts +28 -49
  54. package/dist/src/history/query.js +83 -68
  55. package/dist/src/history/summary-cache.d.ts +8 -1
  56. package/dist/src/history/summary-cache.js +138 -12
  57. package/dist/src/index.d.ts +1 -1
  58. package/dist/src/index.js +1 -1
  59. package/dist/src/notes/errors.d.ts +1 -1
  60. package/dist/src/notes/frontmatter.d.ts +0 -2
  61. package/dist/src/notes/frontmatter.js +0 -2
  62. package/dist/src/notes/index.d.ts +1 -1
  63. package/dist/src/notes/index.js +1 -1
  64. package/dist/src/notes/policy.d.ts +15 -1
  65. package/dist/src/notes/policy.js +46 -5
  66. package/dist/src/notes/store.d.ts +12 -0
  67. package/dist/src/notes/store.js +16 -20
  68. package/dist/src/text-match.d.ts +10 -1
  69. package/dist/src/text-match.js +42 -3
  70. package/dist/src/tools/dream.d.ts +22 -93
  71. package/dist/src/tools/dream.js +30 -27
  72. package/dist/src/tools/history.d.ts +33 -26
  73. package/dist/src/tools/history.js +257 -163
  74. package/dist/src/tools/notes.d.ts +51 -163
  75. package/dist/src/tools/notes.js +146 -100
  76. package/dist/src/tools/output.d.ts +2 -1
  77. package/dist/src/tools/output.js +2 -1
  78. package/dist/src/tools/result.d.ts +4 -7
  79. package/dist/src/tools/result.js +8 -9
  80. package/dist/src/tools/schema.d.ts +4 -1
  81. package/dist/src/tools/schema.js +25 -1
  82. package/dist/test/agent-loop.test.js +198 -16
  83. package/dist/test/antigravity-live.test.d.ts +1 -0
  84. package/dist/test/antigravity-live.test.js +142 -0
  85. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  86. package/dist/test/antigravity-plugin.test.js +101 -0
  87. package/dist/test/boot.integration.test.js +133 -14
  88. package/dist/test/claude-history.test.js +14 -13
  89. package/dist/test/claude-mod.test.js +9 -6
  90. package/dist/test/codex-history.test.js +15 -3
  91. package/dist/test/codex-plugin.test.js +76 -38
  92. package/dist/test/dependencies.test.js +7 -3
  93. package/dist/test/dream-skill.test.js +3 -3
  94. package/dist/test/dream-tools.test.js +101 -56
  95. package/dist/test/dsh.test.js +34 -19
  96. package/dist/test/helpers/dependency-graph.js +2 -2
  97. package/dist/test/helpers/extension.d.ts +65 -2
  98. package/dist/test/helpers/extension.js +72 -3
  99. package/dist/test/history-corpus.test.js +79 -77
  100. package/dist/test/history-summary-cache.test.js +97 -9
  101. package/dist/test/history.integration.test.js +234 -168
  102. package/dist/test/host-neutral.test.js +69 -19
  103. package/dist/test/marker.test.js +1 -1
  104. package/dist/test/note-policy.test.js +96 -77
  105. package/dist/test/notes.integration.test.js +212 -94
  106. package/dist/test/notes.test.js +184 -113
  107. package/dist/test/pi-render.test.js +20 -12
  108. package/dist/test/project-namespace.test.js +3 -2
  109. package/dist/test/reset-lifecycle.test.js +2 -2
  110. package/docs/antigravity.md +44 -0
  111. package/docs/architecture.md +6 -4
  112. package/docs/claude-code-mod.md +2 -2
  113. package/docs/codex.md +36 -38
  114. package/docs/dsh.md +3 -3
  115. package/docs/history-sessions.md +28 -50
  116. package/docs/notes-library.md +4 -4
  117. package/docs/skills.md +3 -3
  118. package/docs/tool-results.md +47 -28
  119. package/package.json +3 -2
  120. package/playbook.md +1 -1
  121. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  122. package/plugins/antigravity/hooks.json +7 -0
  123. package/plugins/antigravity/mcp_config.json +8 -0
  124. package/plugins/antigravity/plugin.json +6 -0
  125. package/plugins/antigravity/src/cli.ts +22 -0
  126. package/plugins/antigravity/src/hooks.ts +51 -0
  127. package/plugins/antigravity/src/identity.ts +127 -0
  128. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  129. package/plugins/claude/dist/claude/helper.js +1059 -534
  130. package/plugins/claude/hooks/register.ts +2 -2
  131. package/plugins/claude/playbook.md +1 -1
  132. package/plugins/claude/skills/dream/SKILL.md +1 -1
  133. package/plugins/claude/skills/notesoup/SKILL.md +92 -0
  134. package/plugins/claude/src/helper.ts +2 -1
  135. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  136. package/plugins/codex/.mcp.json +11 -0
  137. package/plugins/codex/README.md +5 -21
  138. package/plugins/codex/dist/codex/notesoup.js +18480 -17946
  139. package/plugins/codex/src/hooks.ts +1 -0
  140. package/plugins/codex/src/identity.ts +14 -1
  141. package/plugins/codex/src/mcp.ts +28 -98
  142. package/plugins/codex/src/text.ts +3 -3
  143. package/plugins/dsh/tools.ts +8 -4
  144. package/plugins/mcp/operations.ts +50 -0
  145. package/plugins/mcp/server.ts +23 -0
  146. package/plugins/paseo/README.md +5 -10
  147. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  148. package/plugins/paseo/client/markdown.tsx +50 -38
  149. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  150. package/plugins/paseo/client/paper-card.tsx +6 -5
  151. package/plugins/paseo/client/paper-palette.ts +2 -9
  152. package/plugins/paseo/client/sticky-card.tsx +2 -2
  153. package/plugins/paseo/client/tool-result.ts +7 -14
  154. package/plugins/paseo/package-lock.json +3406 -0
  155. package/plugins/paseo/package.json +1 -0
  156. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  157. package/plugins/pi/budget.ts +3 -3
  158. package/plugins/pi/entries.ts +1 -0
  159. package/plugins/pi/history-tools.ts +2 -1
  160. package/plugins/pi/history.ts +30 -1
  161. package/plugins/pi/notes/tools.ts +7 -3
  162. package/plugins/pi/render.ts +6 -6
  163. package/plugins/pi/reset/lifecycle.ts +9 -10
  164. package/plugins/pi/runtime.ts +96 -60
  165. package/plugins/pi/tool-result.ts +8 -8
  166. package/plugins/pi/window.ts +198 -9
  167. package/skills/dream/SKILL.md +1 -1
  168. package/skills/notesoup/SKILL.md +92 -0
  169. package/src/boot/render.ts +18 -15
  170. package/src/boot/text.ts +23 -19
  171. package/src/budget/text.ts +13 -13
  172. package/src/history/claude.ts +41 -0
  173. package/src/history/codex-transcript.ts +6 -4
  174. package/src/history/codex.ts +2 -0
  175. package/src/history/corpus.ts +51 -2
  176. package/src/history/history.ts +35 -44
  177. package/src/history/local.ts +67 -27
  178. package/src/history/pi.ts +113 -35
  179. package/src/history/prefilter.ts +73 -15
  180. package/src/history/query.ts +93 -73
  181. package/src/history/summary-cache.ts +142 -17
  182. package/src/index.ts +1 -1
  183. package/src/notes/errors.ts +1 -1
  184. package/src/notes/frontmatter.ts +0 -3
  185. package/src/notes/index.ts +1 -1
  186. package/src/notes/policy.ts +44 -5
  187. package/src/notes/store.ts +17 -20
  188. package/src/text-match.ts +46 -4
  189. package/src/tools/dream.ts +29 -31
  190. package/src/tools/history.ts +249 -142
  191. package/src/tools/notes.ts +145 -113
  192. package/src/tools/output.ts +2 -1
  193. package/src/tools/result.ts +12 -11
  194. package/src/tools/schema.ts +24 -1
  195. package/plugins/claude/skills/memory/SKILL.md +0 -69
  196. package/plugins/codex/mcp.json +0 -10
  197. package/plugins/codex/plugin.json +0 -6
  198. package/plugins/paseo/client/markdown-core.tsx +0 -189
  199. package/plugins/paseo/client/typography.ts +0 -24
  200. package/skills/memory/SKILL.md +0 -69
@@ -8,13 +8,17 @@ import { isFilesystemError } from "./fs-error.js";
8
8
  import { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
9
9
  import { NoteError } from "./errors.js";
10
10
  import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
11
- import { collapseDescription, isOrigin, localIso, MAX_DESCRIPTION_CHARS, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
11
+ import { collapseDescription, isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter, type NoteMeta, type Origin } from "./frontmatter.js";
12
12
  import { namespaceSlugs, noteFileName, physicalPath, scopeDir, isSessionId, SLUG_PATTERN, type Scope } from "./paths.js";
13
13
  import { projectReceipt, type ProjectReceipt } from "./project-namespace.js";
14
- import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteBudgetWarnings, validateNotePolicy, type NotePolicyFields } from "./policy.js";
14
+ import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteWarnings, validateNotePolicy, type NotePolicyFields } from "./policy.js";
15
15
 
16
16
  export type { NoteMeta, Origin, Scope };
17
17
 
18
+ export function compareNoteRows(a: { address: string; meta: { updatedAt: number } }, b: { address: string; meta: { updatedAt: number } }): number {
19
+ return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
20
+ }
21
+
18
22
  export type NoteRow = { address: string; scope: Scope; path: string; meta: NoteMeta; body: string; sizeBytes: number };
19
23
 
20
24
  // Recency sorts tie-break by address, so two writes sharing one Date.now() tick would silently invert the recent-first contract. Write stamps are strictly increasing per process.
@@ -26,7 +30,7 @@ function writeStamp(): number {
26
30
  }
27
31
  export type NoteMatch = { line: number; text: string; /** Code-point offset into the note body, not into the serialized file. */ offsetChars: number };
28
32
  export type NoteSearchRow = { address: string; scope: Scope; path: string; meta: NoteMeta; warnings: string[]; matches: NoteMatch[] };
29
- export type EditOperation = { oldText: string; newText: string };
33
+ export type EditOperation = { oldText: string; newText: string; replaceAll?: boolean };
30
34
  export type WriteOptions = NotePolicyFields & { origin?: Origin; description?: string };
31
35
  export type EditOptions = NotePolicyFields & { origin?: Origin; description?: string; crumpled?: boolean; replaceAll?: boolean; renameTo?: string };
32
36
  /** Omit glob for current notebooks. A pattern without `@` or `/` matches filenames at any depth. */
@@ -188,15 +192,6 @@ function assertOrigin(value: unknown): Origin {
188
192
  return value;
189
193
  }
190
194
 
191
- /** A description is one normalized line; empty clears it. Only the authored value is refused, never read. */
192
- function normalizeDescription(value: string): string | undefined {
193
- const collapsed = collapseDescription(value);
194
- if (collapsed === undefined) return undefined;
195
- const count = Array.from(collapsed).length;
196
- if (count > MAX_DESCRIPTION_CHARS) throw new NoteError("invalid_description", `description is ${count} characters; limit is ${MAX_DESCRIPTION_CHARS}.`);
197
- return collapsed;
198
- }
199
-
200
195
  function assertWho(value: unknown, scope: Scope): string {
201
196
  if (typeof value !== "string" || !(scope === "session" ? isSessionId(value) : SLUG_PATTERN.test(value))) {
202
197
  throw new NoteError("invalid_scope", scope === "session" ? "session id must be a safe single directory component" : "who must be a canonical lowercase slug");
@@ -319,7 +314,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
319
314
  async function write(address: string, content: string, options: WriteOptions = {}): Promise<NoteWriteResult> {
320
315
  const stableOptions = { ...options };
321
316
  validateNotePolicy(stableOptions);
322
- const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
317
+ const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
323
318
  const destination = assertAddress(address);
324
319
  assertWritablePath(destination.path);
325
320
  const scope = destination.scope;
@@ -359,7 +354,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
359
354
  assertSerializedSize(serialized);
360
355
  await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
361
356
  await atomicWrite(path, serialized);
362
- return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
357
+ return { meta, outcome, warnings: noteWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description) };
363
358
  }));
364
359
  }
365
360
 
@@ -385,7 +380,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
385
380
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
386
381
  const stableOptions = { ...options };
387
382
  validateNotePolicy(stableOptions);
388
- const description = stableOptions.description === undefined ? undefined : normalizeDescription(stableOptions.description);
383
+ const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
389
384
  const from = assertAddress(address);
390
385
  const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
391
386
  assertWritablePath(destination.path);
@@ -432,14 +427,16 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
432
427
  const newText = operation?.newText;
433
428
  if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
434
429
  if (typeof newText !== "string") throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
430
+ if (operation.replaceAll !== undefined && typeof operation.replaceAll !== "boolean") throw new NoteError("invalid_edit", `edits[${index}].replaceAll must be a boolean.`, { editIndex: index });
431
+ const replaceAll = operation.replaceAll ?? stableOptions.replaceAll ?? false;
435
432
  const lines = matchLineNumbers(next, oldText);
436
433
  if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
437
- if (lines.length > 1 && !stableOptions.replaceAll) {
434
+ if (lines.length > 1 && !replaceAll) {
438
435
  throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
439
436
  }
440
437
  if (oldText !== newText) applied++;
441
438
  // Positional splicing preserves user replacement text byte-for-byte.
442
- if (stableOptions.replaceAll) next = next.split(oldText).join(newText);
439
+ if (replaceAll) next = next.split(oldText).join(newText);
443
440
  else {
444
441
  const matchIndex = next.indexOf(oldText);
445
442
  next = next.substring(0, matchIndex) + newText + next.substring(matchIndex + oldText.length);
@@ -467,7 +464,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
467
464
  moved ? { root: fromRoot, path: noteFileName(from.path), meta: beforeMeta } : undefined);
468
465
  await atomicWrite(sameFile ? sourceReal! : path, serialized);
469
466
  if (moved) await rm(fromPath, { force: true });
470
- return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
467
+ return { meta, warnings: noteWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
471
468
  };
472
469
  return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
473
470
  }
@@ -543,7 +540,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
543
540
  for await (const row of scan(stableOptions, status)) {
544
541
  rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
545
542
  }
546
- rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
543
+ rows.sort(compareNoteRows);
547
544
  return { rows, status: status ?? { namespacesUnavailable: [] } };
548
545
  }
549
546
 
@@ -561,7 +558,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
561
558
  const rows: NoteSearchRow[] = [];
562
559
  for await (const note of scan(stableOptions, status)) {
563
560
  const { address, path, scope, meta, body } = note;
564
- const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
561
+ const warnings = noteWarnings(body, effectiveNotePolicy(meta, path), meta.description);
565
562
  if (stableQueries.length === 0) {
566
563
  rows.push({ address, path, scope, meta, warnings, matches: [] });
567
564
  continue;
package/src/text-match.ts CHANGED
@@ -30,17 +30,59 @@ export function prefixFit(text: string, fits: (content: string) => boolean): str
30
30
  return chars.slice(0, low).join("");
31
31
  }
32
32
 
33
+ /** Compile literal Unicode case-insensitive patterns once per search operation. */
34
+ export function compileSearchQueries(queries: readonly string[]): RegExp[] {
35
+ return queries.map((query) => new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu"));
36
+ }
37
+
38
+ /** Count Unicode code points in `text.slice(0, utf16End)` without allocating an array. */
39
+ export function codePointCount(text: string, utf16End = text.length): number {
40
+ let count = utf16End;
41
+ for (let i = 0; i < utf16End - 1; i++) {
42
+ const code = text.charCodeAt(i);
43
+ if (code >= 0xd800 && code <= 0xdbff) {
44
+ const next = text.charCodeAt(i + 1);
45
+ if (next >= 0xdc00 && next <= 0xdfff) {
46
+ count--;
47
+ i++;
48
+ }
49
+ }
50
+ }
51
+ return count;
52
+ }
53
+
54
+ /** Slice `[start, start + limit)` code points without splitting the entire string into an array. */
55
+ export function sliceCodePoints(text: string, start: number, limit: number): { text: string; truncated: boolean } {
56
+ const len = text.length;
57
+ let utf16Start = 0;
58
+ let cp = 0;
59
+ while (cp < start && utf16Start < len) {
60
+ const code = text.charCodeAt(utf16Start);
61
+ utf16Start += code >= 0xd800 && code <= 0xdbff && utf16Start + 1 < len && text.charCodeAt(utf16Start + 1) >= 0xdc00 && text.charCodeAt(utf16Start + 1) <= 0xdfff ? 2 : 1;
62
+ cp++;
63
+ }
64
+ let utf16End = utf16Start;
65
+ let taken = 0;
66
+ while (taken < limit && utf16End < len) {
67
+ const code = text.charCodeAt(utf16End);
68
+ utf16End += code >= 0xd800 && code <= 0xdbff && utf16End + 1 < len && text.charCodeAt(utf16End + 1) >= 0xdc00 && text.charCodeAt(utf16End + 1) <= 0xdfff ? 2 : 1;
69
+ taken++;
70
+ }
71
+ const truncated = start > 0 || utf16End < len;
72
+ return { text: truncated ? text.slice(utf16Start, utf16End) : text, truncated };
73
+ }
74
+
33
75
  /**
34
76
  * Code-point offset of the earliest case-insensitive literal match, or -1 when
35
77
  * none occurs. Match against the original text so Unicode casing cannot shift offsets.
36
78
  */
37
- export function earliestMatchOffsetChars(text: string, queries: string[]): number {
79
+ export function earliestMatchOffsetChars(text: string, queries: readonly (string | RegExp)[]): number {
38
80
  let earliest = -1;
39
81
  for (const query of queries) {
40
- const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
- const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
82
+ const pattern = typeof query === "string" ? new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu") : query;
83
+ const index = pattern.exec(text)?.index ?? -1;
42
84
  if (index < 0) continue;
43
85
  if (earliest < 0 || index < earliest) earliest = index;
44
86
  }
45
- return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
87
+ return earliest < 0 ? -1 : codePointCount(text, earliest);
46
88
  }
@@ -2,13 +2,14 @@
2
2
  import { join } from "node:path";
3
3
  import { Type, type Static } from "typebox";
4
4
  import { localIso } from "../notes/frontmatter.js";
5
- import { createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
6
- import { projectNamespaces } from "../notes/project-namespace.js";
5
+ import { compareNoteRows, createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
6
+ import { projectReceipt, type ProjectReceipt } from "../notes/project-namespace.js";
7
7
  import { gitCommit } from "../dream/git.js";
8
8
  import { trySqliteLock } from "../sqlite-lock.js";
9
9
  import { failure, success, type Outcome } from "../result.js";
10
- import { renderOutcome, resultSchema } from "./result.js";
11
- import { failureOf, listedFile, ListedFileSchema, NoteIdentitySchema, renderListData, snapshot, SnapshotSchema } from "./notes.js";
10
+ import { renderOutcome } from "./result.js";
11
+ import { failureOf, listedFile, renderListData, snapshot, type ListedFile, type Snapshot } from "./notes.js";
12
+ import { notesIdentityForCall, type NotesToolContext } from "./notes-context.js";
12
13
 
13
14
  /** The one open dream per session; the host owns where it lives. */
14
15
  type DreamOpening = { project: string; release: () => void; generation: number };
@@ -54,33 +55,30 @@ export function dreamingIdentity(identity: NotesIdentity, state: DreamState): No
54
55
  const NOT_DREAMING = "No dream is open; call dream_begin first.";
55
56
 
56
57
  export const dreamBeginParameters = Type.Object({
57
- project: Type.Optional(Type.String({ description: "Which project's pages; leave it out for this one." })),
58
+ cwd: Type.Optional(Type.String({ minLength: 1, description: "Treat this directory's project as current." })),
58
59
  }, { additionalProperties: false });
59
60
 
60
- export const DreamBeginDataSchema = Type.Object({
61
- project: Type.String(), baseline: Type.String(),
62
- files: Type.Array(Type.Object({ ...ListedFileSchema.properties, last_accessed: Type.String() }, { additionalProperties: false })),
63
- ...SnapshotSchema,
64
- }, { additionalProperties: false });
65
- export type DreamBeginData = Static<typeof DreamBeginDataSchema>;
61
+ export type DreamBeginData = Snapshot<ListedFile & { last_accessed: string }> & { project: string; baseline: string } & ProjectReceipt;
66
62
 
67
63
  function renderBeginData(data: DreamBeginData): string {
68
- return `dreaming over ${data.project} (baseline ${data.baseline})\n${renderListData(data)}`;
64
+ const header = `dreaming over ${data.project} (baseline ${data.baseline}${data.project_root === undefined ? "" : `, project_root ${data.project_root}`})`;
65
+ const siblings = data.project_siblings === undefined ? "" : `\n Same-basename projects: ${data.project_siblings.map(sibling => `${sibling.name} (${sibling.path})`).join(", ")}`;
66
+ return `${header}${siblings}\n${renderListData(data, undefined, { omitNamedProjectContext: true })}`;
69
67
  }
70
68
 
71
69
  export const dreamBegin = {
72
70
  name: "dream_begin", label: "Dream begin",
73
- description: "Spread one project's pages across the table — its project shelf, every session page born there, crumpled balls included. Until `dream_end` your pen works on all of them; other sessions' pages can be rewritten, not added to.",
74
- parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
75
- async execute(params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamBeginData>> {
71
+ description: "Open a project's notes and its session notes for consolidation after committing a Git baseline; unlocks writes until `dream_end`.",
72
+ parameters: dreamBeginParameters,
73
+ async execute(params: Static<typeof dreamBeginParameters>, context: NotesToolContext, state: DreamState): Promise<Outcome<DreamBeginData>> {
76
74
  if (state.project !== undefined || state.pending !== undefined) {
77
75
  const project = state.project ?? state.pending?.project;
78
76
  return failure("already_dreaming", `Already dreaming over ${project}; call dream_end before opening another project.`);
79
77
  }
80
- const project = params.project ?? identity.projectKey;
81
- if (project !== identity.projectKey && !projectNamespaces(identity.home).some(namespace => namespace.name === project)) {
82
- return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
83
- }
78
+ let identity: NotesIdentity;
79
+ try { identity = notesIdentityForCall(context, params.cwd); } catch (error) { return failureOf(error); }
80
+ const project = identity.projectKey;
81
+ const receipt = projectReceipt(identity.home, project);
84
82
  const release = trySqliteLock(join(identity.home, ".dream.lock.sqlite"), 0);
85
83
  if (!release) return failure("already_dreaming", "Another dream is open in this notes home.");
86
84
  // Publish ownership before the first await so shutdown can release this transaction.
@@ -98,8 +96,10 @@ export const dreamBegin = {
98
96
  unavailable.push(...result.status.namespacesUnavailable);
99
97
  }
100
98
  }
101
- rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
102
- const listed = snapshot(rows.map(row => ({ ...listedFile(row, identity), last_accessed: localIso(row.meta.lastAccessed) })), undefined, { namespacesUnavailable: unavailable }, renderListData);
99
+ rows.sort(compareNoteRows);
100
+ const listed = snapshot(rows.map(row => ({ ...listedFile(row, identity), last_accessed: localIso(row.meta.lastAccessed) })), undefined, { namespacesUnavailable: unavailable },
101
+ // Reserve the header before committing; Git object IDs are at most 64 hex digits.
102
+ (data) => renderBeginData({ ...data, project, baseline: "0".repeat(64), ...receipt }));
103
103
  if (!listed.ok) {
104
104
  releaseOpening(state, opening);
105
105
  return listed;
@@ -114,7 +114,7 @@ export const dreamBegin = {
114
114
  state.project = opening.project;
115
115
  state.release = opening.release;
116
116
  delete state.pending;
117
- return success({ project, baseline: baseline.commit, ...listed.data });
117
+ return success({ project, baseline: baseline.commit, ...receipt, ...listed.data });
118
118
  } catch (error) {
119
119
  if (!currentOpening(state, opening)) return cancelledOpening(state, opening);
120
120
  releaseOpening(state, opening);
@@ -124,14 +124,13 @@ export const dreamBegin = {
124
124
  render: (result: Outcome<DreamBeginData>): string => renderOutcome(result, renderBeginData),
125
125
  } as const;
126
126
 
127
- export const dreamForgetParameters = Type.Object({ address: Type.String({ description: "Which crumpled page goes in the bin." }) }, { additionalProperties: false });
128
- export const DreamForgetDataSchema = Type.Object({ ...NoteIdentitySchema }, { additionalProperties: false });
129
- export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
127
+ export const dreamForgetParameters = Type.Object({ address: Type.String({ description: "Address of the crumpled note to delete." }) }, { additionalProperties: false });
128
+ export type DreamForgetData = ReturnType<typeof noteIdentity>;
130
129
 
131
130
  export const dreamForget = {
132
131
  name: "dream_forget", label: "Dream forget",
133
- description: "Throw a crumpled page in the bin for good. Only crumpled pages go.",
134
- parameters: dreamForgetParameters, outputSchema: resultSchema(DreamForgetDataSchema),
132
+ description: "Permanently delete a crumpled note in the open dream.",
133
+ parameters: dreamForgetParameters,
135
134
  async execute(params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamForgetData>> {
136
135
  if (state.project === undefined) return failure("not_dreaming", NOT_DREAMING);
137
136
  try {
@@ -144,13 +143,12 @@ export const dreamForget = {
144
143
  } as const;
145
144
 
146
145
  export const dreamEndParameters = Type.Object({}, { additionalProperties: false });
147
- export const DreamEndDataSchema = Type.Object({ project: Type.String(), commit: Type.Optional(Type.String()), audit_error: Type.Optional(Type.String()) }, { additionalProperties: false });
148
- export type DreamEndData = Static<typeof DreamEndDataSchema>;
146
+ export type DreamEndData = { project: string; commit?: string; audit_error?: string };
149
147
 
150
148
  export const dreamEnd = {
151
149
  name: "dream_end", label: "Dream end",
152
- description: "Stack the pages, file them, close the drawer.",
153
- parameters: dreamEndParameters, outputSchema: resultSchema(DreamEndDataSchema),
150
+ description: "Commit dream changes to the notes Git repo and close the open dream.",
151
+ parameters: dreamEndParameters,
154
152
  async execute(_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamEndData>> {
155
153
  const project = state.project;
156
154
  if (project === undefined) return failure("not_dreaming", NOT_DREAMING);