@gmickel/gno 2.14.0 → 2.16.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 (205) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/cli-reference.md +4 -2
  3. package/assets/spa-production.json.gz +0 -0
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.14.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +88 -45
  9. package/spec/db/schema.sql +45 -0
  10. package/spec/output-schemas/embed-receipt.schema.json +89 -0
  11. package/src/cli/commands/agents/commands.ts +1 -1
  12. package/src/cli/commands/ask.ts +1 -1
  13. package/src/cli/commands/context-build.ts +1 -1
  14. package/src/cli/commands/embed.ts +341 -20
  15. package/src/cli/commands/links.ts +1 -1
  16. package/src/cli/commands/mcp/install.ts +2 -2
  17. package/src/cli/commands/mcp/status.ts +1 -1
  18. package/src/cli/commands/mcp/uninstall.ts +1 -1
  19. package/src/cli/commands/query.ts +1 -1
  20. package/src/cli/commands/shared.ts +4 -4
  21. package/src/cli/commands/skill/install.ts +1 -1
  22. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  23. package/src/cli/commands/skill/uninstall.ts +1 -1
  24. package/src/cli/commands/status.ts +75 -58
  25. package/src/cli/config-cache.ts +86 -0
  26. package/src/cli/globals.ts +64 -0
  27. package/src/cli/options.ts +23 -0
  28. package/src/cli/program.ts +44 -37
  29. package/src/cli/run.ts +121 -67
  30. package/src/cli/runtime-health.ts +132 -122
  31. package/src/cli/session-binding.ts +11 -2
  32. package/src/config/saver.ts +8 -0
  33. package/src/converters/adapters/browser-export/formats.ts +25 -15
  34. package/src/converters/adapters/email/adapter.ts +37 -53
  35. package/src/converters/adapters/email/html.ts +37 -20
  36. package/src/converters/adapters/email/mime.ts +71 -39
  37. package/src/converters/adapters/ical/adapter.ts +20 -12
  38. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  39. package/src/converters/adapters/shared/html-text.ts +55 -37
  40. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  41. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  42. package/src/converters/adapters/transcript/adapter.ts +12 -7
  43. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  44. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  45. package/src/converters/canonicalize.ts +17 -3
  46. package/src/converters/native/markdown.ts +24 -17
  47. package/src/converters/native/plaintext.ts +5 -6
  48. package/src/converters/registry.ts +130 -8
  49. package/src/core/activation-status.ts +4 -8
  50. package/src/core/change-diff.ts +38 -11
  51. package/src/core/context-compiler.ts +17 -18
  52. package/src/core/context-evidence.ts +116 -25
  53. package/src/core/context-verifier.ts +70 -31
  54. package/src/core/file-lock.ts +10 -2
  55. package/src/core/graph-analysis.ts +3 -3
  56. package/src/core/link-inventory-markdown.ts +2 -2
  57. package/src/core/links.ts +20 -87
  58. package/src/core/memory-fence.ts +16 -9
  59. package/src/core/memory-recall.ts +168 -34
  60. package/src/core/path-rules.ts +143 -0
  61. package/src/core/section-parse.ts +16 -6
  62. package/src/core/typed-metadata.ts +68 -0
  63. package/src/core/wiki-link-syntax.ts +88 -0
  64. package/src/embed/backlog.ts +173 -60
  65. package/src/embed/batch.ts +83 -12
  66. package/src/embed/resume-cursor.ts +103 -0
  67. package/src/embed/retry.ts +41 -32
  68. package/src/embed/variant-backlog.ts +697 -63
  69. package/src/embed/variant-plan.ts +41 -45
  70. package/src/embed/variant-retry.ts +157 -44
  71. package/src/index.ts +3 -3
  72. package/src/ingestion/budget-error-codes.ts +13 -0
  73. package/src/ingestion/chunker.ts +60 -49
  74. package/src/ingestion/compiled-context.ts +4 -5
  75. package/src/ingestion/convert-file.ts +1 -1
  76. package/src/ingestion/document-metadata.ts +16 -9
  77. package/src/ingestion/excluded-ranges.ts +97 -0
  78. package/src/ingestion/file-processor.ts +122 -37
  79. package/src/ingestion/frontmatter.ts +35 -7
  80. package/src/ingestion/graph-reconciliation.ts +187 -51
  81. package/src/ingestion/language.ts +66 -61
  82. package/src/ingestion/position.ts +5 -5
  83. package/src/ingestion/prepare-file.ts +50 -29
  84. package/src/ingestion/record-adapter-canonical.ts +37 -26
  85. package/src/ingestion/record-adapter.ts +46 -26
  86. package/src/ingestion/record-container.ts +121 -53
  87. package/src/ingestion/record-path.ts +5 -2
  88. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  89. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  90. package/src/ingestion/source-availability/readers.ts +51 -0
  91. package/src/ingestion/strip.ts +39 -105
  92. package/src/ingestion/sync.ts +692 -386
  93. package/src/ingestion/typed-metadata.ts +10 -4
  94. package/src/ingestion/walker.ts +485 -158
  95. package/src/llm/cache.ts +128 -84
  96. package/src/llm/http-inference.ts +112 -35
  97. package/src/llm/http-policy.ts +101 -0
  98. package/src/llm/httpEmbedding.ts +8 -1
  99. package/src/llm/httpGeneration.ts +5 -1
  100. package/src/llm/httpRerank.ts +5 -1
  101. package/src/llm/inference-scope.ts +15 -2
  102. package/src/llm/lazy-ports.ts +33 -3
  103. package/src/llm/lockfile.ts +34 -7
  104. package/src/llm/model-cleanup.ts +24 -0
  105. package/src/llm/native-worker/client.ts +23 -12
  106. package/src/llm/native-worker/dispatcher.ts +19 -9
  107. package/src/llm/native-worker/embedding-identity.ts +42 -16
  108. package/src/llm/native-worker/entry.ts +2 -1
  109. package/src/llm/native-worker/owner.ts +1 -0
  110. package/src/llm/native-worker/ports.ts +86 -23
  111. package/src/llm/native-worker/protocol.ts +386 -55
  112. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  113. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  114. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  115. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  116. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  117. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  118. package/src/llm/types.ts +14 -0
  119. package/src/mcp/context.ts +342 -23
  120. package/src/mcp/http-transport.ts +21 -3
  121. package/src/mcp/tool-profile-types.ts +62 -0
  122. package/src/mcp/tool-profile.ts +32 -56
  123. package/src/mcp/tools/context.ts +5 -1
  124. package/src/mcp/tools/index.ts +269 -191
  125. package/src/mcp/tools/links.ts +7 -5
  126. package/src/mcp/tools/query.ts +60 -37
  127. package/src/mcp/tools/vsearch.ts +25 -14
  128. package/src/pipeline/answer.ts +133 -40
  129. package/src/pipeline/claim-verification.ts +293 -189
  130. package/src/pipeline/claim-verifier.ts +6 -7
  131. package/src/pipeline/egress-lineage.ts +37 -26
  132. package/src/pipeline/exclude.ts +34 -11
  133. package/src/pipeline/expansion.ts +233 -19
  134. package/src/pipeline/filters.ts +169 -33
  135. package/src/pipeline/graph-retrieval.ts +117 -61
  136. package/src/pipeline/hybrid.ts +598 -329
  137. package/src/pipeline/hydration.ts +86 -24
  138. package/src/pipeline/intent.ts +15 -7
  139. package/src/pipeline/owner-fusion.ts +61 -19
  140. package/src/pipeline/query-language.ts +15 -2
  141. package/src/pipeline/rerank.ts +15 -22
  142. package/src/pipeline/search.ts +193 -72
  143. package/src/pipeline/snippet.ts +15 -2
  144. package/src/pipeline/temporal.ts +51 -10
  145. package/src/pipeline/vsearch.ts +250 -152
  146. package/src/publish/attachment-raster.ts +2 -16
  147. package/src/publish/encrypted-export.ts +15 -5
  148. package/src/serve/browse-tree.ts +50 -42
  149. package/src/serve/connectors.ts +2 -1
  150. package/src/serve/context.ts +13 -4
  151. package/src/serve/doc-events.ts +3 -0
  152. package/src/serve/public/app.tsx +49 -21
  153. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  154. package/src/serve/public/components/CaptureModal.tsx +14 -10
  155. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  156. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  157. package/src/serve/public/globals.built.css +1 -1
  158. package/src/serve/public/globals.css +19 -0
  159. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  160. package/src/serve/public/lib/metadata-filter.ts +234 -9
  161. package/src/serve/public/pages/Browse.tsx +61 -27
  162. package/src/serve/public/pages/DocView.tsx +44 -25
  163. package/src/serve/public/pages/GraphView.tsx +8 -3
  164. package/src/serve/resident-runtime.ts +199 -48
  165. package/src/serve/routes/api.ts +98 -67
  166. package/src/serve/routes/links.ts +18 -4
  167. package/src/serve/server.ts +1370 -1180
  168. package/src/serve/spa-bundle-source.ts +52 -27
  169. package/src/serve/status.ts +101 -52
  170. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  171. package/src/serve/watch-reconciliation-shared.ts +42 -4
  172. package/src/serve/watch-reconciliation.ts +21 -8
  173. package/src/serve/watch-service-events.ts +7 -1
  174. package/src/serve/watch-service-hosts.ts +3 -1
  175. package/src/serve/watch-service.ts +46 -21
  176. package/src/serve/watch-snapshot-scan.ts +6 -15
  177. package/src/sessions/archive.ts +20 -8
  178. package/src/sessions/sanitize.ts +38 -18
  179. package/src/sessions/service.ts +180 -102
  180. package/src/store/migrations/036-vector-mirror-state.ts +83 -0
  181. package/src/store/migrations/037-performance-indexes.ts +56 -0
  182. package/src/store/migrations/index.ts +4 -0
  183. package/src/store/sqlite/adapter.ts +1217 -651
  184. package/src/store/sqlite/chunking-policy.ts +15 -1
  185. package/src/store/sqlite/eligibility.ts +110 -70
  186. package/src/store/sqlite/graph-neighbors.ts +71 -46
  187. package/src/store/sqlite/graph-reference-state.ts +27 -3
  188. package/src/store/sqlite/graph-similarity.ts +59 -12
  189. package/src/store/sqlite/metadata-predicate.ts +123 -28
  190. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  191. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  192. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  193. package/src/store/types.ts +32 -0
  194. package/src/store/vector/eligibility.ts +39 -0
  195. package/src/store/vector/lazy.ts +17 -0
  196. package/src/store/vector/partition-index.ts +49 -47
  197. package/src/store/vector/proof-cache.ts +103 -0
  198. package/src/store/vector/sqlite-vec.ts +230 -139
  199. package/src/store/vector/stats.ts +29 -73
  200. package/src/store/vector/status.ts +151 -52
  201. package/src/store/vector/stored-vectors.ts +131 -45
  202. package/src/store/vector/types.ts +10 -0
  203. package/src/store/vector/variant-search.ts +771 -109
  204. package/src/store/vector/variants.ts +785 -144
  205. package/browser-extension/artifacts/gno-browser-clipper-v2.14.0.zip.sha256 +0 -1
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Excluded-range types and binary-search lookup helpers.
3
+ * Extracted from src/ingestion/strip so link/attachment utilities do not pull
4
+ * in mdast/micromark parser packages at module load time.
5
+ *
6
+ * @module src/ingestion/excluded-ranges
7
+ */
8
+
9
+ export type ExcludedRangeKind =
10
+ | "frontmatter"
11
+ | "fenced_code"
12
+ | "indented_code"
13
+ | "inline_code"
14
+ | "html_comment";
15
+
16
+ export interface ExcludedRange {
17
+ /** String offset in original string (inclusive, UTF-16 code unit index) */
18
+ start: number;
19
+ /** String offset in original string (exclusive, UTF-16 code unit index) */
20
+ end: number;
21
+ /** Type of excluded region */
22
+ kind: ExcludedRangeKind;
23
+ }
24
+
25
+ /**
26
+ * Check if a string offset falls within any excluded range.
27
+ * Uses binary search for O(log n) lookup.
28
+ */
29
+ export function isExcluded(
30
+ offset: number,
31
+ excludedRanges: readonly ExcludedRange[]
32
+ ): boolean {
33
+ let left = 0;
34
+ let right = excludedRanges.length - 1;
35
+
36
+ while (left <= right) {
37
+ const mid = Math.floor((left + right) / 2);
38
+ const range = excludedRanges[mid];
39
+ if (range === undefined) return false;
40
+
41
+ if (offset < range.start) {
42
+ right = mid - 1;
43
+ } else if (offset >= range.end) {
44
+ left = mid + 1;
45
+ } else {
46
+ // offset is in [start, end)
47
+ return true;
48
+ }
49
+ }
50
+
51
+ return false;
52
+ }
53
+
54
+ /**
55
+ * Largest `end` among each prefix of a start-sorted range list, built once
56
+ * per list. Ranges can overlap (a comment around a code span), so a range
57
+ * list's ends are not sorted and the prefix maximum stands in for them.
58
+ */
59
+ const prefixMaxEnds = new WeakMap<readonly ExcludedRange[], Int32Array>();
60
+
61
+ const getPrefixMaxEnds = (ranges: readonly ExcludedRange[]): Int32Array => {
62
+ let maxEnds = prefixMaxEnds.get(ranges);
63
+ if (maxEnds?.length !== ranges.length) {
64
+ maxEnds = new Int32Array(ranges.length);
65
+ let maxEnd = -1;
66
+ for (const [index, range] of ranges.entries()) {
67
+ maxEnd = Math.max(maxEnd, range.end);
68
+ maxEnds[index] = maxEnd;
69
+ }
70
+ prefixMaxEnds.set(ranges, maxEnds);
71
+ }
72
+ return maxEnds;
73
+ };
74
+
75
+ /**
76
+ * Check if a range [start, end) intersects any excluded range.
77
+ * More precise than isExcluded for multi-character matches. Ranges must be
78
+ * sorted by start, as getExcludedRanges returns them; one lookup is a binary
79
+ * search, so checking every link of a large note stays linear.
80
+ */
81
+ export function rangeIntersectsExcluded(
82
+ start: number,
83
+ end: number,
84
+ excludedRanges: readonly ExcludedRange[]
85
+ ): boolean {
86
+ // Ranges starting before `end` form a prefix; one of them intersects
87
+ // [start, end) exactly when the largest end among them passes `start`.
88
+ let low = 0;
89
+ let high = excludedRanges.length;
90
+ while (low < high) {
91
+ const mid = (low + high) >>> 1;
92
+ if ((excludedRanges[mid]?.start ?? end) < end) low = mid + 1;
93
+ else high = mid;
94
+ }
95
+ if (low === 0) return false;
96
+ return (getPrefixMaxEnds(excludedRanges)[low - 1] ?? -1) > start;
97
+ }
@@ -80,6 +80,12 @@ export interface FileProcessorHooks {
80
80
  onPrevious: (structure: DocumentStructureSnapshot) => void;
81
81
  /** Called when the processor starts on the file (its clock starts). */
82
82
  onStarted?: () => void;
83
+ /**
84
+ * When true and running on the worker backend with an unshared full-buffer
85
+ * `request.input.bytes`, transfer the underlying `ArrayBuffer` instead of
86
+ * copying it. Callers must not read `request.input.bytes` afterward.
87
+ */
88
+ transferInputBytes?: boolean;
83
89
  }
