@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
@@ -10,6 +10,7 @@ import type { Database } from "bun:sqlite";
10
10
  // node:readline/promises is the platform line-input API; Bun has no equivalent
11
11
  import { createInterface } from "node:readline/promises";
12
12
 
13
+ import type { EmbedRunLimits } from "../../embed/backlog";
13
14
  import type { EmbeddingPort } from "../../llm/types";
14
15
  import type { StoreResult } from "../../store/types";
15
16
 
@@ -26,7 +27,15 @@ import {
26
27
  withCliWriteLease,
27
28
  } from "../../core/write-lease";
28
29
  import { embedBacklog, prepareEmbeddingBacklog } from "../../embed/backlog";
30
+ import { meterEmbeddingPort } from "../../embed/batch";
29
31
  import { getEmbeddingFingerprint } from "../../embed/fingerprint";
32
+ import {
33
+ compareChunkCursor,
34
+ isChunkCursor,
35
+ readResumeCursor,
36
+ resumeCursorKey,
37
+ writeResumeCursor,
38
+ } from "../../embed/resume-cursor";
30
39
  import {
31
40
  addUniqueSamples,
32
41
  chunkRetryKey,
@@ -55,7 +64,7 @@ import {
55
64
  type VectorIndexPort,
56
65
  type VectorStatsPort,
57
66
  } from "../../store/vector";
58
- import { getGlobals } from "../program";
67
+ import { getGlobals } from "../globals";
59
68
  import {
60
69
  createProgressRenderer,
61
70
  createThrottledProgressRenderer,
@@ -80,6 +89,10 @@ export interface EmbedOptions extends CliWriteLeaseOptions {
80
89
  force?: boolean;
81
90
  /** Show what would be done without embedding */
82
91
  dryRun?: boolean;
92
+ /** Stop after the batch that reaches this many attempted chunks */
93
+ maxChunks?: number;
94
+ /** Stop after the batch that reaches this many seconds of embedding */
95
+ maxSeconds?: number;
83
96
  /** Skip confirmation prompts (never confirms a separate vector partition) */
84
97
  yes?: boolean;
85
98
  /** Explicitly confirm building a separate vector partition */
@@ -111,6 +124,12 @@ export type EmbedResult = (
111
124
  errorSamples?: string[];
112
125
  suggestion?: string;
113
126
  syncError?: string;
127
+ /** Chunks still pending for the scope after this run (not set for dry runs). */
128
+ remaining?: number;
129
+ /** Set when `--max-chunks`/`--max-seconds` ended the run with work pending. */
130
+ stopped?: "limit";
131
+ /** The run ended early because the embedding runtime changed. */
132
+ incomplete?: boolean;
114
133
  }
115
134
  | { success: false; error: string; contention?: WriteLeaseContention }
116
135
  ) & {
@@ -161,6 +180,7 @@ interface BatchContext {
161
180
  recreateEmbedPort?: () => Promise<
162
181
  { ok: true; value: EmbeddingPort } | { ok: false; error: string }
163
182
  >;
183
+ limits?: EmbedRunLimits;
164
184
  }
165
185
 
166
186
  type BatchResult =
@@ -172,6 +192,7 @@ type BatchResult =
172
192
  duration: number;
173
193
  errorSamples: string[];
174
194
  suggestion?: string;
195
+ stopped?: "limit";
175
196
  }
176
197
  | { ok: false; error: string };
177
198
 
@@ -181,13 +202,36 @@ interface Cursor {
181
202
  }
182
203
 
183
204
  async function processBatches(ctx: BatchContext): Promise<BatchResult> {
184
- const startTime = Date.now();
205
+ // Monotonic: a wall-clock adjustment cannot shorten or negate the run.
206
+ const startTime = performance.now();
185
207
  let embedded = 0;
186
208
  let errors = 0;
187
209
  let contentionErrors = 0;
188
210
  const errorSamples: string[] = [];
189
211
  let suggestion: string | undefined;
190
212
  let cursor: Cursor | undefined;
213
+ let stopped: "limit" | undefined;
214
+ // Chunks charged against --max-chunks: every chunk submitted to the
215
+ // provider, so a disposed-port retry and adaptive recovery resubmissions
216
+ // count. Charged at batch boundaries, where the limit is checked.
217
+ let attempted = ctx.limits?.spent ?? 0;
218
+ let batchesStarted = 0;
219
+ const onSubmit = (texts: number): void => {
220
+ attempted += texts;
221
+ };
222
+ const limitReached = (): boolean =>
223
+ runLimitReached(ctx.limits, attempted, startTime);
224
+ const resumeKey = resumeCursorKey(
225
+ `legacy:${ctx.force ? "force:" : ""}${ctx.modelUri}`,
226
+ ctx.collection
227
+ );
228
+ // A bounded run resumes after the previous slice and wraps to the start,
229
+ // so chunks that keep failing stay pending without blocking later ones.
230
+ const resumeFrom = ctx.limits
231
+ ? readResumeCursor(ctx.db, resumeKey, isChunkCursor)
232
+ : undefined;
233
+ let wrapped = !resumeFrom;
234
+ cursor = resumeFrom;
191
235
  const retryQueue = new Map<string, { item: BacklogItem; attempts: number }>();
192
236
  const embedFingerprint = getEmbeddingFingerprint({
193
237
  modelUri: ctx.modelUri,
@@ -238,6 +282,7 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
238
282
  items: batch,
239
283
  modelUri: ctx.modelUri,
240
284
  embedFingerprint,
285
+ onSubmit,
241
286
  });
242
287
 
243
288
  if (
@@ -260,6 +305,7 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
260
305
  items: batch,
261
306
  modelUri: ctx.modelUri,
262
307
  embedFingerprint,
308
+ onSubmit,
263
309
  });
264
310
  if (ctx.verbose && result.embedded > 0) {
265
311
  process.stderr.write("\n[embed] Retry after port reset succeeded\n");
@@ -277,7 +323,7 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
277
323
  const embeddedDisplay = Math.min(embedded, ctx.totalToEmbed);
278
324
  const completed = Math.min(embedded + errors, ctx.totalToEmbed);
279
325
  const pct = (completed / ctx.totalToEmbed) * 100;
280
- const elapsed = (Date.now() - startTime) / 1000;
326
+ const elapsed = (performance.now() - startTime) / 1000;
281
327
  const rate = embedded / Math.max(elapsed, 0.001);
282
328
  const eta =
283
329
  Math.max(0, ctx.totalToEmbed - completed) / Math.max(rate, 0.001);
@@ -295,6 +341,8 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
295
341
  (entry) => entry.attempts < MAX_EMBED_CHUNK_ATTEMPTS
296
342
  );
297
343
  for (let idx = 0; idx < entries.length; idx += ctx.batchSize) {
344
+ // Retries count against the run limits; the rest stay queued.
345
+ if (limitReached()) break;
298
346
  const slice = entries.slice(idx, idx + ctx.batchSize);
299
347
  for (const entry of slice) {
300
348
  retryQueue.delete(chunkRetryKey(entry.item));
@@ -335,7 +383,7 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
335
383
 
336
384
  while (embedded + errors < ctx.totalToEmbed) {
337
385
  // Get next batch using seek pagination (cursor-based)
338
- const batchResult = ctx.force
386
+ const fetched = ctx.force
339
387
  ? await getActiveChunks(ctx.db, ctx.batchSize, cursor, ctx.collection)
340
388
  : await ctx.stats.getBacklog(ctx.modelUri, embedFingerprint, {
341
389
  limit: ctx.batchSize,
@@ -343,14 +391,34 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
343
391
  collection: ctx.collection,
344
392
  });
345
393
 
346
- if (!batchResult.ok) {
347
- return { ok: false, error: batchResult.error.message };
394
+ if (!fetched.ok) {
395
+ return { ok: false, error: fetched.error.message };
348
396
  }
349
397
 
350
- const batch = batchResult.value;
398
+ // After wrapping, a bounded run stops where it started.
399
+ const batch =
400
+ wrapped && resumeFrom
401
+ ? fetched.value.filter(
402
+ (item) => compareChunkCursor(item, resumeFrom) <= 0
403
+ )
404
+ : fetched.value;
351
405
  if (batch.length === 0) {
406
+ if (wrapped) break;
407
+ wrapped = true;
408
+ cursor = undefined;
409
+ continue;
410
+ }
411
+
412
+ // Time can run out while the batch is fetched: stop before inference,
413
+ // keeping this batch eligible for the next run (the cursor stays put).
414
+ // Every run processes at least one batch, even one that submits nothing
415
+ // or follows a runtime verification that spent the budget, so bounded
416
+ // runs always progress.
417
+ if (batchesStarted > 0 && limitReached()) {
418
+ stopped = "limit";
352
419
  break;
353
420
  }
421
+ batchesStarted += 1;
354
422
 
355
423
  // Advance cursor to last item (even on failure, to avoid infinite loops)
356
424
  const lastItem = batch.at(-1);
@@ -368,14 +436,51 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
368
436
  contentionErrors += batchStoreResult.contentionErrors;
369
437
  enqueueRetryItems(batchStoreResult.retryItems, 1);
370
438
 
371
- if (embedded > beforeEmbedded) {
439
+ if (embedded > beforeEmbedded && !limitReached()) {
372
440
  await drainRetryQueue();
373
441
  }
374
442
 
375
443
  renderProgress();
444
+
445
+ if (embedded + errors < ctx.totalToEmbed && limitReached()) {
446
+ stopped = "limit";
447
+ break;
448
+ }
376
449
  }
377
450
 
378
- await drainRetryQueue();
451
+ if (!stopped) {
452
+ await drainRetryQueue();
453
+ // The limit can be reached by the last batch or the final retry drain.
454
+ // It ended the run with work pending when chunks are still queued for a
455
+ // retry or, for a non-forced run, still in the backlog (including
456
+ // chunks that used every attempt).
457
+ if (limitReached()) {
458
+ const queued = [...retryQueue.values()].some(
459
+ (entry) => entry.attempts < MAX_EMBED_CHUNK_ATTEMPTS
460
+ );
461
+ // Under the CLI write lease the starting backlog minus what was
462
+ // embedded is exact (chunks that failed stay pending).
463
+ const pending = queued || (!ctx.force && ctx.totalToEmbed - embedded > 0);
464
+ if (pending) stopped = "limit";
465
+ }
466
+ }
467
+ if (stopped) {
468
+ // Queued retries stay pending for the next run instead of spending more
469
+ // than the limit; they are counted in `remaining`, not as failures.
470
+ // Retries that used every attempt remain failures.
471
+ for (const [key, entry] of retryQueue)
472
+ if (entry.attempts < MAX_EMBED_CHUNK_ATTEMPTS) retryQueue.delete(key);
473
+ }
474
+
475
+ // Bounded runs continue after this slice next time; a finished traversal
476
+ // leaves nothing to resume.
477
+ try {
478
+ if (stopped) writeResumeCursor(ctx.db, resumeKey, cursor);
479
+ else if (readResumeCursor(ctx.db, resumeKey, isChunkCursor))
480
+ writeResumeCursor(ctx.db, resumeKey, undefined);
481
+ } catch {
482
+ // Advisory: a busy database must not fail a finished slice.
483
+ }
379
484
 
380
485
  if (retryQueue.size > 0) {
381
486
  errors += retryQueue.size;
@@ -394,12 +499,78 @@ async function processBatches(ctx: BatchContext): Promise<BatchResult> {
394
499
  embedded,
395
500
  errors,
396
501
  contentionErrors,
397
- duration: (Date.now() - startTime) / 1000,
502
+ duration: (performance.now() - startTime) / 1000,
398
503
  errorSamples,
399
504
  suggestion,
505
+ stopped,
400
506
  };
401
507
  }
402
508
 
509
+ function getSchemaMeta(db: Database, key: string): string | undefined {
510
+ try {
511
+ return (
512
+ db
513
+ .query<{ value: string }, [string]>(
514
+ "SELECT value FROM schema_meta WHERE key = ?"
515
+ )
516
+ .get(key)?.value ?? undefined
517
+ );
518
+ } catch {
519
+ return undefined;
520
+ }
521
+ }
522
+
523
+ function setSchemaMeta(
524
+ db: Database,
525
+ key: string,
526
+ value: string | undefined
527
+ ): void {
528
+ if (value === undefined) {
529
+ db.run("DELETE FROM schema_meta WHERE key = ?", [key]);
530
+ return;
531
+ }
532
+ db.run(
533
+ `INSERT INTO schema_meta (key, value, updated_at) VALUES (?, ?, datetime('now'))
534
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
535
+ [key, value]
536
+ );
537
+ }
538
+
539
+ /**
540
+ * Record the embed stage as finished. One attempt: the connection's busy
541
+ * timeout already waits for other writers, and retrying would hold the
542
+ * receipt and the write lease for several timeouts. Never throws: the receipt
543
+ * of a run that already committed its batches must survive a marker that
544
+ * cannot be written. A marker left `running` makes the next run print a
545
+ * resume note and continue from the committed vectors; it gates nothing.
546
+ */
547
+ export function finishEmbedStageMarker(
548
+ db: Database,
549
+ outcome: "completed" | "failed",
550
+ write: typeof markIndexStageFinished = markIndexStageFinished
551
+ ): boolean {
552
+ try {
553
+ write(db, "embed", outcome);
554
+ return true;
555
+ } catch {
556
+ return false;
557
+ }
558
+ }
559
+
560
+ /** A bounded run stops at the first batch boundary at or past either limit. */
561
+ function runLimitReached(
562
+ limits: EmbedRunLimits | undefined,
563
+ attempted: number,
564
+ startedAtMs: number
565
+ ): boolean {
566
+ if (!limits) return false;
567
+ return (
568
+ (limits.maxChunks !== undefined && attempted >= limits.maxChunks) ||
569
+ (limits.maxSeconds !== undefined &&
570
+ (performance.now() - startedAtMs) / 1000 >= limits.maxSeconds)
571
+ );
572
+ }
573
+
403
574
  // ─────────────────────────────────────────────────────────────────────────────
404
575
  // Helpers
405
576
  // ─────────────────────────────────────────────────────────────────────────────
@@ -481,9 +652,13 @@ async function confirmSeparatePartition(message: string): Promise<boolean> {
481
652
  * Execute gno embed command.
482
653
  */
483
654
  export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
484
- const batchSize = options.batchSize ?? 32;
655
+ const batchSize = options.batchSize ?? 64;
485
656
  const force = options.force ?? false;
486
657
  const dryRun = options.dryRun ?? false;
658
+ const limits: EmbedRunLimits | undefined =
659
+ options.maxChunks !== undefined || options.maxSeconds !== undefined
660
+ ? { maxChunks: options.maxChunks, maxSeconds: options.maxSeconds }
661
+ : undefined;
487
662
 
488
663
  return await withCliWriteLease(options, async () => {
489
664
  // Initialize config and store
@@ -596,10 +771,44 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
596
771
  return { success: false, error: vectorResult.error.message };
597
772
  }
598
773
  vectorIndex = vectorResult.value;
599
-
774
+ // A bounded legacy run that skipped its vec index sync leaves this
775
+ // marker; the next run that is not stopped by a limit syncs.
776
+ const vecSyncOwedKey = `embed_vec_sync_owed:${modelUri}`;
777
+ const vecSyncOwed =
778
+ !dryRun && getSchemaMeta(db, vecSyncOwedKey) === "1";
779
+ /** Performs a deferred sync; returns its error, keeping the marker. */
780
+ const settleOwedVecSync = async (): Promise<string | undefined> => {
781
+ if (!vecSyncOwed || !vectorIndex) return undefined;
782
+ const synced = await vectorIndex.syncVecIndex();
783
+ if (!synced.ok) return synced.error.message;
784
+ // Without sqlite-vec the sync is a no-op; keep the marker for a
785
+ // run that can repair the vector index.
786
+ if (vectorIndex.searchAvailable)
787
+ setSchemaMeta(db, vecSyncOwedKey, undefined);
788
+ return undefined;
789
+ };
790
+ const owedSyncFields = (error: string | undefined) =>
791
+ error
792
+ ? {
793
+ syncError: error,
794
+ suggestion:
795
+ "Vector index sync failed. Rerun `gno embed` once more. If it repeats, run `gno vec sync`.",
796
+ }
797
+ : {};
798
+
799
+ // Runtime verification during preparation can re-embed stored chunks;
800
+ // a bounded run charges those requests against --max-chunks too.
801
+ // Verification is not interrupted midway (the run needs a resolved
802
+ // partition): it is at most one sample per stored partition, and the
803
+ // verdict is cached, so it happens once per runtime (again only if
804
+ // that cache write failed).
805
+ let verificationSpent = 0;
806
+ const verification = meterEmbeddingPort(embedPort, (texts) => {
807
+ verificationSpent += texts;
808
+ });
600
809
  const backlogDeps = {
601
810
  statsPort: stats,
602
- embedPort,
811
+ embedPort: verification.port,
603
812
  vectorIndex,
604
813
  modelUri,
605
814
  collection: options.collection,
@@ -621,11 +830,13 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
621
830
  ...backlogDeps,
622
831
  allowNewPartition: true,
623
832
  });
833
+ verification.meter.active = false;
624
834
  if (!prepared.ok)
625
835
  return { success: false, error: prepared.error.message };
836
+ const runLimits = limits && { ...limits, spent: verificationSpent };
626
837
  if (prepared.value.variantStore) {
627
838
  totalToEmbed = countVariantBacklog(prepared.value);
628
- const startedAt = Date.now();
839
+ const startedAt = performance.now();
629
840
  if (dryRun)
630
841
  return {
631
842
  success: true,
@@ -639,6 +850,10 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
639
850
  };
640
851
  const processed = await embedBacklog({
641
852
  ...prepared.value,
853
+ limits: runLimits && {
854
+ ...runLimits,
855
+ pendingAtStart: totalToEmbed,
856
+ },
642
857
  onProgress: !options.json
643
858
  ? (embedded, errors) =>
644
859
  process.stderr.write(
@@ -649,22 +864,49 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
649
864
  if (!options.json) process.stderr.write("\n");
650
865
  if (!processed.ok)
651
866
  return { success: false, error: processed.error.message };
867
+ const { stopped } = processed.value;
868
+ // Recount only when work can be left: a limit stop, failures,
869
+ // contention, deferral or a runtime change. The count is the real
870
+ // pending backlog, also after `--force` (whose failed re-embeds
871
+ // keep their previous vector).
872
+ const leftWork =
873
+ stopped ||
874
+ processed.value.errors ||
875
+ processed.value.contentionErrors ||
876
+ processed.value.deferred ||
877
+ processed.value.incomplete;
878
+ // Under the CLI write lease nothing else changes the backlog, so a
879
+ // non-forced run leaves the starting backlog minus what it embedded
880
+ // (failed or discarded owners stay pending), with no further pass.
881
+ // A forced run recounts the real backlog when it may have left work.
882
+ let remaining = 0;
883
+ if (!force)
884
+ remaining = Math.max(0, totalToEmbed - processed.value.embedded);
885
+ else if (leftWork)
886
+ remaining = countVariantBacklog({
887
+ ...prepared.value,
888
+ force: false,
889
+ });
652
890
  return {
653
891
  success: true,
654
892
  ...processed.value,
655
893
  contentionErrors: processed.value.contentionErrors ?? 0,
656
- duration: (Date.now() - startedAt) / 1000,
894
+ duration: (performance.now() - startedAt) / 1000,
657
895
  model: modelUri,
658
896
  searchAvailable: prepared.value.variantStore.searchAvailable,
659
897
  errorSamples: [],
898
+ remaining,
660
899
  };
661
900
  }
662
901
  if (force) {
663
902
  const count = await getActiveChunkCount(db, options.collection);
664
903
  if (!count.ok) return { success: false, error: count.error.message };
665
904
  totalToEmbed = count.value;
905
+ const owedError =
906
+ !dryRun && !totalToEmbed ? await settleOwedVecSync() : undefined;
666
907
  if (dryRun || !totalToEmbed)
667
908
  return {
909
+ ...owedSyncFields(owedError),
668
910
  success: true,
669
911
  embedded: totalToEmbed,
670
912
  errors: 0,
@@ -673,6 +915,7 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
673
915
  model: modelUri,
674
916
  searchAvailable: vectorIndex.searchAvailable,
675
917
  errorSamples: [],
918
+ ...(dryRun ? {} : { remaining: 0 }),
676
919
  };
677
920
  }
678
921
 
@@ -696,7 +939,9 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
696
939
  totalToEmbed = backlogResult.value;
697
940
 
698
941
  if (totalToEmbed === 0 || dryRun) {
942
+ const owedError = dryRun ? undefined : await settleOwedVecSync();
699
943
  return {
944
+ ...owedSyncFields(owedError),
700
945
  success: true,
701
946
  embedded: totalToEmbed,
702
947
  errors: 0,
@@ -705,6 +950,7 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
705
950
  model: modelUri,
706
951
  searchAvailable: vectorIndex.searchAvailable,
707
952
  errorSamples: [],
953
+ ...(dryRun ? {} : { remaining: 0 }),
708
954
  };
709
955
  }
710
956
  }
@@ -723,14 +969,61 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
723
969
  totalToEmbed,
724
970
  verbose: options.verbose ?? false,
725
971
  recreateEmbedPort,
972
+ limits: runLimits,
726
973
  });
727
974
 
728
975
  if (!result.ok) {
729
976
  return { success: false, error: result.error };
730
977
  }
978
+ const legacyRemaining = async (): Promise<number> => {
979
+ // Under the CLI write lease: the starting backlog minus what this
980
+ // run embedded (failed chunks stay pending).
981
+ if (!force) return Math.max(0, totalToEmbed - result.embedded);
982
+ if (!result.stopped && !result.errors && !result.contentionErrors)
983
+ return 0;
984
+ // The real pending backlog, also after `--force`.
985
+ const recount = await stats.countBacklog(
986
+ modelUri,
987
+ getEmbeddingFingerprint({ modelUri, dimensions }),
988
+ { collection: options.collection }
989
+ );
990
+ return recount.ok
991
+ ? recount.value
992
+ : Math.max(0, totalToEmbed - result.embedded);
993
+ };
994
+ const stoppedFields = {
995
+ remaining: await legacyRemaining(),
996
+ ...(result.stopped ? { stopped: result.stopped } : {}),
997
+ };
731
998
 
732
- // Sync vec index if any vec0 writes failed (matches embedBacklog behavior)
733
- if (vectorIndex.vecDirty) {
999
+ // A bounded run that stopped at its limit does not start a
1000
+ // model-wide vec index scan while holding the lease; it records that
1001
+ // a sync is owed, and the next run that is not stopped performs it.
1002
+ if (result.stopped && (vectorIndex.vecDirty || vecSyncOwed)) {
1003
+ if (vectorIndex.vecDirty)
1004
+ try {
1005
+ setSchemaMeta(db, vecSyncOwedKey, "1");
1006
+ } catch {
1007
+ // The suggestion below still tells the user to sync.
1008
+ }
1009
+ return {
1010
+ success: true,
1011
+ embedded: result.embedded,
1012
+ errors: result.errors,
1013
+ contentionErrors: result.contentionErrors,
1014
+ duration: result.duration,
1015
+ model: modelUri,
1016
+ searchAvailable: vectorIndex.searchAvailable,
1017
+ errorSamples: result.errorSamples,
1018
+ suggestion:
1019
+ "Some vector index writes failed. Run `gno vec sync` (a bounded run does not sync the vector index).",
1020
+ ...stoppedFields,
1021
+ };
1022
+ }
1023
+
1024
+ // Sync vec index if any vec0 writes failed (matches embedBacklog
1025
+ // behavior), or if an earlier bounded run deferred its sync.
1026
+ if (vectorIndex.vecDirty || vecSyncOwed) {
734
1027
  const syncResult = await vectorIndex.syncVecIndex();
735
1028
  if (syncResult.ok) {
736
1029
  const { added, removed } = syncResult.value;
@@ -742,6 +1035,8 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
742
1035
  }
743
1036
  }
744
1037
  vectorIndex.vecDirty = false;
1038
+ if (vecSyncOwed && vectorIndex.searchAvailable)
1039
+ setSchemaMeta(db, vecSyncOwedKey, undefined);
745
1040
  } else {
746
1041
  if (!options.json) {
747
1042
  process.stdout.write(
@@ -763,6 +1058,7 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
763
1058
  suggestion:
764
1059
  "Vector index sync failed after embedding. Rerun `gno embed` once more. If it repeats, run `gno vec sync`.",
765
1060
  syncError: syncResult.error.message,
1061
+ ...stoppedFields,
766
1062
  };
767
1063
  }
768
1064
  }
@@ -777,6 +1073,7 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
777
1073
  searchAvailable: vectorIndex.searchAvailable,
778
1074
  errorSamples: result.errorSamples,
779
1075
  suggestion: result.suggestion,
1076
+ ...stoppedFields,
780
1077
  };
781
1078
  };
782
1079
 
@@ -797,8 +1094,13 @@ export async function embed(options: EmbedOptions = {}): Promise<EmbedResult> {
797
1094
  outcome = embedStageOutcome(result);
798
1095
  return { ...result, resumedFrom };
799
1096
  } finally {
800
- markIndexStageFinished(db, "embed", outcome);
801
- await store.close();
1097
+ // The stage marker is advisory resume metadata: a database still busy
1098
+ // after the run must not discard its receipt or leave the store open.
1099
+ try {
1100
+ finishEmbedStageMarker(db, outcome);
1101
+ } finally {
1102
+ await store.close();
1103
+ }
802
1104
  }
803
1105
  });
804
1106
  }
@@ -922,6 +1224,9 @@ export function formatEmbed(
922
1224
  errorSamples: result.errorSamples ?? [],
923
1225
  suggestion: result.suggestion,
924
1226
  syncError: result.syncError,
1227
+ remaining: result.remaining,
1228
+ stopped: result.stopped,
1229
+ incomplete: result.incomplete || undefined,
925
1230
  },
926
1231
  null,
927
1232
  2
@@ -935,7 +1240,10 @@ export function formatEmbed(
935
1240
  if (
936
1241
  result.embedded === 0 &&
937
1242
  result.errors === 0 &&
938
- result.contentionErrors === 0
1243
+ result.contentionErrors === 0 &&
1244
+ !result.stopped &&
1245
+ !result.incomplete &&
1246
+ !result.syncError
939
1247
  ) {
940
1248
  return "No chunks need embedding. All up to date.";
941
1249
  }
@@ -944,6 +1252,19 @@ export function formatEmbed(
944
1252
  lines.push(
945
1253
  `Embedded ${result.embedded.toLocaleString()} chunks in ${formatDuration(result.duration)}`
946
1254
  );
1255
+ if (result.incomplete) {
1256
+ lines.push(
1257
+ `Stopped early because the embedding runtime changed; ${(result.remaining ?? 0).toLocaleString()} chunks remaining. Run \`gno embed\` again to continue.`
1258
+ );
1259
+ }
1260
+ if (result.errors === 0 && result.suggestion) {
1261
+ lines.push(`Hint: ${result.suggestion}`);
1262
+ }
1263
+ if (result.stopped === "limit") {
1264
+ lines.push(
1265
+ `Stopped at the run limit; ${(result.remaining ?? 0).toLocaleString()} chunks remaining. Run \`gno embed\` again to continue.`
1266
+ );
1267
+ }
947
1268
 
948
1269
  if (result.errors > 0) {
949
1270
  lines.push(`${result.errors} chunks failed to embed.`);
@@ -5,7 +5,7 @@
5
5
  * @module src/cli/commands/links
6
6
  */
7
7
 
8
- import type { DocEdgeRow, DocLinkRow, StorePort } from "../../store/types";
8
+ import type { DocEdgeRow, DocLinkRow } from "../../store/types";
9
9
 
10
10
  import { resolveDocRef } from "../../core/ref-parser";
11
11
  import { initStore } from "./shared";
@@ -9,9 +9,9 @@ import { getConfigPaths, toAbsolutePath } from "../../../config/paths.js";
9
9
  import {
10
10
  type McpToolProfile,
11
11
  parseMcpToolProfile,
12
- } from "../../../mcp/tool-profile.js";
12
+ } from "../../../mcp/tool-profile-types.js";
13
13
  import { CliError } from "../../errors.js";
14
- import { getGlobals } from "../../program.js";
14
+ import { getGlobals } from "../../globals.js";
15
15
  import { resolveMcpConfigLocation } from "./config-discovery.js";
16
16
  import {
17
17
  getJsoncServerEntry,
@@ -11,7 +11,7 @@ import type { StandardMcpEntry } from "./config.js";
11
11
 
12
12
  import { normalizeConnectorWorkspaceEnvironment } from "../../../core/connector-environment";
13
13
  import { CliError } from "../../errors.js";
14
- import { getGlobals } from "../../program.js";
14
+ import { getGlobals } from "../../globals.js";
15
15
  import {
16
16
  configPathEntryExists,
17
17
  resolveMcpConfigLocation,
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { CliError } from "../../errors.js";
8
- import { getGlobals } from "../../program.js";
8
+ import { getGlobals } from "../../globals.js";
9
9
  import { resolveMcpConfigLocation } from "./config-discovery.js";
10
10
  import {
11
11
  removeJsoncServerEntry,
@@ -39,7 +39,7 @@ import {
39
39
  type VectorIndexPort,
40
40
  } from "../../store/vector";
41
41
  import { VECTOR_RUNTIME_INCOMPATIBLE } from "../../store/vector/variant-search";
42
- import { getGlobals } from "../program";
42
+ import { getGlobals } from "../globals";
43
43
  import {
44
44
  createProgressRenderer,
45
45
  createThrottledProgressRenderer,