@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
@@ -17,15 +17,15 @@ import {
17
17
  import {
18
18
  getConfigPaths,
19
19
  isInitialized,
20
- loadConfig,
21
20
  writeConfigWarningsToStderr,
22
21
  } from "../../config";
23
22
  import { tracePhase } from "../../core/phase-trace";
24
- import { BUDGET_ERROR_CODES } from "../../ingestion/file-processor";
23
+ import { BUDGET_ERROR_CODES } from "../../ingestion/budget-error-codes";
25
24
  import {
26
25
  SqliteAdapter,
27
26
  staleCollectionsMessage,
28
27
  } from "../../store/sqlite/adapter";
28
+ import { loadConfigCached } from "../config-cache";
29
29
  import { assertCliSessionBinding } from "../session-binding";
30
30
 
31
31
  /**
@@ -78,8 +78,8 @@ export async function initStore(
78
78
  return { ok: false, error: "GNO not initialized. Run: gno init" };
79
79
  }
80
80
 
81
- // Load config
82
- const configResult = await loadConfig(options.configPath);
81
+ // Load config (reused within the same CLI invocation when unchanged)
82
+ const configResult = await loadConfigCached(options.configPath);
83
83
  if (!configResult.ok) {
84
84
  return { ok: false, error: configResult.error.message };
85
85
  }
@@ -10,7 +10,7 @@ import { dirname, join } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
 
12
12
  import { CliError } from "../../errors.js";
13
- import { getGlobals } from "../../program.js";
13
+ import { getGlobals } from "../../globals.js";
14
14
  import {
15
15
  resolveSkillPaths,
16
16
  SKILL_TARGETS,
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { join } from "node:path";
9
9
 
10
- import { getGlobals } from "../../program.js";
10
+ import { getGlobals } from "../../globals.js";
11
11
  import { resolveAllPaths, type SkillScope, type SkillTarget } from "./paths.js";
12
12
 
13
13
  // ─────────────────────────────────────────────────────────────────────────────
@@ -9,7 +9,7 @@ import { rm } from "node:fs/promises";
9
9
  import { join } from "node:path";
10
10
 
11
11
  import { CliError } from "../../errors.js";
12
- import { getGlobals } from "../../program.js";
12
+ import { getGlobals } from "../../globals.js";
13
13
  import {
14
14
  resolveSkillPaths,
15
15
  SKILL_TARGETS,
@@ -16,7 +16,6 @@ import {
16
16
  buildContentTypeBoostStatus,
17
17
  getConfigPaths,
18
18
  isInitialized,
19
- loadConfig,
20
19
  } from "../../config";
21
20
  import {
22
21
  describeConnectorSummary,
@@ -32,7 +31,7 @@ import {
32
31
  formatMemoryStatusLines,
33
32
  } from "../../core/memory-diagnostics";
34
33
  import { formatVectorPartitionLines } from "../../core/vector-partition-status";
35
- import { BUDGET_ERROR_CODES } from "../../ingestion/file-processor";
34
+ import { BUDGET_ERROR_CODES } from "../../ingestion/budget-error-codes";
36
35
  import {
37
36
  checkCollectionRoots,
38
37
  type CollectionRootError,
@@ -42,6 +41,7 @@ import { getActivePreset, resolveModelUri } from "../../llm/registry";
42
41
  import { getConnectorVerificationTargets } from "../../serve/connectors";
43
42
  import { createStandaloneResidentStatus } from "../../serve/resident-status";
44
43
  import { SqliteAdapter } from "../../store/sqlite/adapter";
44
+ import { loadConfigCached } from "../config-cache";
45
45
  import {
46
46
  formatBackgroundIssue,
47
47
  residentIssues,
@@ -115,37 +115,19 @@ const STALE_COLLECTIONS_HINT =
115
115
  const BUDGET_STOP_SCAN_LIMIT = 100;
116
116
  /** Most budget stops listed in status output. */
117
117
  const MAX_BUDGET_STOPS = 10;
118
+ const BUDGET_ERROR_CODE_LIST = Array.from(BUDGET_ERROR_CODES);
118
119
 
119
120
  /**
120
121
  * Files whose latest indexing attempt stopped at the conversion budget, from
121
122
  * the recent error log, kept only while the document still carries that code.
122
123
  */
123
124
  async function collectBudgetStops(store: SqliteAdapter): Promise<BudgetStop[]> {
124
- const recent = await store.getRecentErrors(BUDGET_STOP_SCAN_LIMIT);
125
- if (!recent.ok) return [];
126
- const stops: BudgetStop[] = [];
127
- const seen = new Set<string>();
128
- for (const row of recent.value) {
129
- const key = `${row.collection}\u0000${row.relPath}`;
130
- if (seen.has(key)) continue;
131
- seen.add(key);
132
- if (!BUDGET_ERROR_CODES.has(row.code)) continue;
133
- const document = await store.getDocument(row.collection, row.relPath);
134
- if (
135
- document.ok &&
136
- document.value?.active &&
137
- document.value.lastErrorCode === row.code
138
- ) {
139
- stops.push({
140
- collection: row.collection,
141
- relPath: row.relPath,
142
- code: row.code,
143
- message: row.message,
144
- });
145
- if (stops.length >= MAX_BUDGET_STOPS) break;
146
- }
147
- }
148
- return stops;
125
+ const stops = await store.getRecentBudgetStops(
126
+ BUDGET_ERROR_CODE_LIST,
127
+ BUDGET_STOP_SCAN_LIMIT,
128
+ MAX_BUDGET_STOPS
129
+ );
130
+ return stops.ok ? stops.value : [];
149
131
  }
150
132
 
151
133
  /** A background issue reported by (or about) a running detached resident. */
@@ -423,13 +405,22 @@ export async function status(
423
405
  }
424
406
 
425
407
  // Load config
426
- const configResult = await loadConfig(options.configPath);
408
+ const configResult = await loadConfigCached(options.configPath);
427
409
  if (!configResult.ok) {
428
410
  return { success: false, error: configResult.error.message };
429
411
  }
430
412
  const config = configResult.value;
431
- // Read-time root check, overlapping the index reads below; it never rejects.
432
- const rootErrors = checkCollectionRoots(config.collections);
413
+ const collectionNames = config.collections.map(({ name }) => name);
414
+ const preset = getActivePreset(config);
415
+ // Launch filesystem/process probes in parallel with index open + SQLite reads.
416
+ const rootErrorsPromise = checkCollectionRoots(config.collections);
417
+ const embedModelCachedPromise = new ModelCache(getModelsCachePath()).isCached(
418
+ preset.embed
419
+ );
420
+ const connectorTargetsPromise = getConnectorVerificationTargets();
421
+ const backgroundIssuesPromise = collectResidentIssues();
422
+ const registrationRuntimeIssuesPromise = checkRegistrationRuntimes();
423
+ const residentRuntimeIssuesPromise = checkResidentRuntimes();
433
424
 
434
425
  // Open database
435
426
  const store = new SqliteAdapter();
@@ -445,52 +436,78 @@ export async function status(
445
436
  config.busyTimeoutMs
446
437
  );
447
438
  if (!openResult.ok) {
439
+ await Promise.allSettled([
440
+ rootErrorsPromise,
441
+ embedModelCachedPromise,
442
+ connectorTargetsPromise,
443
+ backgroundIssuesPromise,
444
+ registrationRuntimeIssuesPromise,
445
+ residentRuntimeIssuesPromise,
446
+ ]);
448
447
  return { success: false, error: openResult.error.message };
449
448
  }
450
449
 
451
450
  try {
452
- const statusResult = await store.getStatus({
453
- embedModel: resolveModelUri(config, "embed"),
454
- chunking: config.chunking ?? {},
455
- configuredCollections: config.collections.map(({ name }) => name),
456
- });
451
+ const [
452
+ statusResult,
453
+ embedModelCached,
454
+ connectorTargets,
455
+ memory,
456
+ budgetStops,
457
+ staleCollections,
458
+ ] = await Promise.all([
459
+ store.getStatus({
460
+ embedModel: resolveModelUri(config, "embed"),
461
+ chunking: config.chunking ?? {},
462
+ configuredCollections: collectionNames,
463
+ }),
464
+ embedModelCachedPromise,
465
+ connectorTargetsPromise,
466
+ buildMemoryStatus(store, config.collections),
467
+ collectBudgetStops(store),
468
+ collectStaleCollections(store, collectionNames),
469
+ ]);
457
470
  if (!statusResult.ok) {
471
+ await Promise.allSettled([
472
+ rootErrorsPromise,
473
+ backgroundIssuesPromise,
474
+ registrationRuntimeIssuesPromise,
475
+ residentRuntimeIssuesPromise,
476
+ ]);
458
477
  return { success: false, error: statusResult.error.message };
459
478
  }
460
479
 
461
- const preset = getActivePreset(config);
462
- const embedModelCached = await new ModelCache(
463
- getModelsCachePath()
464
- ).isCached(preset.embed);
465
- const activation = await buildActivationStatus(
466
- store,
467
- config.collections.map(({ name }) => name),
468
- {
480
+ const [
481
+ activation,
482
+ backgroundIssues,
483
+ registrationIssues,
484
+ residentIssuesList,
485
+ rootErrors,
486
+ ] = await Promise.all([
487
+ buildActivationStatus(store, collectionNames, {
469
488
  semantic: {
470
489
  modelsCached: embedModelCached,
471
490
  embeddingBacklog: statusResult.value.embeddingBacklog,
472
491
  },
473
- connectorTargets: await getConnectorVerificationTargets(),
474
- }
475
- );
492
+ connectorTargets,
493
+ }),
494
+ backgroundIssuesPromise,
495
+ registrationRuntimeIssuesPromise,
496
+ residentRuntimeIssuesPromise,
497
+ rootErrorsPromise,
498
+ ]);
476
499
 
477
500
  return {
478
501
  success: true,
479
502
  status: statusResult.value,
480
503
  activation,
481
504
  contentTypeBoost: buildContentTypeBoostStatus(config.contentTypes ?? []),
482
- memory: await buildMemoryStatus(store, config.collections),
483
- backgroundIssues: await collectResidentIssues(),
484
- runtimeIssues: [
485
- ...(await checkRegistrationRuntimes()),
486
- ...(await checkResidentRuntimes()),
487
- ],
488
- budgetStops: await collectBudgetStops(store),
489
- staleCollections: await collectStaleCollections(
490
- store,
491
- config.collections.map(({ name }) => name)
492
- ),
493
- rootErrors: await rootErrors,
505
+ memory,
506
+ backgroundIssues,
507
+ runtimeIssues: [...registrationIssues, ...residentIssuesList],
508
+ budgetStops,
509
+ staleCollections,
510
+ rootErrors,
494
511
  };
495
512
  } finally {
496
513
  await store.close();
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Per-invocation CLI config and session-binding cache.
3
+ *
4
+ * Eliminates 2x-3x redundant YAML/Zod parses across preAction session-binding,
5
+ * initStore, and terminal-link policy within a single CLI command while staying
6
+ * completely inactive for direct non-CLI callers and invalidating immediately
7
+ * on config writes or resetGlobals().
8
+ *
9
+ * @module src/cli/config-cache
10
+ */
11
+
12
+ import type { LoadResult } from "../config/loader";
13
+ import type { Config } from "../config/types";
14
+
15
+ import { expandPath, getConfigPaths } from "../config/paths";
16
+ import { getConfigWriteGeneration } from "../config/saver";
17
+ import { isCliInvocationActive, registerGlobalsResetListener } from "./globals";
18
+
19
+ type LoadConfigResult = LoadResult<Config>;
20
+
21
+ interface CachedConfigEntry {
22
+ generation: number;
23
+ result: LoadConfigResult;
24
+ }
25
+
26
+ const configCache = new Map<string, CachedConfigEntry>();
27
+ const verifiedBindings = new Map<string, number>();
28
+
29
+ export function clearCliConfigCache(): void {
30
+ configCache.clear();
31
+ verifiedBindings.clear();
32
+ }
33
+
34
+ registerGlobalsResetListener(clearCliConfigCache);
35
+
36
+ function resolveCanonicalConfigPath(configPath?: string): string {
37
+ return configPath ? expandPath(configPath) : getConfigPaths().configFile;
38
+ }
39
+
40
+ /**
41
+ * Load config, reusing a parsed result within the same CLI invocation when
42
+ * no config write has occurred since it was loaded.
43
+ */
44
+ export async function loadConfigCached(
45
+ configPath?: string
46
+ ): Promise<LoadConfigResult> {
47
+ const { loadConfig } = await import("../config/loader");
48
+ if (!isCliInvocationActive()) {
49
+ return loadConfig(configPath);
50
+ }
51
+ const canonical = resolveCanonicalConfigPath(configPath);
52
+ const generation = getConfigWriteGeneration();
53
+ const cached = configCache.get(canonical);
54
+ if (cached && cached.generation === generation) {
55
+ return cached.result;
56
+ }
57
+ const loaded = await loadConfig(configPath);
58
+ if (loaded.ok && getConfigWriteGeneration() === generation) {
59
+ configCache.set(canonical, { generation, result: loaded });
60
+ }
61
+ return loaded;
62
+ }
63
+
64
+ /** Check whether a (configPath, indexName) binding was already verified in this CLI invocation. */
65
+ export function isSessionBindingVerifiedInInvocation(
66
+ configPath: string,
67
+ indexName: string
68
+ ): boolean {
69
+ if (!isCliInvocationActive()) {
70
+ return false;
71
+ }
72
+ const key = `${resolveCanonicalConfigPath(configPath)}\u0000${indexName}`;
73
+ return verifiedBindings.get(key) === getConfigWriteGeneration();
74
+ }
75
+
76
+ /** Record that (configPath, indexName) passed session-binding verification in this CLI invocation. */
77
+ export function markSessionBindingVerifiedInInvocation(
78
+ configPath: string,
79
+ indexName: string
80
+ ): void {
81
+ if (!isCliInvocationActive()) {
82
+ return;
83
+ }
84
+ const key = `${resolveCanonicalConfigPath(configPath)}\u0000${indexName}`;
85
+ verifiedBindings.set(key, getConfigWriteGeneration());
86
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Shared CLI global options state.
3
+ * Extracted from src/cli/program so commands and runners do not pull in
4
+ * Commander or the full command definition tree just to read/reset globals.
5
+ *
6
+ * @module src/cli/globals
7
+ */
8
+
9
+ import type { GlobalOptions } from "./context";
10
+
11
+ import { setColorsEnabled } from "./colors";
12
+
13
+ const globalState: { current: GlobalOptions | null } = { current: null };
14
+ let cliInvocationActive = false;
15
+ const resetListeners = new Set<() => void>();
16
+
17
+ /** Register a cleanup hook invoked when CLI global state resets. */
18
+ export function registerGlobalsResetListener(listener: () => void): void {
19
+ resetListeners.add(listener);
20
+ }
21
+
22
+ /** Mark that a CLI invocation is active (enables per-invocation caches). */
23
+ export function setCliInvocationActive(active: boolean): void {
24
+ cliInvocationActive = active;
25
+ if (!active) {
26
+ for (const listener of resetListeners) {
27
+ listener();
28
+ }
29
+ }
30
+ }
31
+
32
+ /** True while inside an active runCli() invocation. */
33
+ export function isCliInvocationActive(): boolean {
34
+ return cliInvocationActive || globalState.current !== null;
35
+ }
36
+
37
+ /** Set resolved global options (called by Commander's preAction hook). */
38
+ export function setGlobals(globals: GlobalOptions): void {
39
+ globalState.current = globals;
40
+ }
41
+
42
+ /**
43
+ * Get resolved global options. Must be called after command parsing.
44
+ * Throws if called before preAction hook runs.
45
+ */
46
+ export function getGlobals(): GlobalOptions {
47
+ if (!globalState.current) {
48
+ throw new Error("Global options not resolved - called before preAction?");
49
+ }
50
+ return globalState.current;
51
+ }
52
+
53
+ /**
54
+ * Reset global state (for testing and at the start of every CLI invocation).
55
+ * Resets option state, color state, and per-invocation caches.
56
+ */
57
+ export function resetGlobals(): void {
58
+ globalState.current = null;
59
+ cliInvocationActive = false;
60
+ setColorsEnabled(true);
61
+ for (const listener of resetListeners) {
62
+ listener();
63
+ }
64
+ }
@@ -233,6 +233,29 @@ export function getDefaultLimit(format: OutputFormat): number {
233
233
  * Parse and validate a positive integer option.
234
234
  * Throws CliError on invalid input.
235
235
  */
236
+ /**
237
+ * Optional run bound (`--max-chunks`, `--max-seconds`): a whole positive
238
+ * safe integer, rejecting values like `2.9`, `1e3` or `7junk` that
239
+ * parseInt would truncate.
240
+ */
241
+ export function parseRunLimit(
242
+ name: string,
243
+ value: unknown
244
+ ): number | undefined {
245
+ if (value === undefined) return undefined;
246
+ const text = (
247
+ typeof value === "string" ? value : JSON.stringify(value)
248
+ ).trim();
249
+ const num = Number(text);
250
+ if (!/^[0-9]+$/.test(text) || !Number.isSafeInteger(num) || num < 1) {
251
+ throw new CliError(
252
+ "VALIDATION",
253
+ `--${name} must be a positive whole number, got: ${text}`
254
+ );
255
+ }
256
+ return num;
257
+ }
258
+
236
259
  export function parsePositiveInt(name: string, value: unknown): number {
237
260
  if (value === undefined || value === null) {
238
261
  throw new CliError("VALIDATION", `--${name} requires a value`);
@@ -20,11 +20,6 @@ import {
20
20
  } from "../app/constants";
21
21
  import { INDEX_NAME_REQUIREMENTS, isValidIndexName } from "../app/index-name";
22
22
  import { resolveDepthPolicy } from "../core/depth-policy";
23
- import {
24
- findingsRunStatePathForIndex,
25
- formatFindingsRunStatusLine,
26
- readFindingsRunStatus,
27
- } from "../core/findings-run-state";
28
23
  import { residentShutdownHandlerInstalled } from "../core/resident-shutdown-handler";
29
24
  import { parseAndValidateTagFilter } from "../core/tags";
30
25
  import {
@@ -35,8 +30,11 @@ import {
35
30
  withCliWriteLease,
36
31
  type WriteLeaseBusyFailure,
37
32
  } from "../core/write-lease";
38
- import { type McpToolProfile, parseMcpToolProfile } from "../mcp/tool-profile";
39
- import { setColorsEnabled } from "./colors";
33
+ import {
34
+ type McpToolProfile,
35
+ parseMcpToolProfile,
36
+ } from "../mcp/tool-profile-types";
37
+ import { loadConfigCached } from "./config-cache";
40
38
  import {
41
39
  applyGlobalOptions,
42
40
  type GlobalOptions,
@@ -48,6 +46,7 @@ import {
48
46
  residentIssues,
49
47
  } from "./detach";
50
48
  import { CliError } from "./errors";
49
+ import { getGlobals, resetGlobals, setGlobals } from "./globals";
51
50
  import {
52
51
  assertFormatSupported,
53
52
  CMD,
@@ -58,36 +57,15 @@ import {
58
57
  parseCliMetadataFilter,
59
58
  parseOptionalFloat,
60
59
  parsePositiveInt,
60
+ parseRunLimit,
61
61
  } from "./options";
62
62
  import { resolveCliQueryText } from "./query-text";
63
63
 
64
64
  // ─────────────────────────────────────────────────────────────────────────────
65
- // Global State (set by preAction hook)
65
+ // Global State (re-exported from ./globals for backwards compatibility)
66
66
  // ─────────────────────────────────────────────────────────────────────────────
67
67
 
68
- // Using object wrapper to allow mutation while satisfying linter
69
- const globalState: { current: GlobalOptions | null } = { current: null };
70
-
71
- /**
72
- * Get resolved global options. Must be called after command parsing.
73
- * Throws if called before preAction hook runs.
74
- */
75
- export function getGlobals(): GlobalOptions {
76
- if (!globalState.current) {
77
- throw new Error("Global options not resolved - called before preAction?");
78
- }
79
- return globalState.current;
80
- }
81
-
82
- /**
83
- * Reset global state (for testing).
84
- * Resets both option state and color state to avoid test pollution.
85
- */
86
- export function resetGlobals(): void {
87
- globalState.current = null;
88
- // Reset colors to default (true) - will be set by applyGlobalOptions on next run
89
- setColorsEnabled(true);
90
- }
68
+ export { getGlobals, resetGlobals };
91
69
 
92
70
  /**
93
71
  * Resolve the user-facing argv slice (everything after `[execPath, scriptPath]`)
@@ -219,8 +197,7 @@ async function resolveTerminalLinkPolicy(
219
197
  };
220
198
  }
221
199
 
222
- const { loadConfig } = await import("../config");
223
- const configResult = await loadConfig(globals.config);
200
+ const configResult = await loadConfigCached(globals.config);
224
201
  const configTemplate = configResult.ok
225
202
  ? configResult.value.editorUriTemplate?.trim()
226
203
  : undefined;
@@ -372,7 +349,7 @@ export function createProgram(): Command {
372
349
  );
373
350
  }
374
351
  applyGlobalOptions(globals);
375
- globalState.current = globals;
352
+ setGlobals(globals);
376
353
  // convert reads no config or index, so there is no binding to check.
377
354
  if (actionCommand === convertCommand) return;
378
355
  const { assertCliSessionBinding } = await import("./session-binding");
@@ -3676,13 +3653,21 @@ function wireManagementCommands(program: Command): void {
3676
3653
  .description("Generate embeddings for indexed documents")
3677
3654
  .option("--collection <name>", "restrict to one collection")
3678
3655
  .option("--model <uri>", "embedding model URI")
3679
- .option("--batch-size <num>", "batch size", "32")
3656
+ .option("--batch-size <num>", "batch size")
3680
3657
  .option("--force", "regenerate all embeddings")
3681
3658
  .option(
3682
3659
  "--new-partition",
3683
3660
  "confirm building a separate vector partition for an incompatible runtime"
3684
3661
  )
3685
3662
  .option("--dry-run", "show what would be done")
3663
+ .option(
3664
+ "--max-chunks <num>",
3665
+ "stop after the batch that reaches this many chunks sent to the model (retries count)"
3666
+ )
3667
+ .option(
3668
+ "--max-seconds <num>",
3669
+ "stop after the batch that reaches this many seconds"
3670
+ )
3686
3671
  .option("--json", "JSON output")
3687
3672
  ).action(
3688
3673
  async (
@@ -3696,14 +3681,29 @@ function wireManagementCommands(program: Command): void {
3696
3681
  const collection =
3697
3682
  collectionArg ?? (cmdOpts.collection as string | undefined);
3698
3683
  const lease = parseWriteLeaseFlags(cmdOpts);
3684
+ if (
3685
+ cmdOpts.force &&
3686
+ (cmdOpts.maxChunks !== undefined || cmdOpts.maxSeconds !== undefined)
3687
+ )
3688
+ // A forced pass restarts from the first chunk, so a bounded one
3689
+ // would re-embed the same prefix on every run.
3690
+ throw new CliError(
3691
+ "VALIDATION",
3692
+ "--max-chunks and --max-seconds cannot be combined with --force"
3693
+ );
3699
3694
  const opts = {
3700
3695
  configPath: globals.config,
3701
3696
  indexName: globals.index,
3702
3697
  collection,
3703
3698
  model: cmdOpts.model as string | undefined,
3704
- batchSize: parsePositiveInt("batch-size", cmdOpts.batchSize),
3699
+ batchSize:
3700
+ cmdOpts.batchSize !== undefined
3701
+ ? parsePositiveInt("batch-size", cmdOpts.batchSize)
3702
+ : undefined,
3705
3703
  force: Boolean(cmdOpts.force),
3706
3704
  dryRun: Boolean(cmdOpts.dryRun),
3705
+ maxChunks: parseRunLimit("max-chunks", cmdOpts.maxChunks),
3706
+ maxSeconds: parseRunLimit("max-seconds", cmdOpts.maxSeconds),
3707
3707
  yes: globals.yes,
3708
3708
  newPartition: Boolean(cmdOpts.newPartition),
3709
3709
  json: format === "json",
@@ -3719,7 +3719,9 @@ function wireManagementCommands(program: Command): void {
3719
3719
  throw new CliError("RUNTIME", result.error ?? "Embed failed");
3720
3720
  }
3721
3721
  process.stdout.write(`${formatEmbed(result, opts)}\n`);
3722
- if (result.contentionErrors > 0) {
3722
+ // A run stopped by --max-chunks/--max-seconds exits 0 as requested;
3723
+ // its receipt still reports contentionErrors.
3724
+ if (result.contentionErrors > 0 && result.stopped !== "limit") {
3723
3725
  throw new CliError(
3724
3726
  "BUSY",
3725
3727
  "Some chunks were deferred by index contention",
@@ -5228,6 +5230,11 @@ async function runDaemonStatus(deps: DaemonStatusDeps): Promise<void> {
5228
5230
  });
5229
5231
  // Persisted by the daemon after every scheduled findings attempt; absent
5230
5232
  // (null) when the pass is not configured. Read from disk, never live.
5233
+ const {
5234
+ findingsRunStatePathForIndex,
5235
+ formatFindingsRunStatusLine,
5236
+ readFindingsRunStatus,
5237
+ } = await import("../core/findings-run-state");
5231
5238
  const findings = await readFindingsRunStatus(
5232
5239
  findingsRunStatePathForIndex(deps.indexName)
5233
5240
  );