84
90
 
85
91
  /** Posted once by a processor when it has loaded. */
@@ -107,11 +113,7 @@ export type FileProcessorBackendKind = "worker" | "child";
107
113
  /** Error code of a file whose message to or from the processor was lost. */
108
114
  export const PROCESSOR_MESSAGE_FAILED = "PROCESSOR_MESSAGE_FAILED";
109
115
 
110
- /** Error codes of a file stopped at its budget. */
111
- export const BUDGET_ERROR_CODES: ReadonlySet<string> = new Set([
112
- "TIMEOUT",
113
- "MEMORY_LIMIT",
114
- ]);
116
+ export { BUDGET_ERROR_CODES } from "./budget-error-codes";
115
117
 
116
118
  /** How often resident memory is sampled while a file is processed. */
117
119
  const MEMORY_SAMPLE_INTERVAL_MS = 200;
@@ -175,12 +177,19 @@ interface Processor {
175
177
  readonly kind: FileProcessorBackendKind;
176
178
  /** Settles once the processor has loaded and can take a file. */
177
179
  readonly ready: Promise<void>;
178
- /** Settles, with a reason, if the processor dies or errors. */
180
+ /** Settles, with a reason, if the processor dies or errors (startup only). */
179
181
  readonly failed: Promise<ProcessorFailure>;
182
+ /** Current failure if the processor has already died; null while alive. */
183
+ failure(): ProcessorFailure | null;
184
+ /** Replaceable single-slot failure listener for the currently running file. */
185
+ setOnFailed(handler: ((failure: ProcessorFailure) => void) | null): void;
186
+ /** Release per-file message and failure callbacks once a file settles. */
187
+ clearHandlers(): void;
180
188
  /** Send one file; its messages go to `onMessage`. */
181
189
  run(
182
190
  request: PrepareFileRequest,
183
- onMessage: (message: FileWorkerMessage) => void
191
+ onMessage: (message: FileWorkerMessage) => void,
192
+ transferInputBytes?: boolean
184
193
  ): void;
185
194
  /** Name of the running step, for overrun messages. */
186
195
  phase(): string;
@@ -204,6 +213,8 @@ function startWorker(): Processor {
204
213
  (worker as Worker & { unref(): void }).unref();
205
214
  const phaseSlot = new Int32Array(new SharedArrayBuffer(4));
206
215
  let onMessage: ((message: FileWorkerMessage) => void) | null = null;
216
+ let onFailed: ((failure: ProcessorFailure) => void) | null = null;
217
+ let failureState: ProcessorFailure | null = null;
207
218
  let markReady: () => void = () => undefined;
208
219
  let markFailed: (failure: ProcessorFailure) => void = () => undefined;
209
220
  let dead = false;
@@ -212,8 +223,14 @@ function startWorker(): Processor {
212
223
  });
213
224
  const failed = new Promise<ProcessorFailure>((resolve) => {
214
225
  markFailed = (failure) => {
226
+ if (dead) return;
215
227
  dead = true;
228
+ failureState = failure;
229
+ const failHandler = onFailed;
230
+ onFailed = null;
231
+ onMessage = null;
216
232
  resolve(failure);
233
+ failHandler?.(failure);
217
234
  };
218
235
  });
219
236
  worker.onmessage = (
@@ -242,11 +259,30 @@ function startWorker(): Processor {
242
259
  kind: "worker",
243
260
  ready,
244
261
  failed,
245
- run(request, messageHandler) {
262
+ failure: () => failureState,
263
+ setOnFailed(handler) {
264
+ onFailed = handler;
265
+ },
266
+ clearHandlers() {
267
+ onMessage = null;
268
+ onFailed = null;
269
+ },
270
+ run(request, messageHandler, transferInputBytes) {
246
271
  Atomics.store(phaseSlot, 0, -1);
247
272
  onMessage = messageHandler;
248
273
  const job: FileWorkerRequest = { request, phaseSlot };
249
- worker.postMessage(job);
274
+ const bytes = request.input.bytes;
275
+ if (
276
+ transferInputBytes &&
277
+ bytes.byteLength > 0 &&
278
+ bytes.buffer instanceof ArrayBuffer &&
279
+ bytes.byteOffset === 0 &&
280
+ bytes.byteLength === bytes.buffer.byteLength
281
+ ) {
282
+ worker.postMessage(job, [bytes.buffer]);
283
+ } else {
284
+ worker.postMessage(job);
285
+ }
250
286
  },
251
287
  phase: () => phaseName(Atomics.load(phaseSlot, 0)),
252
288
  externalRss: () => Promise.resolve(0),
@@ -288,6 +324,8 @@ function startChild(): Processor {
288
324
  const compiled = isBunfsPath(modulePath(import.meta));
289
325
  let phase = "startup";
290
326
  let onMessage: ((message: FileWorkerMessage) => void) | null = null;
327
+ let onFailed: ((failure: ProcessorFailure) => void) | null = null;
328
+ let failureState: ProcessorFailure | null = null;
291
329
  let markReady: () => void = () => undefined;
292
330
  let stopping = false;
293
331
  let exited = false;
@@ -317,23 +355,39 @@ function startChild(): Processor {
317
355
  const failed = child.exited.then((code): ProcessorFailure => {
318
356
  exited = true;
319
357
  liveChildren.delete(child);
320
- if (stopping) return { reason: "file processor was stopped" };
358
+ let failure: ProcessorFailure;
359
+ if (stopping) failure = { reason: "file processor was stopped" };
321
360
  // Bun closes the channel on both ends when either side receives a
322
361
  // message it cannot deserialize. The child exits cleanly only once its
323
362
  // channel is gone (file-child.ts), and a crash never exits cleanly; the
324
363
  // exit can be reported before Bun's own disconnect callback.
325
- if (code === 0) {
326
- return {
364
+ else if (code === 0) {
365
+ failure = {
327
366
  reason: "the IPC channel to the file processor child closed",
328
367
  delivery: "unknown",
329
368
  };
369
+ } else {
370
+ failure = { reason: `file processor child exited (${code})` };
330
371
  }
331
- return { reason: `file processor child exited (${code})` };
372
+ failureState = failure;
373
+ const failHandler = onFailed;
374
+ onFailed = null;
375
+ onMessage = null;
376
+ failHandler?.(failure);
377
+ return failure;
332
378
  });
333
379
  return {
334
380
  kind: "child",
335
381
  ready,
336
382
  failed,
383
+ failure: () => failureState,
384
+ setOnFailed(handler) {
385
+ onFailed = handler;
386
+ },
387
+ clearHandlers() {
388
+ onMessage = null;
389
+ onFailed = null;
390
+ },
337
391
  run(request, messageHandler) {
338
392
  phase = "startup";
339
393
  onMessage = messageHandler;
@@ -489,8 +543,20 @@ function acquireProcessor(): Processor {
489
543
  /** How long a new processor may take to load before the file fails closed. */
490
544
  const PROCESSOR_START_TIMEOUT_MS = 30_000;
491
545
 
546
+ /** Processors whose startup handshake already succeeded (zero per-file subscriptions). */
547
+ const readyProcessors = new WeakSet<Processor>();
548
+ /** Single shared startup race per processor while starting. */
549
+ const startupRaces = new WeakMap<Processor, Promise<string | null>>();
550
+
492
551
  /** Wait for the processor to load: null once ready, else why it did not. */
493
552
  const awaitReady = (active: Processor): Promise<string | null> => {
553
+ if (readyProcessors.has(active)) {
554
+ return Promise.resolve(null);
555
+ }
556
+ const existing = startupRaces.get(active);
557
+ if (existing) {
558
+ return existing;
559
+ }
494
560
  let timer: ReturnType<typeof setTimeout> | undefined;
495
561
  const timedOut = new Promise<string>((resolve) => {
496
562
  timer = setTimeout(
@@ -498,11 +564,19 @@ const awaitReady = (active: Processor): Promise<string | null> => {
498
564
  PROCESSOR_START_TIMEOUT_MS
499
565
  );
500
566
  });
501
- return Promise.race([
502
- active.ready.then(() => null),
567
+ const race = Promise.race([
568
+ active.ready.then(() => {
569
+ readyProcessors.add(active);
570
+ return null;
571
+ }),
503
572
  active.failed.then((failure) => failure.reason),
504
573
  timedOut,
505
- ]).finally(() => clearTimeout(timer));
574
+ ]).finally(() => {
575
+ clearTimeout(timer);
576
+ startupRaces.delete(active);
577
+ });
578
+ startupRaces.set(active, race);
579
+ return race;
506
580
  };
507
581
 
508
582
  /** Failure of a file whose message to or from the processor was lost. */
@@ -560,6 +634,7 @@ const runOne = async (
560
634
  settled = true;
561
635
  clearTimeout(deadline);
562
636
  clearInterval(sampler);
637
+ active.clearHandlers();
563
638
  if (keep && process.memoryUsage.rss() <= budget.maxMemoryBytes / 2) {
564
639
  idleTimer = setTimeout(stopProcessor, PROCESSOR_IDLE_MS);
565
640
  idleTimer.unref?.();
@@ -570,6 +645,23 @@ const runOne = async (
570
645
  }
571
646
  resolve(outcome);
572
647
  };
648
+ const handleFailure = (failure: ProcessorFailure): void => {
649
+ if (settled) return;
650
+ finish(
651
+ {
652
+ ok: false,
653
+ error: failure.delivery
654
+ ? undeliverableFailure(
655
+ request,
656
+ active.kind,
657
+ active.phase(),
658
+ failure
659
+ )
660
+ : { code: "INTERNAL", message: failure.reason },
661
+ },
662
+ false
663
+ );
664
+ };
573
665
  const deadline = setTimeout(() => {
574
666
  finish(
575
667
  {
@@ -601,23 +693,12 @@ const runOne = async (
601
693
  const sampler = setInterval(() => {
602
694
  void checkMemory();
603
695
  }, MEMORY_SAMPLE_INTERVAL_MS);
604
- void active.failed.then((failure) => {
605
- if (settled) return;
606
- finish(
607
- {
608
- ok: false,
609
- error: failure.delivery
610
- ? undeliverableFailure(
611
- request,
612
- active.kind,
613
- active.phase(),
614
- failure
615
- )
616
- : { code: "INTERNAL", message: failure.reason },
617
- },
618
- false
619
- );
620
- });
696
+ const alreadyFailed = active.failure();
697
+ if (alreadyFailed) {
698
+ handleFailure(alreadyFailed);
699
+ return;
700
+ }
701
+ active.setOnFailed(handleFailure);
621
702
  // A process already over the budget does not start another file.
622
703
  const rss = process.memoryUsage.rss();
623
704
  if (rss > budget.maxMemoryBytes) {
@@ -630,10 +711,14 @@ const runOne = async (
630
711
  );
631
712
  return;
632
713
  }
633
- active.run(request, (message) => {
634
- if (message.type === "previous") hooks.onPrevious(message.structure);
635
- else finish(message.outcome, true);
636
- });
714
+ active.run(
715
+ request,
716
+ (message) => {
717
+ if (message.type === "previous") hooks.onPrevious(message.structure);
718
+ else finish(message.outcome, true);
719
+ },
720
+ hooks.transferInputBytes
721
+ );
637
722
  });
638
723
  };
639
724
 
@@ -27,6 +27,14 @@ export interface FrontmatterResult {
27
27
  metadata: Record<string, unknown>;
28
28
  }
29
29
 
30
+ /** Detailed frontmatter parse result shared across single-pass preparation. */
31
+ export interface FrontmatterDetails extends FrontmatterResult {
32
+ /** Character offset where the body begins (0 if no YAML frontmatter). */
33
+ bodyStart: number;
34
+ /** Raw YAML block inside `---` delimiters, when present. */
35
+ rawYaml?: string;
36
+ }
37
+
30
38
  // ─────────────────────────────────────────────────────────────────────────────
31
39
  // Constants
32
40
  // ─────────────────────────────────────────────────────────────────────────────
@@ -283,31 +291,41 @@ function parseMetadataValue(
283
291
  return unquoteScalar(trimmed);
284
292
  }
285
293
 
294
+ function firstLines(source: string, maxLines: number): string {
295
+ let end = -1;
296
+ for (let i = 0; i < maxLines; i += 1) {
297
+ end = source.indexOf("\n", end + 1);
298
+ if (end === -1) return source;
299
+ }
300
+ return source.slice(0, end);
301
+ }
302
+
286
303
  /**
287
- * Parse frontmatter from markdown source.
288
- * Returns extracted tags and metadata.
304
+ * Parse frontmatter from markdown source, returning tags, metadata, body offset,
305
+ * and raw YAML block in a single regex scan.
289
306
  * Never throws - returns empty result on parse errors.
290
307
  */
291
- export function parseFrontmatter(source: string): FrontmatterResult {
292
- const result: FrontmatterResult = {
308
+ export function parseFrontmatterDetails(source: string): FrontmatterDetails {
309
+ const result: FrontmatterDetails = {
293
310
  tags: [],
294
311
  metadata: {},
312
+ bodyStart: 0,
295
313
  };
296
314
 
297
315
  const match = FRONTMATTER_REGEX.exec(source);
298
316
  if (!match) {
299
317
  // Check for Logseq-style properties at start of file (no --- delimiters)
300
- const logseqMatch = LOGSEQ_TAGS_REGEX.exec(
301
- source.split("\n").slice(0, 10).join("\n")
302
- );
318
+ const logseqMatch = LOGSEQ_TAGS_REGEX.exec(firstLines(source, 10));
303
319
  if (logseqMatch?.[1]) {
304
320
  result.tags = parseLogseqTags(logseqMatch[1]);
305
321
  }
306
322
  return result;
307
323
  }
308
324
 
325
+ result.bodyStart = match[0].length;
309
326
  const frontmatter = match[1];
310
327
  if (frontmatter === undefined) return result;
328
+ result.rawYaml = frontmatter;
311
329
 
312
330
  const lines = frontmatter.split("\n");
313
331
 
@@ -354,6 +372,16 @@ export function parseFrontmatter(source: string): FrontmatterResult {
354
372
  return result;
355
373
  }
356
374
 
375
+ /**
376
+ * Parse frontmatter from markdown source.
377
+ * Returns extracted tags and metadata.
378
+ * Never throws - returns empty result on parse errors.
379
+ */
380
+ export function parseFrontmatter(source: string): FrontmatterResult {
381
+ const { tags, metadata } = parseFrontmatterDetails(source);
382
+ return { tags, metadata };
383
+ }
384
+
357
385
  /**
358
386
  * Parse Logseq-style tags (space or comma separated).
359
387
  */