@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
@@ -64,6 +64,7 @@ import type {
64
64
  FileRefactorResolutionSnapshot,
65
65
  GetGraphNeighborsOptions,
66
66
  GetGraphOptions,
67
+ GraphDocumentIdentity,
67
68
  GraphEdgeConfidence,
68
69
  GraphEdgeAudit,
69
70
  GraphLinkType,
@@ -149,6 +150,7 @@ import {
149
150
  import { normalizeWikiName, stripWikiMdExt } from "../../core/links";
150
151
  import { tracePhase } from "../../core/phase-trace";
151
152
  import {
153
+ parseStoredTypedMetadata,
152
154
  TYPED_METADATA_INGEST_VERSION,
153
155
  typedMetadataSchema,
154
156
  } from "../../core/typed-metadata";
@@ -185,6 +187,7 @@ import {
185
187
  } from "./capsule-registry-store";
186
188
  import {
187
189
  appendDocumentChange as appendStoredDocumentChange,
190
+ type DocumentChangeSnapshot,
188
191
  enforceDocumentChangeRetention as enforceStoredDocumentChangeRetention,
189
192
  listDocumentChanges as listStoredDocumentChanges,
190
193
  purgeDocumentChanges as purgeStoredDocumentChanges,
@@ -272,7 +275,6 @@ const WHITESPACE_REGEX = /\s+/;
272
275
  const SINGLE_LINE_QUERY_PATTERN = /[\r\n]/;
273
276
  const DOUBLE_QUOTE_PATTERN = /"/g;
274
277
  const DOC_EDGE_TYPE_PATTERN = /^[a-z][a-z0-9_]*$/;
275
- const SQLITE_SAFE_PARAMETER_BATCH_SIZE = 900;
276
278
 
277
279
  /**
278
280
  * Effective physical source path for watcher fallback queries.
@@ -632,6 +634,16 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
632
634
  private shutdownDeadline?: number;
633
635
  private contextGeneration = 0;
634
636
  private chunkingGeneration = 0;
637
+ private staleIndexedCache: {
638
+ dv: number;
639
+ tc: number;
640
+ indexedNames: string[];
641
+ } | null = null;
642
+ private dateFieldsCache: {
643
+ dv: number;
644
+ tc: number;
645
+ byCollection: Map<string, string[]>;
646
+ } | null = null;
635
647
 
636
648
  // ─────────────────────────────────────────────────────────────────────────
637
649
  // Lifecycle
@@ -657,17 +669,21 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
657
669
  );
658
670
 
659
671
  // Keep WAL everywhere so readers can continue while a writer is active.
660
- // CI still relaxes fsync/temp-store for speed, but MEMORY journal mode
661
- // breaks the cross-process read/write behavior we rely on in CLI tests.
672
+ // CI still relaxes fsync for speed, but MEMORY journal mode breaks the
673
+ // cross-process read/write behavior we rely on in CLI tests.
674
+ let isWal = false;
662
675
  try {
663
- const journalMode = this.db
676
+ let journalMode = this.db
664
677
  .query<{ journal_mode: string }, []>("PRAGMA journal_mode")
665
678
  .get()?.journal_mode;
666
679
  tracePhase(`db: journal_mode ${journalMode}`);
667
680
  if (journalMode?.toLowerCase() !== "wal") {
668
- this.db.exec("PRAGMA journal_mode = WAL");
669
- tracePhase("db: journal_mode set to wal");
681
+ journalMode = this.db
682
+ .query<{ journal_mode: string }, []>("PRAGMA journal_mode = WAL")
683
+ .get()?.journal_mode;
684
+ tracePhase(`db: journal_mode set to ${journalMode}`);
670
685
  }
686
+ isWal = journalMode?.toLowerCase() === "wal";
671
687
  } catch (cause) {
672
688
  if (!isDatabaseLockedError(cause)) {
673
689
  throw cause;
@@ -677,9 +693,18 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
677
693
  // rely on the existing DB journal mode instead of failing open().
678
694
  }
679
695
 
696
+ this.db.exec("PRAGMA temp_store = MEMORY");
697
+ this.db.exec("PRAGMA cache_size = -64000");
698
+ try {
699
+ this.db.exec("PRAGMA mmap_size = 268435456");
700
+ } catch {
701
+ // Platforms/filesystems that reject mmap_size keep default file I/O.
702
+ }
703
+
680
704
  if (process.env.CI) {
681
705
  this.db.exec("PRAGMA synchronous = OFF");
682
- this.db.exec("PRAGMA temp_store = MEMORY");
706
+ } else if (isWal) {
707
+ this.db.exec("PRAGMA synchronous = NORMAL");
683
708
  }
684
709
 
685
710
  // Load fts5-snowball extension if using snowball tokenizer
@@ -729,6 +754,13 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
729
754
  this.db.exec(
730
755
  `PRAGMA busy_timeout = ${resolveBusyTimeoutMs(busyTimeoutMs)}`
731
756
  );
757
+ this.db.exec("PRAGMA temp_store = MEMORY");
758
+ this.db.exec("PRAGMA cache_size = -32000");
759
+ try {
760
+ this.db.exec("PRAGMA mmap_size = 268435456");
761
+ } catch {
762
+ // Platforms/filesystems that reject mmap_size keep default file I/O.
763
+ }
732
764
  this.contextGeneration += 1;
733
765
  return ok(undefined);
734
766
  } catch (cause) {
@@ -746,6 +778,8 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
746
778
 
747
779
  async close(): Promise<void> {
748
780
  this.fenceForShutdown();
781
+ this.staleIndexedCache = null;
782
+ this.dateFieldsCache = null;
749
783
  this.readDb?.close(false);
750
784
  this.readDb = null;
751
785
  if (this.db) {
@@ -831,6 +865,13 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
831
865
  main.query<{ timeout: number }, []>("PRAGMA busy_timeout").get()
832
866
  ?.timeout ?? DEFAULT_BUSY_TIMEOUT_MS;
833
867
  db.exec(`PRAGMA busy_timeout = ${busyTimeout}`);
868
+ db.exec("PRAGMA temp_store = MEMORY");
869
+ db.exec("PRAGMA cache_size = -32000");
870
+ try {
871
+ db.exec("PRAGMA mmap_size = 268435456");
872
+ } catch {
873
+ // Platforms/filesystems that reject mmap_size keep default file I/O.
874
+ }
834
875
  if (this.ftsTokenizer.startsWith("snowball")) {
835
876
  const snowball = loadFts5Snowball(db);
836
877
  if (!snowball.loaded)
@@ -1105,20 +1146,47 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
1105
1146
  }
1106
1147
  }
1107
1148
 
1149
+ private readDbVersionTuple(db: Database): { dv: number; tc: number } {
1150
+ const row = db
1151
+ .query<{ dv: number; tc: number }, []>(
1152
+ "SELECT (SELECT * FROM pragma_data_version) AS dv, total_changes() AS tc"
1153
+ )
1154
+ .get();
1155
+ return row ?? { dv: 0, tc: 0 };
1156
+ }
1157
+
1108
1158
  /**
1109
1159
  * Indexed collections `configured` omits, checked cheaply on each read of a
1110
1160
  * long-lived client: another client may add a collection after it opened.
1161
+ * Memoized by (PRAGMA data_version, total_changes()) so unchanged reads skip
1162
+ * the collection/document EXISTS scan.
1111
1163
  */
1112
1164
  staleIndexedCollections(configured: readonly string[]): StaleCollection[] {
1113
1165
  const db = this.ensureOpen();
1166
+ const canCache = !db.inTransaction;
1167
+ const { dv, tc } = this.readDbVersionTuple(db);
1168
+ let indexedNames: string[];
1169
+ if (
1170
+ canCache &&
1171
+ this.staleIndexedCache &&
1172
+ this.staleIndexedCache.dv === dv &&
1173
+ this.staleIndexedCache.tc === tc
1174
+ ) {
1175
+ indexedNames = this.staleIndexedCache.indexedNames;
1176
+ } else {
1177
+ indexedNames = db
1178
+ .query<{ name: string }, []>(
1179
+ `SELECT c.name AS name FROM collections c
1180
+ WHERE EXISTS (SELECT 1 FROM documents d WHERE d.collection = c.name)`
1181
+ )
1182
+ .all()
1183
+ .map(({ name }) => name);
1184
+ if (canCache) {
1185
+ this.staleIndexedCache = { dv, tc, indexedNames };
1186
+ }
1187
+ }
1114
1188
  const listed = new Set(configured);
1115
- const indexed = db
1116
- .query<{ name: string }, []>(
1117
- `SELECT c.name AS name FROM collections c
1118
- WHERE EXISTS (SELECT 1 FROM documents d WHERE d.collection = c.name)`
1119
- )
1120
- .all();
1121
- return indexed.some(({ name }) => !listed.has(name))
1189
+ return indexedNames.some((name) => !listed.has(name))
1122
1190
  ? this.queryStaleCollections(db, configured).filter(
1123
1191
  (c) => c.documents > 0
1124
1192
  )
@@ -1773,9 +1841,23 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
1773
1841
  const uri = buildUri(doc.collection, doc.relPath);
1774
1842
 
1775
1843
  const transaction = db.transaction((): UpsertDocumentResult => {
1844
+ interface PreviousDocumentSnapshotRow {
1845
+ id: number;
1846
+ collection: string;
1847
+ rel_path: string;
1848
+ docid: string;
1849
+ uri: string;
1850
+ source_hash: string;
1851
+ mirror_hash: string | null;
1852
+ active: number;
1853
+ title: string | null;
1854
+ }
1776
1855
  const previousRow = db
1777
- .query<DbDocumentRow, [string, string]>(
1778
- "SELECT * FROM documents WHERE collection = ? AND rel_path = ?"
1856
+ .query<PreviousDocumentSnapshotRow, [string, string]>(
1857
+ `SELECT id, collection, rel_path, docid, uri, source_hash,
1858
+ mirror_hash, active, title
1859
+ FROM documents
1860
+ WHERE collection = ? AND rel_path = ?`
1779
1861
  )
1780
1862
  .get(doc.collection, doc.relPath);
1781
1863
  const legacyTitles = snapshotLegacyTitles(
@@ -1788,8 +1870,9 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
1788
1870
  : []
1789
1871
  );
1790
1872
 
1791
- db.run(
1792
- `
1873
+ const idRow = db
1874
+ .query<{ id: number }, (string | number | null)[]>(
1875
+ `
1793
1876
  INSERT INTO documents (
1794
1877
  collection, rel_path, source_hash, source_mime, source_ext,
1795
1878
  source_size, source_mtime, source_ctime, docid, uri, title, mirror_hash,
@@ -1837,8 +1920,10 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
1837
1920
  last_error_at = excluded.last_error_at,
1838
1921
  ingest_version = excluded.ingest_version,
1839
1922
  updated_at = datetime('now')
1840
- `,
1841
- [
1923
+ RETURNING id
1924
+ `
1925
+ )
1926
+ .get(
1842
1927
  doc.collection,
1843
1928
  doc.relPath,
1844
1929
  doc.sourceHash,
@@ -1874,16 +1959,8 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
1874
1959
  doc.lastErrorCode ?? null,
1875
1960
  doc.lastErrorMessage ?? null,
1876
1961
  doc.lastErrorCode ? new Date().toISOString() : null,
1877
- doc.ingestVersion ?? null,
1878
- ]
1879
- );
1880
-
1881
- // Get the row id (either inserted or updated)
1882
- const idRow = db
1883
- .query<{ id: number }, [string, string]>(
1884
- "SELECT id FROM documents WHERE collection = ? AND rel_path = ?"
1885
- )
1886
- .get(doc.collection, doc.relPath);
1962
+ doc.ingestVersion ?? null
1963
+ );
1887
1964
 
1888
1965
  if (!idRow) {
1889
1966
  throw new Error("Failed to get document id after upsert");
@@ -1898,32 +1975,44 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
1898
1975
  (previousRow.mirror_hash !== (doc.mirrorHash ?? null) ||
1899
1976
  previousRow.title !== (doc.title ?? null))
1900
1977
  ) {
1901
- db.run("DELETE FROM vector_owners WHERE document_id = ?", [idRow.id]);
1978
+ db.query("DELETE FROM vector_owners WHERE document_id = ?").run(
1979
+ idRow.id
1980
+ );
1902
1981
  }
1903
1982
 
1904
1983
  // Conversion failures deliberately drop mirror ownership. Remove the
1905
1984
  // old lexical projection in the same transaction so stale content can
1906
1985
  // never join against the newly updated document metadata.
1907
1986
  if (doc.mirrorHash == null) {
1908
- db.run("DELETE FROM documents_fts WHERE rowid = ?", [idRow.id]);
1909
- db.run("UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?", [
1910
- idRow.id,
1911
- ]);
1987
+ db.query("DELETE FROM documents_fts WHERE rowid = ?").run(idRow.id);
1988
+ db.query(
1989
+ "UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?"
1990
+ ).run(idRow.id);
1912
1991
  }
1913
1992
 
1914
1993
  if (doc.changeJournal !== false) {
1915
- const nextRow = db
1916
- .query<DbDocumentRow, [number]>(
1917
- "SELECT * FROM documents WHERE id = ?"
1918
- )
1919
- .get(idRow.id);
1920
- if (!nextRow) {
1921
- throw new Error("Failed to read document after upsert");
1922
- }
1923
- const previous = previousRow
1924
- ? snapshotDocumentChange(mapDocumentRow(previousRow))
1994
+ const previous: DocumentChangeSnapshot | null = previousRow
1995
+ ? {
1996
+ id: previousRow.id,
1997
+ collection: previousRow.collection,
1998
+ relPath: previousRow.rel_path,
1999
+ docid: previousRow.docid,
2000
+ uri: previousRow.uri,
2001
+ sourceHash: previousRow.source_hash,
2002
+ mirrorHash: previousRow.mirror_hash,
2003
+ active: previousRow.active === 1,
2004
+ }
1925
2005
  : null;
1926
- const next = snapshotDocumentChange(mapDocumentRow(nextRow));
2006
+ const next: DocumentChangeSnapshot = {
2007
+ id: idRow.id,
2008
+ collection: doc.collection,
2009
+ relPath: doc.relPath,
2010
+ docid,
2011
+ uri,
2012
+ sourceHash: doc.sourceHash,
2013
+ mirrorHash: doc.mirrorHash ?? null,
2014
+ active: true,
2015
+ };
1927
2016
  const kind: DocumentChangeKind | null =
1928
2017
  previous === null
1929
2018
  ? "create"
@@ -2126,6 +2215,59 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2126
2215
  }
2127
2216
  }
2128
2217
 
2218
+ async listGraphDocumentIdentities(): Promise<
2219
+ StoreResult<GraphDocumentIdentity[]>
2220
+ > {
2221
+ try {
2222
+ const db = this.ensureOpen();
2223
+ const rows = db
2224
+ .query<
2225
+ {
2226
+ documentId: number;
2227
+ collection: string;
2228
+ relPath: string;
2229
+ docid: string;
2230
+ uri: string;
2231
+ title: string | null;
2232
+ mirrorHash: string | null;
2233
+ sourceHash: string;
2234
+ contentType: string | null;
2235
+ active: number;
2236
+ },
2237
+ []
2238
+ >(
2239
+ `SELECT id AS documentId, collection, rel_path AS relPath, docid, uri,
2240
+ title, mirror_hash AS mirrorHash, source_hash AS sourceHash,
2241
+ content_type AS contentType, active
2242
+ FROM documents`
2243
+ )
2244
+ .all();
2245
+
2246
+ return ok(
2247
+ rows.map((row) => ({
2248
+ documentId: row.documentId,
2249
+ collection: row.collection,
2250
+ relPath: row.relPath,
2251
+ docid: row.docid,
2252
+ uri: row.uri,
2253
+ title: row.title,
2254
+ mirrorHash: row.mirrorHash,
2255
+ sourceHash: row.sourceHash,
2256
+ contentType: row.contentType,
2257
+ active: row.active === 1,
2258
+ }))
2259
+ );
2260
+ } catch (cause) {
2261
+ return err(
2262
+ "QUERY_FAILED",
2263
+ cause instanceof Error
2264
+ ? cause.message
2265
+ : "Failed to list graph document identities",
2266
+ cause
2267
+ );
2268
+ }
2269
+ }
2270
+
2129
2271
  async listDocumentsForAudit(options: {
2130
2272
  collections: readonly string[];
2131
2273
  pathPrefixes: readonly string[];
@@ -2412,34 +2554,24 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2412
2554
  }
2413
2555
 
2414
2556
  const db = this.ensureOpen();
2415
- const rows: DbDocumentRow[] = [];
2416
-
2417
- // SQLite SQLITE_LIMIT_VARIABLE_NUMBER defaults to 999.
2418
- // Reserve headroom for optional non-IN parameters.
2419
- const SQL_PARAM_LIMIT = 898;
2557
+ const clauses = ["mirror_hash IN (SELECT value FROM json_each(?))"];
2558
+ const params: string[] = [JSON.stringify(uniqueHashes)];
2420
2559
 
2421
- for (let i = 0; i < uniqueHashes.length; i += SQL_PARAM_LIMIT) {
2422
- const batch = uniqueHashes.slice(i, i + SQL_PARAM_LIMIT);
2423
- const placeholders = batch.map(() => "?").join(",");
2424
- const clauses = [`mirror_hash IN (${placeholders})`];
2425
- const params: string[] = [...batch];
2426
-
2427
- if (options.activeOnly ?? true) {
2428
- clauses.push("active = 1");
2429
- }
2430
- if (options.collection) {
2431
- clauses.push("collection = ?");
2432
- params.push(options.collection);
2433
- }
2434
- if (options.collections !== undefined) {
2435
- clauses.push("collection IN (SELECT value FROM json_each(?))");
2436
- params.push(JSON.stringify(options.collections));
2437
- }
2438
-
2439
- const sql = `SELECT * FROM documents INDEXED BY idx_documents_mirror_hash WHERE ${clauses.join(" AND ")} ORDER BY id`;
2440
- rows.push(...db.query<DbDocumentRow, string[]>(sql).all(...params));
2560
+ if (options.activeOnly ?? true) {
2561
+ clauses.push("active = 1");
2562
+ }
2563
+ if (options.collection) {
2564
+ clauses.push("collection = ?");
2565
+ params.push(options.collection);
2566
+ }
2567
+ if (options.collections !== undefined) {
2568
+ clauses.push("collection IN (SELECT value FROM json_each(?))");
2569
+ params.push(JSON.stringify(options.collections));
2441
2570
  }
2442
2571
 
2572
+ const sql = `SELECT * FROM documents INDEXED BY idx_documents_mirror_hash WHERE ${clauses.join(" AND ")} ORDER BY id`;
2573
+ const rows = db.query<DbDocumentRow, string[]>(sql).all(...params);
2574
+
2443
2575
  return ok(rows.map(mapDocumentRow));
2444
2576
  } catch (cause) {
2445
2577
  return err(
@@ -2473,33 +2605,26 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2473
2605
  }
2474
2606
 
2475
2607
  const db = this.ensureOpen();
2476
- const rows: DbDocumentRow[] = [];
2477
- const SQL_PARAM_LIMIT = options.collection ? 899 : 900;
2478
-
2479
- for (let i = 0; i < uniqueDocids.length; i += SQL_PARAM_LIMIT) {
2480
- const batch = uniqueDocids.slice(i, i + SQL_PARAM_LIMIT);
2481
- const placeholders = batch.map(() => "?").join(",");
2482
- const clauses = [`docid IN (${placeholders})`];
2483
- const params: (string | number)[] = [...batch];
2608
+ const clauses = ["docid IN (SELECT value FROM json_each(?))"];
2609
+ const params: (string | number)[] = [JSON.stringify(uniqueDocids)];
2484
2610
 
2485
- if (options.activeOnly ?? true) {
2486
- clauses.push("active = 1");
2487
- }
2488
- if (options.collection) {
2489
- clauses.push("collection = ?");
2490
- params.push(options.collection);
2491
- }
2611
+ if (options.activeOnly ?? true) {
2612
+ clauses.push("active = 1");
2613
+ }
2614
+ if (options.collection) {
2615
+ clauses.push("collection = ?");
2616
+ params.push(options.collection);
2617
+ }
2492
2618
 
2493
- if (options.eligibility) {
2494
- const eligible = buildEligibleDocumentQuery(options.eligibility, db);
2495
- clauses.push(`id IN (SELECT id FROM (${eligible.sql}))`);
2496
- params.push(...eligible.params);
2497
- }
2498
- const sql = `SELECT * FROM documents WHERE ${clauses.join(" AND ")} ORDER BY id`;
2499
- rows.push(
2500
- ...db.query<DbDocumentRow, (string | number)[]>(sql).all(...params)
2501
- );
2619
+ if (options.eligibility) {
2620
+ const eligible = buildEligibleDocumentQuery(options.eligibility, db);
2621
+ clauses.push(`id IN (SELECT id FROM (${eligible.sql}))`);
2622
+ params.push(...eligible.params);
2502
2623
  }
2624
+ const sql = `SELECT * FROM documents WHERE ${clauses.join(" AND ")} ORDER BY id`;
2625
+ const rows = db
2626
+ .query<DbDocumentRow, (string | number)[]>(sql)
2627
+ .all(...params);
2503
2628
 
2504
2629
  return ok(rows.map(mapDocumentRow));
2505
2630
  } catch (cause) {
@@ -2576,11 +2701,11 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2576
2701
  }
2577
2702
 
2578
2703
  if (options.categories && options.categories.length > 0) {
2579
- const placeholders = options.categories.map(() => "?").join(",");
2704
+ const categoriesJson = JSON.stringify(options.categories);
2580
2705
  conditions.push(
2581
- `(d.content_type IN (${placeholders}) OR EXISTS (SELECT 1 FROM json_each(COALESCE(d.categories, '[]')) jc WHERE jc.value IN (${placeholders})))`
2706
+ "(d.content_type IN (SELECT value FROM json_each(?)) OR EXISTS (SELECT 1 FROM json_each(COALESCE(d.categories, '[]')) jc WHERE jc.value IN (SELECT value FROM json_each(?))))"
2582
2707
  );
2583
- params.push(...options.categories, ...options.categories);
2708
+ params.push(categoriesJson, categoriesJson);
2584
2709
  }
2585
2710
 
2586
2711
  if (options.author) {
@@ -2590,11 +2715,10 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2590
2715
 
2591
2716
  // tagsAny: document has at least one of these tags (OR)
2592
2717
  if (tagsAny && tagsAny.length > 0) {
2593
- const placeholders = tagsAny.map(() => "?").join(",");
2594
2718
  conditions.push(
2595
- `EXISTS (SELECT 1 FROM doc_tags dt WHERE dt.document_id = d.id AND dt.tag IN (${placeholders}))`
2719
+ "EXISTS (SELECT 1 FROM doc_tags dt WHERE dt.document_id = d.id AND dt.tag IN (SELECT value FROM json_each(?)))"
2596
2720
  );
2597
- params.push(...tagsAny);
2721
+ params.push(JSON.stringify(tagsAny));
2598
2722
  }
2599
2723
 
2600
2724
  // tagsAll: document has all of these tags (AND)
@@ -2648,6 +2772,24 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2648
2772
  ): Promise<StoreResult<string[]>> {
2649
2773
  try {
2650
2774
  const db = this.ensureOpen();
2775
+ const canCache = !db.inTransaction;
2776
+ const { dv, tc } = this.readDbVersionTuple(db);
2777
+ const cacheKey = collection ?? "";
2778
+ if (canCache) {
2779
+ if (
2780
+ this.dateFieldsCache &&
2781
+ this.dateFieldsCache.dv === dv &&
2782
+ this.dateFieldsCache.tc === tc
2783
+ ) {
2784
+ const hit = this.dateFieldsCache.byCollection.get(cacheKey);
2785
+ if (hit) {
2786
+ return ok([...hit]);
2787
+ }
2788
+ } else {
2789
+ this.dateFieldsCache = { dv, tc, byCollection: new Map() };
2790
+ }
2791
+ }
2792
+
2651
2793
  const conditions: string[] = [
2652
2794
  "d.active = 1",
2653
2795
  "d.date_fields IS NOT NULL",
@@ -2667,8 +2809,14 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2667
2809
  ORDER BY jf.key ASC
2668
2810
  `;
2669
2811
 
2670
- const rows = db.query<{ field: string }, string[]>(sql).all(...params);
2671
- return ok(rows.map((r) => r.field));
2812
+ const fields = db
2813
+ .query<{ field: string }, string[]>(sql)
2814
+ .all(...params)
2815
+ .map((r) => r.field);
2816
+ if (canCache && this.dateFieldsCache) {
2817
+ this.dateFieldsCache.byCollection.set(cacheKey, fields);
2818
+ }
2819
+ return ok([...fields]);
2672
2820
  } catch (cause) {
2673
2821
  return err(
2674
2822
  "QUERY_FAILED",
@@ -2680,6 +2828,212 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2680
2828
  }
2681
2829
  }
2682
2830
 
2831
+ /**
2832
+ * Targeted lookup for similarity hit hydration: fetches only the active
2833
+ * documents owning the returned vector hits instead of scanning the entire
2834
+ * documents table.
2835
+ */
2836
+ async listDocumentsForSimilarity(options: {
2837
+ documentIds: readonly number[];
2838
+ mirrorHashes: readonly string[];
2839
+ collection?: string;
2840
+ }): Promise<
2841
+ StoreResult<
2842
+ Array<{
2843
+ id: number;
2844
+ docid: string;
2845
+ uri: string;
2846
+ title: string | null;
2847
+ collection: string;
2848
+ relPath: string;
2849
+ mirrorHash: string;
2850
+ active: boolean;
2851
+ }>
2852
+ >
2853
+ > {
2854
+ if (options.documentIds.length === 0 && options.mirrorHashes.length === 0) {
2855
+ return ok([]);
2856
+ }
2857
+ try {
2858
+ const db = this.ensureOpen();
2859
+ const idsJson = JSON.stringify([...new Set(options.documentIds)]);
2860
+ const hashesJson = JSON.stringify([...new Set(options.mirrorHashes)]);
2861
+ const rows = options.collection
2862
+ ? db
2863
+ .query<
2864
+ {
2865
+ id: number;
2866
+ docid: string;
2867
+ uri: string;
2868
+ title: string | null;
2869
+ collection: string;
2870
+ rel_path: string;
2871
+ mirror_hash: string;
2872
+ },
2873
+ [string, string, string]
2874
+ >(
2875
+ `SELECT id, docid, uri, title, collection, rel_path, mirror_hash
2876
+ FROM documents
2877
+ WHERE active = 1
2878
+ AND mirror_hash IS NOT NULL
2879
+ AND collection = ?
2880
+ AND (
2881
+ id IN (SELECT value FROM json_each(?))
2882
+ OR mirror_hash IN (SELECT value FROM json_each(?))
2883
+ )
2884
+ ORDER BY id`
2885
+ )
2886
+ .all(options.collection, idsJson, hashesJson)
2887
+ : db
2888
+ .query<
2889
+ {
2890
+ id: number;
2891
+ docid: string;
2892
+ uri: string;
2893
+ title: string | null;
2894
+ collection: string;
2895
+ rel_path: string;
2896
+ mirror_hash: string;
2897
+ },
2898
+ [string, string]
2899
+ >(
2900
+ `SELECT id, docid, uri, title, collection, rel_path, mirror_hash
2901
+ FROM documents
2902
+ WHERE active = 1
2903
+ AND mirror_hash IS NOT NULL
2904
+ AND (
2905
+ id IN (SELECT value FROM json_each(?))
2906
+ OR mirror_hash IN (SELECT value FROM json_each(?))
2907
+ )
2908
+ ORDER BY id`
2909
+ )
2910
+ .all(idsJson, hashesJson);
2911
+
2912
+ return ok(
2913
+ rows.map((row) => ({
2914
+ id: row.id,
2915
+ docid: row.docid,
2916
+ uri: row.uri,
2917
+ title: row.title,
2918
+ collection: row.collection,
2919
+ relPath: row.rel_path,
2920
+ mirrorHash: row.mirror_hash,
2921
+ active: true,
2922
+ }))
2923
+ );
2924
+ } catch (cause) {
2925
+ return err(
2926
+ "QUERY_FAILED",
2927
+ cause instanceof Error
2928
+ ? cause.message
2929
+ : "Failed to load similarity documents",
2930
+ cause
2931
+ );
2932
+ }
2933
+ }
2934
+
2935
+ /**
2936
+ * Minimal-column SQL autocomplete search.
2937
+ * Selects only the 5 scalar columns needed for autocomplete (never hydrating
2938
+ * full DocumentRow blobs or parsing typedMetadata JSON). For non-empty
2939
+ * single-token ASCII queries, pushes an ASCII substring pre-filter into SQL
2940
+ * while still passing rows containing any non-ASCII character (so Unicode
2941
+ * case folding like `Kelvin` -> `kelvin` is never missed), then applies
2942
+ * exact JS display-title resolution, `.toLowerCase().includes()`,
2943
+ * `.localeCompare()` ordering, and `.slice(0, limit)`.
2944
+ */
2945
+ async searchDocumentsForAutocomplete(options: {
2946
+ query: string;
2947
+ collection?: string;
2948
+ limit: number;
2949
+ }): Promise<
2950
+ StoreResult<
2951
+ Array<{
2952
+ docid: string;
2953
+ uri: string;
2954
+ title: string;
2955
+ collection: string;
2956
+ }>
2957
+ >
2958
+ > {
2959
+ try {
2960
+ const db = this.ensureOpen();
2961
+ const query = options.query.trim().toLowerCase();
2962
+ // Preserve Array.prototype.slice(0, limit) semantics identically
2963
+ // (including fractional limits like 1.5 -> 1 and negative limits like -1).
2964
+ const sliceLimit = Math.min(options.limit, 20);
2965
+ if (sliceLimit === 0) {
2966
+ return ok([]);
2967
+ }
2968
+ const isAsciiSingleSegment =
2969
+ query.length > 0 && !/[^\x20-\x7f]/.test(query) && !query.includes(" ");
2970
+
2971
+ const resolveTitle = (title: string | null, relPath: string): string =>
2972
+ title ??
2973
+ relPath
2974
+ .split("/")
2975
+ .pop()
2976
+ ?.replace(/\.[^.]+$/, "") ??
2977
+ relPath;
2978
+
2979
+ type MinimalRow = {
2980
+ docid: string;
2981
+ uri: string;
2982
+ title: string | null;
2983
+ rel_path: string;
2984
+ collection: string;
2985
+ };
2986
+
2987
+ const conditions = ["active = 1"];
2988
+ const params: string[] = [];
2989
+ if (options.collection) {
2990
+ conditions.push("collection = ?");
2991
+ params.push(options.collection);
2992
+ }
2993
+ if (isAsciiSingleSegment) {
2994
+ // Pure-ASCII rows can only match if SQLite's ASCII lower() matches
2995
+ // title or uri (which includes rel_path); pass rows containing any
2996
+ // non-ASCII byte through so Unicode case folding matches identically.
2997
+ conditions.push(
2998
+ "(instr(lower(COALESCE(title, '')), ?) > 0 OR instr(lower(uri), ?) > 0 OR COALESCE(title, '') GLOB '*[^' || char(1) || '-' || char(127) || ']*' OR uri GLOB '*[^' || char(1) || '-' || char(127) || ']*')"
2999
+ );
3000
+ params.push(query, query);
3001
+ }
3002
+
3003
+ const rows = db
3004
+ .query<MinimalRow, string[]>(
3005
+ `SELECT docid, uri, title, rel_path, collection
3006
+ FROM documents
3007
+ WHERE ${conditions.join(" AND ")}`
3008
+ )
3009
+ .all(...params);
3010
+
3011
+ const candidates = rows
3012
+ .map((row) => ({
3013
+ docid: row.docid,
3014
+ uri: row.uri,
3015
+ title: resolveTitle(row.title, row.rel_path),
3016
+ collection: row.collection,
3017
+ }))
3018
+ .filter((doc) => {
3019
+ if (!query) return true;
3020
+ return `${doc.title} ${doc.uri}`.toLowerCase().includes(query);
3021
+ })
3022
+ .sort((a, b) => a.title.localeCompare(b.title))
3023
+ .slice(0, sliceLimit);
3024
+
3025
+ return ok(candidates);
3026
+ } catch (cause) {
3027
+ return err(
3028
+ "QUERY_FAILED",
3029
+ cause instanceof Error
3030
+ ? cause.message
3031
+ : "Failed to search autocomplete documents",
3032
+ cause
3033
+ );
3034
+ }
3035
+ }
3036
+
2683
3037
  async markInactive(
2684
3038
  collection: string,
2685
3039
  relPaths: string[]
@@ -2692,18 +3046,29 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2692
3046
  }
2693
3047
 
2694
3048
  const uniquePaths = [...new Set(relPaths)];
2695
- const placeholders = uniquePaths.map(() => "?").join(",");
3049
+ const pathsJson = JSON.stringify(uniquePaths);
2696
3050
  const transaction = db.transaction((): number => {
2697
3051
  const activeRows = db
2698
- .query<DbDocumentRow, (string | number)[]>(
2699
- `SELECT *
3052
+ .query<
3053
+ {
3054
+ id: number;
3055
+ collection: string;
3056
+ rel_path: string;
3057
+ docid: string;
3058
+ uri: string;
3059
+ source_hash: string;
3060
+ mirror_hash: string | null;
3061
+ },
3062
+ [string, string]
3063
+ >(
3064
+ `SELECT id, collection, rel_path, docid, uri, source_hash, mirror_hash
2700
3065
  FROM documents
2701
3066
  WHERE collection = ?
2702
3067
  AND active = 1
2703
- AND rel_path IN (${placeholders})
3068
+ AND rel_path IN (SELECT value FROM json_each(?))
2704
3069
  ORDER BY rel_path ASC, id ASC`
2705
3070
  )
2706
- .all(collection, ...uniquePaths);
3071
+ .all(collection, pathsJson);
2707
3072
  if (activeRows.length === 0) {
2708
3073
  return 0;
2709
3074
  }
@@ -2711,13 +3076,12 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2711
3076
  db,
2712
3077
  activeRows.map((row) => row.mirror_hash)
2713
3078
  );
2714
- db.run(
3079
+ db.query(
2715
3080
  `UPDATE documents SET active = 0, updated_at = datetime('now')
2716
3081
  WHERE collection = ?
2717
3082
  AND active = 1
2718
- AND rel_path IN (${placeholders})`,
2719
- [collection, ...uniquePaths]
2720
- );
3083
+ AND rel_path IN (SELECT value FROM json_each(?))`
3084
+ ).run(collection, pathsJson);
2721
3085
  // Bun run().changes includes trigger writes; report logical document rows.
2722
3086
  const changed =
2723
3087
  db.query<{ count: number }, []>("SELECT changes() AS count").get()
@@ -2725,7 +3089,16 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2725
3089
  reconcileLegacyTitles(db, legacyTitles);
2726
3090
  const observedAtMs = Date.now();
2727
3091
  for (const activeRow of activeRows) {
2728
- const previous = snapshotDocumentChange(mapDocumentRow(activeRow));
3092
+ const previous: DocumentChangeSnapshot = {
3093
+ id: activeRow.id,
3094
+ collection: activeRow.collection,
3095
+ relPath: activeRow.rel_path,
3096
+ docid: activeRow.docid,
3097
+ uri: activeRow.uri,
3098
+ sourceHash: activeRow.source_hash,
3099
+ mirrorHash: activeRow.mirror_hash,
3100
+ active: true,
3101
+ };
2729
3102
  appendStoredDocumentChange(db, {
2730
3103
  documentId: activeRow.id,
2731
3104
  collection,
@@ -2973,24 +3346,13 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
2973
3346
  }
2974
3347
 
2975
3348
  const result = new Map<string, string>();
2976
- for (
2977
- let offset = 0;
2978
- offset < uniqueHashes.length;
2979
- offset += SQLITE_SAFE_PARAMETER_BATCH_SIZE
2980
- ) {
2981
- const batch = uniqueHashes.slice(
2982
- offset,
2983
- offset + SQLITE_SAFE_PARAMETER_BATCH_SIZE
2984
- );
2985
- const placeholders = batch.map(() => "?").join(", ");
2986
- const rows = db
2987
- .query<DbContentRow, string[]>(
2988
- `SELECT mirror_hash, markdown FROM content
2989
- WHERE mirror_hash IN (${placeholders})`
2990
- )
2991
- .all(...batch);
2992
- for (const row of rows) result.set(row.mirror_hash, row.markdown);
2993
- }
3349
+ const rows = db
3350
+ .query<DbContentRow, [string]>(
3351
+ `SELECT mirror_hash, markdown FROM content
3352
+ WHERE mirror_hash IN (SELECT value FROM json_each(?))`
3353
+ )
3354
+ .all(JSON.stringify(uniqueHashes));
3355
+ for (const row of rows) result.set(row.mirror_hash, row.markdown);
2994
3356
 
2995
3357
  return ok(result);
2996
3358
  } catch (cause) {
@@ -3024,29 +3386,43 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3024
3386
  );
3025
3387
  // Retain stable rows: DELETE cascades erase valid legacy vectors even
3026
3388
  // when duplicate ingestion produces exactly the same embedding input.
3027
- const nextBySequence = new Map(
3028
- chunks.map((chunk) => [chunk.seq, chunk])
3029
- );
3030
3389
  const existing = db
3031
3390
  .query<{ seq: number; text: string }, [string]>(
3032
3391
  "SELECT seq, text FROM content_chunks WHERE mirror_hash = ?"
3033
3392
  )
3034
3393
  .all(mirrorHash);
3035
- for (const old of existing) {
3036
- const next = nextBySequence.get(old.seq);
3037
- if (!next || next.text !== old.text) {
3038
- db.run(
3039
- "DELETE FROM vector_owners WHERE mirror_hash = ? AND seq = ?",
3040
- [mirrorHash, old.seq]
3041
- );
3042
- db.run(
3043
- "DELETE FROM content_chunks WHERE mirror_hash = ? AND seq = ?",
3044
- [mirrorHash, old.seq]
3045
- );
3394
+ if (existing.length > 0) {
3395
+ const nextBySequence = new Map(
3396
+ chunks.map((chunk) => [chunk.seq, chunk])
3397
+ );
3398
+ const deleteOwner = db.query<unknown, [string, number]>(
3399
+ "DELETE FROM vector_owners WHERE mirror_hash = ? AND seq = ?"
3400
+ );
3401
+ const deleteChunk = db.query<unknown, [string, number]>(
3402
+ "DELETE FROM content_chunks WHERE mirror_hash = ? AND seq = ?"
3403
+ );
3404
+ for (const old of existing) {
3405
+ const next = nextBySequence.get(old.seq);
3406
+ if (!next || next.text !== old.text) {
3407
+ deleteOwner.run(mirrorHash, old.seq);
3408
+ deleteChunk.run(mirrorHash, old.seq);
3409
+ }
3046
3410
  }
3047
3411
  }
3048
3412
 
3049
- const stmt = db.prepare(`
3413
+ const stmt = db.query<
3414
+ unknown,
3415
+ [
3416
+ string,
3417
+ number,
3418
+ number,
3419
+ string,
3420
+ number,
3421
+ number,
3422
+ string | null,
3423
+ number | null,
3424
+ ]
3425
+ >(`
3050
3426
  INSERT INTO content_chunks (mirror_hash, seq, pos, text, start_line, end_line, language, token_count)
3051
3427
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
3052
3428
  ON CONFLICT(mirror_hash, seq) DO UPDATE SET
@@ -3192,32 +3568,20 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3192
3568
 
3193
3569
  const db = this.ensureOpen();
3194
3570
  const result = new Map<string, ChunkRow[]>();
3571
+ const rows = db
3572
+ .query<DbChunkRow, [string]>(
3573
+ `SELECT * FROM content_chunks
3574
+ WHERE mirror_hash IN (SELECT value FROM json_each(?))
3575
+ ORDER BY mirror_hash, seq`
3576
+ )
3577
+ .all(JSON.stringify(uniqueHashes));
3195
3578
 
3196
- // SQLite SQLITE_LIMIT_VARIABLE_NUMBER defaults to 999
3197
- // Reserve 99 for potential future filter params (collection, language, etc.)
3198
- // Batch queries to respect SQLite parameter limit
3199
- for (
3200
- let i = 0;
3201
- i < uniqueHashes.length;
3202
- i += SQLITE_SAFE_PARAMETER_BATCH_SIZE
3203
- ) {
3204
- const batch = uniqueHashes.slice(
3205
- i,
3206
- i + SQLITE_SAFE_PARAMETER_BATCH_SIZE
3207
- );
3208
- const placeholders = batch.map(() => "?").join(",");
3209
- const sql = `SELECT * FROM content_chunks
3210
- WHERE mirror_hash IN (${placeholders})
3211
- ORDER BY mirror_hash, seq`;
3212
- const rows = db.query<DbChunkRow, string[]>(sql).all(...batch);
3213
-
3214
- // Group by mirrorHash, preserving seq order from ORDER BY
3215
- for (const row of rows) {
3216
- const mapped = mapChunkRow(row);
3217
- const existing = result.get(mapped.mirrorHash) ?? [];
3218
- existing.push(mapped);
3219
- result.set(mapped.mirrorHash, existing);
3220
- }
3579
+ // Group by mirrorHash, preserving seq order from ORDER BY
3580
+ for (const row of rows) {
3581
+ const mapped = mapChunkRow(row);
3582
+ const existing = result.get(mapped.mirrorHash);
3583
+ if (existing) existing.push(mapped);
3584
+ else result.set(mapped.mirrorHash, [mapped]);
3221
3585
  }
3222
3586
 
3223
3587
  return ok(result);
@@ -3243,27 +3607,27 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3243
3607
  const result = new Map<string, ChunkRow[]>();
3244
3608
  if (pairs.length === 0) return ok(result);
3245
3609
  const db = this.ensureOpen();
3246
- const batchSize = Math.floor(SQLITE_SAFE_PARAMETER_BATCH_SIZE / 2);
3247
- for (let offset = 0; offset < pairs.length; offset += batchSize) {
3248
- const batch = pairs.slice(offset, offset + batchSize);
3249
- const values = batch.map(() => "(?, ?)").join(",");
3250
- const rows = db
3251
- .query<DbChunkRow, (string | number)[]>(`
3252
- WITH requested(mirror_hash, seq) AS (VALUES ${values})
3610
+ const rows = db
3611
+ .query<DbChunkRow, [string]>(`
3612
+ WITH requested AS (
3613
+ SELECT
3614
+ json_extract(value, '$[0]') AS mirror_hash,
3615
+ json_extract(value, '$[1]') AS seq
3616
+ FROM json_each(?)
3617
+ )
3253
3618
  SELECT c.* FROM requested r JOIN content_chunks c
3254
3619
  ON c.mirror_hash = r.mirror_hash AND c.seq = r.seq
3255
3620
  ORDER BY c.mirror_hash, c.seq
3256
3621
  `)
3257
- .all(...batch.flatMap(({ mirrorHash, seq }) => [mirrorHash, seq]));
3258
- for (const row of rows) {
3259
- const mapped = mapChunkRow(row);
3260
- const chunks = result.get(mapped.mirrorHash) ?? [];
3261
- chunks.push(mapped);
3262
- result.set(mapped.mirrorHash, chunks);
3263
- }
3622
+ .all(
3623
+ JSON.stringify(pairs.map(({ mirrorHash, seq }) => [mirrorHash, seq]))
3624
+ );
3625
+ for (const row of rows) {
3626
+ const mapped = mapChunkRow(row);
3627
+ const chunks = result.get(mapped.mirrorHash);
3628
+ if (chunks) chunks.push(mapped);
3629
+ else result.set(mapped.mirrorHash, [mapped]);
3264
3630
  }
3265
- for (const chunks of result.values())
3266
- chunks.sort((a, b) => a.seq - b.seq);
3267
3631
  return ok(result);
3268
3632
  } catch (cause) {
3269
3633
  return err(
@@ -3286,41 +3650,52 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3286
3650
  const uniqueHashes = uniqueNonEmptyValues(mirrorHashes);
3287
3651
  if (uniqueHashes.length === 0 || terms.length === 0) return ok([]);
3288
3652
  const db = this.ensureOpen();
3289
- // SQLite lower() folds ASCII only, so a non-ASCII term is also looked
3290
- // up in its upper-case and capitalized spellings (ÜBERBLICK, Überblick).
3291
- const spellings = terms.flatMap((term) => [
3292
- term,
3293
- term.toUpperCase(),
3294
- `${term.charAt(0).toUpperCase()}${term.slice(1)}`,
3295
- ]);
3653
+ // Compute lower(text) once per chunk in a derived table. SQLite lower()
3654
+ // folds ASCII only, so lowercase ASCII terms need only one instr(ltext, ?)
3655
+ // check, while non-ASCII or mixed-case terms check upper/capitalized too.
3656
+ const spellings: string[] = [];
3296
3657
  const columns = terms
3297
- .map(
3298
- () =>
3299
- "(instr(lower(text), ?) > 0 OR instr(text, ?) > 0 OR instr(text, ?) > 0)"
3300
- )
3658
+ .map((term) => {
3659
+ let isAscii = true;
3660
+ for (let i = 0; i < term.length; i++) {
3661
+ if (term.charCodeAt(i) > 0x7f) {
3662
+ isAscii = false;
3663
+ break;
3664
+ }
3665
+ }
3666
+ const isLowerAscii = isAscii && term === term.toLowerCase();
3667
+ if (isLowerAscii) {
3668
+ spellings.push(term);
3669
+ return "instr(ltext, ?) > 0";
3670
+ }
3671
+ spellings.push(
3672
+ term,
3673
+ term.toUpperCase(),
3674
+ `${term.charAt(0).toUpperCase()}${term.slice(1)}`
3675
+ );
3676
+ return "(instr(ltext, ?) > 0 OR instr(text, ?) > 0 OR instr(text, ?) > 0)";
3677
+ })
3301
3678
  .join(", ");
3302
- const batchSize = Math.max(
3303
- 1,
3304
- SQLITE_SAFE_PARAMETER_BATCH_SIZE - spellings.length
3305
- );
3679
+ const values = db
3680
+ .query<unknown, string[]>(
3681
+ `WITH scoped AS MATERIALIZED (
3682
+ SELECT mirror_hash, seq, text, lower(text) AS ltext
3683
+ FROM content_chunks
3684
+ WHERE mirror_hash IN (SELECT value FROM json_each(?))
3685
+ )
3686
+ SELECT mirror_hash, seq, ${columns}
3687
+ FROM scoped
3688
+ ORDER BY mirror_hash, seq`
3689
+ )
3690
+ .values(JSON.stringify(uniqueHashes), ...spellings) as unknown[][];
3306
3691
  const rows: { mirrorHash: string; seq: number; present: boolean[] }[] =
3307
3692
  [];
3308
- for (let i = 0; i < uniqueHashes.length; i += batchSize) {
3309
- const batch = uniqueHashes.slice(i, i + batchSize);
3310
- const values = db
3311
- .query<unknown, string[]>(
3312
- `SELECT mirror_hash, seq, ${columns} FROM content_chunks
3313
- WHERE mirror_hash IN (${batch.map(() => "?").join(",")})
3314
- ORDER BY mirror_hash, seq`
3315
- )
3316
- .values(...spellings, ...batch) as unknown[][];
3317
- for (const [mirrorHash, seq, ...present] of values) {
3318
- rows.push({
3319
- mirrorHash: String(mirrorHash),
3320
- seq: Number(seq),
3321
- present: present.map((flag) => flag === 1),
3322
- });
3323
- }
3693
+ for (const [mirrorHash, seq, ...present] of values) {
3694
+ rows.push({
3695
+ mirrorHash: String(mirrorHash),
3696
+ seq: Number(seq),
3697
+ present: present.map((flag) => flag === 1),
3698
+ });
3324
3699
  }
3325
3700
  return ok(rows);
3326
3701
  } catch (cause) {
@@ -3534,22 +3909,21 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3534
3909
  return; // Document not found or inactive
3535
3910
  }
3536
3911
 
3537
- // Delete existing FTS entry for this doc
3538
- db.run("DELETE FROM documents_fts WHERE rowid = ?", [doc.id]);
3539
- db.run("UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?", [
3540
- doc.id,
3541
- ]);
3912
+ // Delete existing FTS entry for this doc and update fts_mirror_hash once
3913
+ db.query("DELETE FROM documents_fts WHERE rowid = ?").run(doc.id);
3542
3914
 
3543
- // Insert new FTS entry if we have content
3544
3915
  if (doc.markdown !== null) {
3545
- db.run(
3546
- "INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)",
3547
- [doc.id, doc.rel_path, doc.title ?? "", doc.markdown]
3548
- );
3549
- db.run("UPDATE documents SET fts_mirror_hash = ? WHERE id = ?", [
3916
+ db.query(
3917
+ "INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)"
3918
+ ).run(doc.id, doc.rel_path, doc.title ?? "", doc.markdown);
3919
+ db.query("UPDATE documents SET fts_mirror_hash = ? WHERE id = ?").run(
3550
3920
  doc.mirror_hash,
3551
- doc.id,
3552
- ]);
3921
+ doc.id
3922
+ );
3923
+ } else {
3924
+ db.query(
3925
+ "UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?"
3926
+ ).run(doc.id);
3553
3927
  }
3554
3928
  });
3555
3929
 
@@ -3574,41 +3948,28 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3574
3948
  let count = 0;
3575
3949
 
3576
3950
  const transaction = db.transaction(() => {
3577
- // Clear FTS table
3578
- db.run("DELETE FROM documents_fts");
3579
- db.run("UPDATE documents SET fts_mirror_hash = NULL");
3580
-
3581
- // Get all active documents with content
3582
- interface DocWithContent {
3583
- id: number;
3584
- rel_path: string;
3585
- title: string | null;
3586
- mirror_hash: string;
3587
- markdown: string;
3588
- }
3589
-
3590
- const docs = db
3591
- .query<DocWithContent, []>(
3592
- `SELECT d.id, d.rel_path, d.title, d.mirror_hash, c.markdown
3593
- FROM documents d
3594
- JOIN content c ON c.mirror_hash = d.mirror_hash
3595
- WHERE d.active = 1 AND d.mirror_hash IS NOT NULL`
3596
- )
3597
- .all();
3598
-
3599
- // Insert FTS entries
3600
- const stmt = db.prepare(
3601
- "INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)"
3602
- );
3603
- const markSynced = db.prepare(
3604
- "UPDATE documents SET fts_mirror_hash = ? WHERE id = ?"
3951
+ // Clear FTS table and rebuild purely in SQL without loading bodies into JS
3952
+ db.exec("DELETE FROM documents_fts");
3953
+ db.exec("UPDATE documents SET fts_mirror_hash = NULL");
3954
+ db.query(
3955
+ `INSERT INTO documents_fts (rowid, filepath, title, body)
3956
+ SELECT d.id, d.rel_path, COALESCE(d.title, ''), c.markdown
3957
+ FROM documents d
3958
+ JOIN content c ON c.mirror_hash = d.mirror_hash
3959
+ WHERE d.active = 1 AND d.mirror_hash IS NOT NULL`
3960
+ ).run();
3961
+ count =
3962
+ db.query<{ count: number }, []>("SELECT changes() AS count").get()
3963
+ ?.count ?? 0;
3964
+ db.exec(
3965
+ `UPDATE documents
3966
+ SET fts_mirror_hash = mirror_hash
3967
+ WHERE active = 1
3968
+ AND mirror_hash IS NOT NULL
3969
+ AND EXISTS (
3970
+ SELECT 1 FROM content c WHERE c.mirror_hash = documents.mirror_hash
3971
+ )`
3605
3972
  );
3606
-
3607
- for (const doc of docs) {
3608
- stmt.run(doc.id, doc.rel_path, doc.title ?? "", doc.markdown);
3609
- markSynced.run(doc.mirror_hash, doc.id);
3610
- count++;
3611
- }
3612
3973
  });
3613
3974
 
3614
3975
  transaction();
@@ -3657,20 +4018,26 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3657
4018
  return;
3658
4019
  }
3659
4020
 
3660
- // Update FTS for each document using this hash
4021
+ const deleteFts = db.query<unknown, [number]>(
4022
+ "DELETE FROM documents_fts WHERE rowid = ?"
4023
+ );
4024
+ const insertFts = db.query<unknown, [number, string, string, string]>(
4025
+ "INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)"
4026
+ );
4027
+ const markSynced = db.query<unknown, [string, number]>(
4028
+ "UPDATE documents SET fts_mirror_hash = ? WHERE id = ?"
4029
+ );
4030
+
4031
+ // Update FTS for each document using this hash (single fts_mirror_hash update)
3661
4032
  for (const doc of docs) {
3662
- db.run("DELETE FROM documents_fts WHERE rowid = ?", [doc.id]);
3663
- db.run("UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?", [
4033
+ deleteFts.run(doc.id);
4034
+ insertFts.run(
3664
4035
  doc.id,
3665
- ]);
3666
- db.run(
3667
- "INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)",
3668
- [doc.id, doc.rel_path, doc.title ?? "", content.markdown]
4036
+ doc.rel_path,
4037
+ doc.title ?? "",
4038
+ content.markdown
3669
4039
  );
3670
- db.run("UPDATE documents SET fts_mirror_hash = ? WHERE id = ?", [
3671
- mirrorHash,
3672
- doc.id,
3673
- ]);
4040
+ markSynced.run(mirrorHash, doc.id);
3674
4041
  }
3675
4042
  });
3676
4043
 
@@ -3789,24 +4156,49 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3789
4156
  if (options.scopes.length === 0) {
3790
4157
  return ok([]);
3791
4158
  }
3792
- const placeholders = options.scopes.map(() => "?").join(",");
3793
- const rows = db
3794
- .query<
3795
- { id: number; docid: string; uri: string; mirror_hash: string },
3796
- string[]
3797
- >(
4159
+ const limit =
4160
+ options.limit !== undefined &&
4161
+ Number.isSafeInteger(options.limit) &&
4162
+ options.limit > 0
4163
+ ? options.limit
4164
+ : null;
4165
+ const rows =
4166
+ limit !== null
4167
+ ? db
4168
+ .query<
4169
+ { id: number; docid: string; uri: string; mirror_hash: string },
4170
+ [string, string, number]
4171
+ >(
4172
+ `
4173
+ SELECT d.id, d.docid, d.uri, d.mirror_hash
4174
+ FROM documents d
4175
+ WHERE d.active = 1
4176
+ AND d.collection = ?
4177
+ AND d.mirror_hash IS NOT NULL
4178
+ AND EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (SELECT value FROM json_each(?)))
4179
+ ${options.excludeSuperseded ? SUPERSEDED_EXCLUSION_SQL("d.id") : ""}
4180
+ ORDER BY d.id
4181
+ LIMIT ?
3798
4182
  `
4183
+ )
4184
+ .all(options.collection, JSON.stringify(options.scopes), limit)
4185
+ : db
4186
+ .query<
4187
+ { id: number; docid: string; uri: string; mirror_hash: string },
4188
+ [string, string]
4189
+ >(
4190
+ `
3799
4191
  SELECT d.id, d.docid, d.uri, d.mirror_hash
3800
4192
  FROM documents d
3801
4193
  WHERE d.active = 1
3802
4194
  AND d.collection = ?
3803
4195
  AND d.mirror_hash IS NOT NULL
3804
- AND EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (${placeholders}))
4196
+ AND EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (SELECT value FROM json_each(?)))
3805
4197
  ${options.excludeSuperseded ? SUPERSEDED_EXCLUSION_SQL("d.id") : ""}
3806
4198
  ORDER BY d.id
3807
4199
  `
3808
- )
3809
- .all(options.collection, ...options.scopes);
4200
+ )
4201
+ .all(options.collection, JSON.stringify(options.scopes));
3810
4202
  return ok(
3811
4203
  rows.map((row) => ({
3812
4204
  id: row.id,
@@ -3876,14 +4268,12 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3876
4268
  source: "frontmatter" | "user";
3877
4269
  }
3878
4270
 
3879
- // Use parameterized IN clause to prevent SQL injection
3880
- const placeholders = documentIds.map(() => "?").join(", ");
3881
4271
  const rows = db
3882
- .query<DbTagRow, number[]>(
4272
+ .query<DbTagRow, [string]>(
3883
4273
  `SELECT document_id, tag, source FROM doc_tags
3884
- WHERE document_id IN (${placeholders}) ORDER BY document_id, tag`
4274
+ WHERE document_id IN (SELECT value FROM json_each(?)) ORDER BY document_id, tag`
3885
4275
  )
3886
- .all(...documentIds);
4276
+ .all(JSON.stringify(documentIds));
3887
4277
 
3888
4278
  // Group by document_id
3889
4279
  const result = new Map<number, TagRow[]>();
@@ -3996,7 +4386,7 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
3996
4386
 
3997
4387
  const params: (string | number)[] = [];
3998
4388
  let sql = `
3999
- SELECT dt.tag, COUNT(DISTINCT dt.document_id) as count
4389
+ SELECT dt.tag, COUNT(*) as count
4000
4390
  FROM doc_tags dt
4001
4391
  JOIN documents d ON d.id = dt.document_id AND d.active = 1
4002
4392
  `;
@@ -4262,9 +4652,12 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
4262
4652
  const sourceScopeSql = sourceAllowlist
4263
4653
  ? sourceAllowlist.length === 0
4264
4654
  ? "AND 0"
4265
- : `AND src.collection IN (${sourceAllowlist.map(() => "?").join(",")})`
4655
+ : "AND src.collection IN (SELECT value FROM json_each(?))"
4266
4656
  : "";
4267
- const sourceScopeParams = sourceAllowlist ?? [];
4657
+ const sourceScopeParams =
4658
+ sourceAllowlist && sourceAllowlist.length > 0
4659
+ ? [JSON.stringify(sourceAllowlist)]
4660
+ : [];
4268
4661
  const backlinkColumns = `dl.id AS link_id, dl.source_doc_id, src.docid,
4269
4662
  src.uri, src.title, src.collection AS source_collection,
4270
4663
  src.rel_path AS source_rel_path, dl.target_ref_norm,
@@ -4349,21 +4742,21 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
4349
4742
  JOIN documents src ON src.id = dl.source_doc_id AND src.active = 1
4350
4743
  WHERE dl.link_type = 'wiki'
4351
4744
  AND dl.target_collection IS NULL
4352
- AND src.collection IN (${members.map(() => "?").join(",")})
4745
+ AND src.collection IN (SELECT value FROM json_each(?))
4353
4746
  AND (dl.target_ref_norm IN (?, ?)
4354
4747
  OR dl.target_ref_norm LIKE ? ESCAPE '\\'
4355
4748
  OR dl.target_ref_norm LIKE ? ESCAPE '\\'
4356
- OR dl.target_ref_norm IN (${[...keySet].map(() => "?").join(",") || "NULL"}))
4749
+ OR dl.target_ref_norm IN (SELECT value FROM json_each(?)))
4357
4750
  ${sourceScopeSql}
4358
4751
  ORDER BY src.uri, dl.start_line, dl.start_col`
4359
4752
  )
4360
4753
  .all(
4361
- ...members,
4754
+ JSON.stringify(members),
4362
4755
  base,
4363
4756
  `${base}.md`,
4364
4757
  `%/${escapeLike(base)}`,
4365
4758
  `%/${escapeLike(`${base}.md`)}`,
4366
- ...keySet,
4759
+ JSON.stringify([...keySet]),
4367
4760
  ...sourceScopeParams
4368
4761
  )
4369
4762
  );
@@ -4373,40 +4766,53 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
4373
4766
  for (const row of [...wikiBacklinks, ...workspaceBacklinks]) {
4374
4767
  candidates.set(row.link_id, row);
4375
4768
  }
4376
- const candidateRows = [...candidates.values()];
4377
- const resolutions = resolveGraphLinkTargets(
4378
- db,
4379
- candidateRows.map((row) => ({
4380
- targetRefNorm: row.target_ref_norm,
4381
- targetCollection: row.target_collection ?? row.source_collection,
4382
- linkType: "wiki" as const,
4383
- source: linkSourceIdentity(row),
4384
- }))
4385
- );
4386
4769
  const legacyLinkIds = new Set(wikiBacklinks.map((row) => row.link_id));
4387
- const resolvedWikiBacklinks = candidateRows
4388
- .filter((row, index) => {
4389
- const workspaceLink =
4390
- !row.target_collection &&
4391
- workspaceKeyForDocument(
4392
- memberships,
4393
- row.source_collection,
4394
- row.source_rel_path
4395
- ) !== null;
4396
- // Collection-scoped links keep their key-match semantics.
4397
- if (!workspaceLink) return legacyLinkIds.has(row.link_id);
4398
- const resolution = resolutions[index];
4399
- return (
4770
+ const directWikiBacklinks: DbBacklinkRow[] = [];
4771
+ const workspaceCandidateRows: DbBacklinkRow[] = [];
4772
+ for (const row of candidates.values()) {
4773
+ const workspaceLink =
4774
+ !row.target_collection &&
4775
+ workspaceKeyForDocument(
4776
+ memberships,
4777
+ row.source_collection,
4778
+ row.source_rel_path
4779
+ ) !== null;
4780
+ if (workspaceLink) {
4781
+ workspaceCandidateRows.push(row);
4782
+ } else if (legacyLinkIds.has(row.link_id)) {
4783
+ directWikiBacklinks.push(row);
4784
+ }
4785
+ }
4786
+ const resolvedWorkspaceBacklinks: DbBacklinkRow[] = [];
4787
+ if (workspaceCandidateRows.length > 0) {
4788
+ const resolutions = resolveGraphLinkTargets(
4789
+ db,
4790
+ workspaceCandidateRows.map((row) => ({
4791
+ targetRefNorm: row.target_ref_norm,
4792
+ targetCollection: row.target_collection ?? row.source_collection,
4793
+ linkType: "wiki" as const,
4794
+ source: linkSourceIdentity(row),
4795
+ }))
4796
+ );
4797
+ for (let i = 0; i < workspaceCandidateRows.length; i++) {
4798
+ const resolution = resolutions[i];
4799
+ if (
4400
4800
  isTraversableResolution(resolution) &&
4401
4801
  resolution.targetId === documentId
4402
- );
4403
- })
4404
- .sort(
4405
- (left, right) =>
4406
- (left.uri < right.uri ? -1 : left.uri > right.uri ? 1 : 0) ||
4407
- left.start_line - right.start_line ||
4408
- left.start_col - right.start_col
4409
- );
4802
+ ) {
4803
+ resolvedWorkspaceBacklinks.push(workspaceCandidateRows[i]!);
4804
+ }
4805
+ }
4806
+ }
4807
+ const resolvedWikiBacklinks = [
4808
+ ...directWikiBacklinks,
4809
+ ...resolvedWorkspaceBacklinks,
4810
+ ].sort(
4811
+ (left, right) =>
4812
+ (left.uri < right.uri ? -1 : left.uri > right.uri ? 1 : 0) ||
4813
+ left.start_line - right.start_line ||
4814
+ left.start_col - right.start_col
4815
+ );
4410
4816
 
4411
4817
  // Query markdown backlinks (link_type='markdown')
4412
4818
  // NULL target_collection means "same collection as source" - enforce this in SQL
@@ -4487,8 +4893,7 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
4487
4893
  number,
4488
4894
  { docid: string; uri: string; title: string | null; collection: string }
4489
4895
  >();
4490
- for (let offset = 0; offset < ids.length; offset += 900) {
4491
- const batch = ids.slice(offset, offset + 900);
4896
+ if (ids.length > 0) {
4492
4897
  for (const row of db
4493
4898
  .query<
4494
4899
  {
@@ -4498,11 +4903,11 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
4498
4903
  title: string | null;
4499
4904
  collection: string;
4500
4905
  },
4501
- number[]
4906
+ [string]
4502
4907
  >(
4503
- `SELECT id, docid, uri, title, collection FROM documents WHERE id IN (${batch.map(() => "?").join(",")})`
4908
+ "SELECT id, docid, uri, title, collection FROM documents WHERE id IN (SELECT value FROM json_each(?))"
4504
4909
  )
4505
- .all(...batch)) {
4910
+ .all(JSON.stringify(ids))) {
4506
4911
  byId.set(row.id, {
4507
4912
  docid: row.docid,
4508
4913
  uri: row.uri,
@@ -4752,144 +5157,118 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
4752
5157
 
4753
5158
  const referrers: FileRefactorResolutionReferrerDocument[] = [];
4754
5159
  let totalContentChars = sourceContent?.length ?? 0;
5160
+ const boundedCandidateIds = sortedCandidateIds.slice(0, maxReferrers);
4755
5161
 
4756
- for (const referrerId of sortedCandidateIds.slice(0, maxReferrers)) {
4757
- const referrerRow = db
4758
- .query<
4759
- {
4760
- id: number;
4761
- uri: string;
4762
- rel_path: string;
4763
- collection: string;
4764
- title: string | null;
4765
- mirror_hash: string | null;
4766
- source_ext: string;
4767
- source_mime: string;
4768
- record_key: string | null;
4769
- },
4770
- [number]
4771
- >(
4772
- `SELECT id, uri, rel_path, collection, title, mirror_hash,
4773
- source_ext, source_mime, record_key
4774
- FROM documents
4775
- WHERE id = ? AND active = 1`
4776
- )
4777
- .get(referrerId);
4778
- if (!referrerRow) continue;
4779
-
4780
- const caps = getDocumentCapabilities({
4781
- sourceExt: referrerRow.source_ext,
4782
- sourceMime: referrerRow.source_mime,
4783
- contentAvailable: Boolean(referrerRow.mirror_hash),
4784
- recordKey: referrerRow.record_key,
4785
- });
4786
-
4787
- if (!referrerRow.mirror_hash) {
4788
- truncationReasons.push("referrer_content_missing");
4789
- referrers.push({
4790
- id: referrerRow.id,
4791
- uri: referrerRow.uri,
4792
- relPath: referrerRow.rel_path,
4793
- collection: referrerRow.collection,
4794
- title: referrerRow.title,
4795
- content: null,
4796
- contentTruncated: false,
4797
- contentMissing: true,
4798
- editable: caps.editable,
4799
- editableReason: caps.editable
4800
- ? undefined
4801
- : caps.reason
4802
- ? "read_only_document"
4803
- : "capability_denied",
4804
- sourceExt: referrerRow.source_ext,
4805
- sourceMime: referrerRow.source_mime,
4806
- recordKey: referrerRow.record_key,
4807
- });
4808
- continue;
5162
+ if (boundedCandidateIds.length > 0) {
5163
+ interface ReferrerJoinedRow {
5164
+ id: number;
5165
+ uri: string;
5166
+ rel_path: string;
5167
+ collection: string;
5168
+ title: string | null;
5169
+ mirror_hash: string | null;
5170
+ source_ext: string;
5171
+ source_mime: string;
5172
+ record_key: string | null;
5173
+ markdown: string | null;
5174
+ has_content: number;
4809
5175
  }
4810
-
4811
- const contentRow = db
4812
- .query<{ markdown: string }, [number, string]>(
4813
- `SELECT substr(markdown, 1, ?) AS markdown
4814
- FROM content WHERE mirror_hash = ?`
4815
- )
4816
- .get(maxChars + 1, referrerRow.mirror_hash);
4817
-
4818
- if (!contentRow) {
4819
- truncationReasons.push("referrer_content_missing");
4820
- referrers.push({
4821
- id: referrerRow.id,
4822
- uri: referrerRow.uri,
4823
- relPath: referrerRow.rel_path,
4824
- collection: referrerRow.collection,
4825
- title: referrerRow.title,
4826
- content: null,
4827
- contentTruncated: false,
4828
- contentMissing: true,
4829
- editable: caps.editable,
4830
- editableReason: caps.editable
5176
+ const referrerStmt = db.prepare<ReferrerJoinedRow, [number, string]>(
5177
+ `SELECT d.id, d.uri, d.rel_path, d.collection, d.title, d.mirror_hash,
5178
+ d.source_ext, d.source_mime, d.record_key,
5179
+ substr(c.markdown, 1, ?) AS markdown,
5180
+ CASE WHEN c.mirror_hash IS NOT NULL THEN 1 ELSE 0 END AS has_content
5181
+ FROM documents d
5182
+ LEFT JOIN content c ON c.mirror_hash = d.mirror_hash
5183
+ WHERE d.active = 1
5184
+ AND d.id IN (SELECT value FROM json_each(?))
5185
+ ORDER BY d.id ASC`
5186
+ );
5187
+ try {
5188
+ for (const referrerRow of referrerStmt.iterate(
5189
+ maxChars + 1,
5190
+ JSON.stringify(boundedCandidateIds)
5191
+ )) {
5192
+ const caps = getDocumentCapabilities({
5193
+ sourceExt: referrerRow.source_ext,
5194
+ sourceMime: referrerRow.source_mime,
5195
+ contentAvailable: Boolean(referrerRow.mirror_hash),
5196
+ recordKey: referrerRow.record_key,
5197
+ });
5198
+ const editableReason = caps.editable
4831
5199
  ? undefined
4832
5200
  : caps.reason
4833
- ? "read_only_document"
4834
- : "capability_denied",
4835
- sourceExt: referrerRow.source_ext,
4836
- sourceMime: referrerRow.source_mime,
4837
- recordKey: referrerRow.record_key,
4838
- });
4839
- continue;
4840
- }
5201
+ ? ("read_only_document" as const)
5202
+ : ("capability_denied" as const);
5203
+
5204
+ if (!referrerRow.mirror_hash || referrerRow.has_content !== 1) {
5205
+ truncationReasons.push("referrer_content_missing");
5206
+ referrers.push({
5207
+ id: referrerRow.id,
5208
+ uri: referrerRow.uri,
5209
+ relPath: referrerRow.rel_path,
5210
+ collection: referrerRow.collection,
5211
+ title: referrerRow.title,
5212
+ content: null,
5213
+ contentTruncated: false,
5214
+ contentMissing: true,
5215
+ editable: caps.editable,
5216
+ editableReason,
5217
+ sourceExt: referrerRow.source_ext,
5218
+ sourceMime: referrerRow.source_mime,
5219
+ recordKey: referrerRow.record_key,
5220
+ });
5221
+ continue;
5222
+ }
4841
5223
 
4842
- const contentTruncated = contentRow.markdown.length > maxChars;
4843
- if (contentTruncated) {
4844
- truncationReasons.push("referrer_content_truncated");
4845
- }
4846
- const content = contentTruncated
4847
- ? contentRow.markdown.slice(0, maxChars)
4848
- : contentRow.markdown;
4849
- totalContentChars += content.length;
4850
- if (totalContentChars > maxTotalChars) {
4851
- truncationReasons.push("total_content_truncated");
4852
- referrers.push({
4853
- id: referrerRow.id,
4854
- uri: referrerRow.uri,
4855
- relPath: referrerRow.rel_path,
4856
- collection: referrerRow.collection,
4857
- title: referrerRow.title,
4858
- content: null,
4859
- contentTruncated: false,
4860
- contentMissing: true,
4861
- editable: caps.editable,
4862
- editableReason: caps.editable
4863
- ? undefined
4864
- : caps.reason
4865
- ? "read_only_document"
4866
- : "capability_denied",
4867
- sourceExt: referrerRow.source_ext,
4868
- sourceMime: referrerRow.source_mime,
4869
- recordKey: referrerRow.record_key,
4870
- });
4871
- continue;
4872
- }
5224
+ const rawMarkdown = referrerRow.markdown ?? "";
5225
+ const contentTruncated = rawMarkdown.length > maxChars;
5226
+ if (contentTruncated) {
5227
+ truncationReasons.push("referrer_content_truncated");
5228
+ }
5229
+ const content = contentTruncated
5230
+ ? rawMarkdown.slice(0, maxChars)
5231
+ : rawMarkdown;
5232
+ totalContentChars += content.length;
5233
+ if (totalContentChars > maxTotalChars) {
5234
+ truncationReasons.push("total_content_truncated");
5235
+ referrers.push({
5236
+ id: referrerRow.id,
5237
+ uri: referrerRow.uri,
5238
+ relPath: referrerRow.rel_path,
5239
+ collection: referrerRow.collection,
5240
+ title: referrerRow.title,
5241
+ content: null,
5242
+ contentTruncated: false,
5243
+ contentMissing: true,
5244
+ editable: caps.editable,
5245
+ editableReason,
5246
+ sourceExt: referrerRow.source_ext,
5247
+ sourceMime: referrerRow.source_mime,
5248
+ recordKey: referrerRow.record_key,
5249
+ });
5250
+ continue;
5251
+ }
4873
5252
 
4874
- referrers.push({
4875
- id: referrerRow.id,
4876
- uri: referrerRow.uri,
4877
- relPath: referrerRow.rel_path,
4878
- collection: referrerRow.collection,
4879
- title: referrerRow.title,
4880
- content,
4881
- contentTruncated,
4882
- contentMissing: false,
4883
- editable: caps.editable,
4884
- editableReason: caps.editable
4885
- ? undefined
4886
- : caps.reason
4887
- ? "read_only_document"
4888
- : "capability_denied",
4889
- sourceExt: referrerRow.source_ext,
4890
- sourceMime: referrerRow.source_mime,
4891
- recordKey: referrerRow.record_key,
4892
- });
5253
+ referrers.push({
5254
+ id: referrerRow.id,
5255
+ uri: referrerRow.uri,
5256
+ relPath: referrerRow.rel_path,
5257
+ collection: referrerRow.collection,
5258
+ title: referrerRow.title,
5259
+ content,
5260
+ contentTruncated,
5261
+ contentMissing: false,
5262
+ editable: caps.editable,
5263
+ editableReason,
5264
+ sourceExt: referrerRow.source_ext,
5265
+ sourceMime: referrerRow.source_mime,
5266
+ recordKey: referrerRow.record_key,
5267
+ });
5268
+ }
5269
+ } finally {
5270
+ referrerStmt.finalize();
5271
+ }
4893
5272
  }
4894
5273
 
4895
5274
  const snapshot: FileRefactorResolutionSnapshot = {
@@ -5898,16 +6277,17 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
5898
6277
  }
5899
6278
 
5900
6279
  const connectedIdList = [...connectedNodeIds].sort((a, b) => a - b);
6280
+ const connectedIdsJson =
6281
+ connectedIdList.length > 0 ? JSON.stringify(connectedIdList) : null;
5901
6282
  const connectedMetaMap = new Map<number, NodeMetaRow>();
5902
- if (connectedIdList.length > 0) {
5903
- const placeholders = connectedIdList.map(() => "?").join(",");
6283
+ if (connectedIdsJson) {
5904
6284
  const connectedRows = db
5905
- .query<NodeMetaRow, number[]>(
6285
+ .query<NodeMetaRow, [string]>(
5906
6286
  `SELECT id, docid, uri, title, collection, rel_path
5907
6287
  FROM documents
5908
- WHERE id IN (${placeholders})`
6288
+ WHERE id IN (SELECT value FROM json_each(?))`
5909
6289
  )
5910
- .all(...connectedIdList);
6290
+ .all(connectedIdsJson);
5911
6291
  for (const row of connectedRows) {
5912
6292
  connectedMetaMap.set(row.id, row);
5913
6293
  }
@@ -5946,10 +6326,11 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
5946
6326
  isolatedBaseConditions.push("collection = ?");
5947
6327
  isolatedBaseParams.push(collection);
5948
6328
  }
5949
- if (connectedIdList.length > 0) {
5950
- const placeholders = connectedIdList.map(() => "?").join(",");
5951
- isolatedBaseConditions.push(`id NOT IN (${placeholders})`);
5952
- isolatedBaseParams.push(...connectedIdList);
6329
+ if (connectedIdsJson) {
6330
+ isolatedBaseConditions.push(
6331
+ "id NOT IN (SELECT value FROM json_each(?))"
6332
+ );
6333
+ isolatedBaseParams.push(connectedIdsJson);
5953
6334
  }
5954
6335
  const isolatedWhereClause = isolatedBaseConditions.join(" AND ");
5955
6336
  const isolatedCountRow = db
@@ -5998,9 +6379,8 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
5998
6379
  isolatedParams.push(collection);
5999
6380
  }
6000
6381
  if (excluded.length > 0) {
6001
- const placeholders = excluded.map(() => "?").join(",");
6002
- conditions.push(`id NOT IN (${placeholders})`);
6003
- isolatedParams.push(...excluded);
6382
+ conditions.push("id NOT IN (SELECT value FROM json_each(?))");
6383
+ isolatedParams.push(JSON.stringify(excluded));
6004
6384
  }
6005
6385
  isolatedParams.push(remaining);
6006
6386
 
@@ -6296,7 +6676,67 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
6296
6676
  .replace(SQLITE_EXT_REGEX, "")
6297
6677
  .replace(INDEX_PREFIX_REGEX, "") || "default";
6298
6678
 
6299
- // Get collection stats with chunk counts
6679
+ // Single pass over `documents` gathers per-collection counts, configured
6680
+ // totals, global lastUpdatedAt, and global typed-metadata coverage.
6681
+ interface DocumentAggregateRow {
6682
+ collection: string;
6683
+ total: number;
6684
+ active: number;
6685
+ errored: number;
6686
+ chunked: number;
6687
+ last_updated: string | null;
6688
+ meta_pending: number;
6689
+ meta_invalid: number;
6690
+ }
6691
+ const docAggregateRows = db
6692
+ .query<DocumentAggregateRow, []>(
6693
+ `
6694
+ SELECT
6695
+ collection,
6696
+ COUNT(*) AS total,
6697
+ SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) AS active,
6698
+ SUM(CASE WHEN last_error_code IS NOT NULL THEN 1 ELSE 0 END) AS errored,
6699
+ SUM(CASE WHEN mirror_hash IS NOT NULL THEN 1 ELSE 0 END) AS chunked,
6700
+ strftime('%Y-%m-%dT%H:%M:%fZ', MAX(updated_at)) AS last_updated,
6701
+ SUM(CASE WHEN active = 1 AND mirror_hash IS NOT NULL AND (
6702
+ ingest_version IS NULL OR ingest_version < ${TYPED_METADATA_INGEST_VERSION}
6703
+ OR (typed_metadata IS NULL AND metadata_error IS NULL)
6704
+ ) THEN 1 ELSE 0 END) AS meta_pending,
6705
+ SUM(CASE WHEN active = 1 AND mirror_hash IS NOT NULL AND metadata_error IS NOT NULL
6706
+ THEN 1 ELSE 0 END) AS meta_invalid
6707
+ FROM documents
6708
+ GROUP BY collection
6709
+ `
6710
+ )
6711
+ .all();
6712
+
6713
+ const configuredSet = options?.configuredCollections
6714
+ ? new Set(options.configuredCollections)
6715
+ : null;
6716
+ const docStatsByCollection = new Map<string, DocumentAggregateRow>();
6717
+ let totalDocuments = 0;
6718
+ let activeDocuments = 0;
6719
+ let lastUpdatedAt: string | null = null;
6720
+ let metaPending = 0;
6721
+ let metaInvalid = 0;
6722
+ for (const row of docAggregateRows) {
6723
+ docStatsByCollection.set(row.collection, row);
6724
+ if (!configuredSet || configuredSet.has(row.collection)) {
6725
+ totalDocuments += row.total;
6726
+ activeDocuments += row.active;
6727
+ }
6728
+ if (
6729
+ row.last_updated !== null &&
6730
+ (lastUpdatedAt === null || row.last_updated > lastUpdatedAt)
6731
+ ) {
6732
+ lastUpdatedAt = row.last_updated;
6733
+ }
6734
+ metaPending += row.meta_pending;
6735
+ metaInvalid += row.meta_invalid;
6736
+ }
6737
+
6738
+ // Get collection metadata + chunk counts; skip legacy vector scans when
6739
+ // variantStatus is authoritative.
6300
6740
  interface CollectionStat {
6301
6741
  name: string;
6302
6742
  path: string;
@@ -6304,107 +6744,104 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
6304
6744
  egress_policy_source: EgressPolicySource;
6305
6745
  workspace_root: string | null;
6306
6746
  workspace_source: LinkWorkspaceSource | null;
6307
- total: number;
6308
- active: number;
6309
- errored: number;
6310
- chunked: number;
6311
6747
  chunk_count: number;
6312
6748
  embedded_count: number;
6313
6749
  }
6314
6750
 
6315
- const collectionStats = db
6316
- .query<
6317
- CollectionStat,
6318
- [
6319
- string | null,
6320
- string | null,
6321
- string | null,
6322
- string | null,
6323
- string | null,
6324
- ]
6325
- >(
6326
- `
6327
- WITH document_stats AS (
6328
- SELECT
6329
- collection,
6330
- COUNT(*) AS total,
6331
- SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) AS active,
6332
- SUM(CASE WHEN last_error_code IS NOT NULL THEN 1 ELSE 0 END) AS errored,
6333
- SUM(CASE WHEN mirror_hash IS NOT NULL THEN 1 ELSE 0 END) AS chunked
6334
- FROM documents
6335
- GROUP BY collection
6336
- ),
6337
- active_collection_mirrors AS (
6338
- SELECT DISTINCT collection, mirror_hash
6339
- FROM documents
6340
- WHERE active = 1 AND mirror_hash IS NOT NULL
6341
- ),
6342
- matching_vectors AS (
6343
- SELECT mirror_hash, seq, MAX(embedded_at) AS embedded_at
6344
- FROM content_vectors
6345
- WHERE (? IS NULL OR (
6346
- model = ? AND embed_fingerprint = ?
6347
- ))
6348
- GROUP BY mirror_hash, seq
6349
- ),
6350
- collection_chunks AS (
6351
- SELECT
6352
- acm.collection,
6353
- COUNT(*) AS chunk_count,
6354
- SUM(CASE
6355
- WHEN mv.embedded_at >= cc.created_at THEN 1
6356
- ELSE 0
6357
- END) AS embedded_count
6358
- FROM active_collection_mirrors acm
6359
- JOIN content_chunks cc ON cc.mirror_hash = acm.mirror_hash
6360
- LEFT JOIN matching_vectors mv
6361
- ON mv.mirror_hash = cc.mirror_hash AND mv.seq = cc.seq
6362
- GROUP BY acm.collection
6363
- )
6364
- SELECT
6365
- c.name,
6366
- c.path,
6367
- c.egress_policy,
6368
- c.egress_policy_source,
6369
- c.workspace_root,
6370
- c.workspace_source,
6371
- COALESCE(ds.total, 0) AS total,
6372
- COALESCE(ds.active, 0) AS active,
6373
- COALESCE(ds.errored, 0) AS errored,
6374
- COALESCE(ds.chunked, 0) AS chunked,
6375
- COALESCE(ch.chunk_count, 0) AS chunk_count,
6376
- COALESCE(ch.embedded_count, 0) AS embedded_count
6377
- FROM collections c
6378
- LEFT JOIN document_stats ds ON ds.collection = c.name
6379
- LEFT JOIN collection_chunks ch ON ch.collection = c.name
6380
- WHERE ? IS NULL OR c.name IN (SELECT value FROM json_each(?))
6381
- ORDER BY c.name
6382
- `
6383
- )
6384
- .all(
6385
- embedModel,
6386
- embedModel,
6387
- embedFingerprint,
6388
- configuredJson,
6389
- configuredJson
6390
- );
6391
-
6392
- // Totals cover the configured collections only, so a collection removed
6393
- // from config stops counting before the next update prunes its rows.
6394
- const totalsRow = db
6395
- .query<
6396
- { total: number; active: number },
6397
- [string | null, string | null]
6398
- >(
6399
- `
6400
- SELECT
6401
- COUNT(*) as total,
6402
- SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) as active
6403
- FROM documents
6404
- WHERE ? IS NULL OR collection IN (SELECT value FROM json_each(?))
6405
- `
6406
- )
6407
- .get(configuredJson, configuredJson);
6751
+ const collectionStats = variantStatus
6752
+ ? db
6753
+ .query<CollectionStat, [string | null, string | null]>(
6754
+ `
6755
+ WITH active_collection_mirrors AS (
6756
+ SELECT DISTINCT collection, mirror_hash
6757
+ FROM documents
6758
+ WHERE active = 1 AND mirror_hash IS NOT NULL
6759
+ ),
6760
+ collection_chunks AS (
6761
+ SELECT
6762
+ acm.collection,
6763
+ COUNT(*) AS chunk_count
6764
+ FROM active_collection_mirrors acm
6765
+ JOIN content_chunks cc ON cc.mirror_hash = acm.mirror_hash
6766
+ GROUP BY acm.collection
6767
+ )
6768
+ SELECT
6769
+ c.name,
6770
+ c.path,
6771
+ c.egress_policy,
6772
+ c.egress_policy_source,
6773
+ c.workspace_root,
6774
+ c.workspace_source,
6775
+ COALESCE(ch.chunk_count, 0) AS chunk_count,
6776
+ 0 AS embedded_count
6777
+ FROM collections c
6778
+ LEFT JOIN collection_chunks ch ON ch.collection = c.name
6779
+ WHERE ? IS NULL OR c.name IN (SELECT value FROM json_each(?))
6780
+ ORDER BY c.name
6781
+ `
6782
+ )
6783
+ .all(configuredJson, configuredJson)
6784
+ : db
6785
+ .query<
6786
+ CollectionStat,
6787
+ [
6788
+ string | null,
6789
+ string | null,
6790
+ string | null,
6791
+ string | null,
6792
+ string | null,
6793
+ ]
6794
+ >(
6795
+ `
6796
+ WITH active_collection_mirrors AS (
6797
+ SELECT DISTINCT collection, mirror_hash
6798
+ FROM documents
6799
+ WHERE active = 1 AND mirror_hash IS NOT NULL
6800
+ ),
6801
+ matching_vectors AS (
6802
+ SELECT mirror_hash, seq, MAX(embedded_at) AS embedded_at
6803
+ FROM content_vectors
6804
+ WHERE (? IS NULL OR (
6805
+ model = ? AND embed_fingerprint = ?
6806
+ ))
6807
+ GROUP BY mirror_hash, seq
6808
+ ),
6809
+ collection_chunks AS (
6810
+ SELECT
6811
+ acm.collection,
6812
+ COUNT(*) AS chunk_count,
6813
+ SUM(CASE
6814
+ WHEN mv.embedded_at >= cc.created_at THEN 1
6815
+ ELSE 0
6816
+ END) AS embedded_count
6817
+ FROM active_collection_mirrors acm
6818
+ JOIN content_chunks cc ON cc.mirror_hash = acm.mirror_hash
6819
+ LEFT JOIN matching_vectors mv
6820
+ ON mv.mirror_hash = cc.mirror_hash AND mv.seq = cc.seq
6821
+ GROUP BY acm.collection
6822
+ )
6823
+ SELECT
6824
+ c.name,
6825
+ c.path,
6826
+ c.egress_policy,
6827
+ c.egress_policy_source,
6828
+ c.workspace_root,
6829
+ c.workspace_source,
6830
+ COALESCE(ch.chunk_count, 0) AS chunk_count,
6831
+ COALESCE(ch.embedded_count, 0) AS embedded_count
6832
+ FROM collections c
6833
+ LEFT JOIN collection_chunks ch ON ch.collection = c.name
6834
+ WHERE ? IS NULL OR c.name IN (SELECT value FROM json_each(?))
6835
+ ORDER BY c.name
6836
+ `
6837
+ )
6838
+ .all(
6839
+ embedModel,
6840
+ embedModel,
6841
+ embedFingerprint,
6842
+ configuredJson,
6843
+ configuredJson
6844
+ );
6408
6845
 
6409
6846
  // Chunks of active documents only (deduplicated by canonical chunk);
6410
6847
  // content_chunks keeps rows of deleted documents until cleanup.
@@ -6423,51 +6860,52 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
6423
6860
  )
6424
6861
  .get(configuredJson, configuredJson)?.count ?? 0;
6425
6862
 
6426
- // Embedding backlog: chunks from active docs of configured collections
6427
- // without vectors. DISTINCT avoids duplicates when docs share mirror_hash.
6428
- const backlogRow = db
6429
- .query<
6430
- { count: number },
6431
- [
6432
- string | null,
6433
- string | null,
6434
- string | null,
6435
- string | null,
6436
- string | null,
6437
- ]
6438
- >(
6439
- `
6440
- WITH active_mirrors AS (
6441
- SELECT DISTINCT mirror_hash
6442
- FROM documents
6443
- WHERE active = 1 AND mirror_hash IS NOT NULL
6444
- AND (? IS NULL OR collection IN (SELECT value FROM json_each(?)))
6445
- ),
6446
- matching_vectors AS (
6447
- SELECT mirror_hash, seq, MAX(embedded_at) AS embedded_at
6448
- FROM content_vectors
6449
- WHERE (? IS NULL OR (
6450
- model = ? AND embed_fingerprint = ?
6451
- ))
6452
- GROUP BY mirror_hash, seq
6453
- )
6454
- SELECT COUNT(*) AS count
6455
- FROM active_mirrors am
6456
- JOIN content_chunks c ON c.mirror_hash = am.mirror_hash
6457
- LEFT JOIN matching_vectors mv
6458
- ON mv.mirror_hash = c.mirror_hash
6459
- AND mv.seq = c.seq
6460
- AND mv.embedded_at >= c.created_at
6461
- WHERE mv.mirror_hash IS NULL
6462
- `
6463
- )
6464
- .get(
6465
- configuredJson,
6466
- configuredJson,
6467
- embedModel,
6468
- embedModel,
6469
- embedFingerprint
6470
- );
6863
+ // Embedding backlog: skip legacy content_vectors scan when variantStatus is present.
6864
+ const embeddingBacklog = variantStatus
6865
+ ? variantStatus.backlog
6866
+ : (db
6867
+ .query<
6868
+ { count: number },
6869
+ [
6870
+ string | null,
6871
+ string | null,
6872
+ string | null,
6873
+ string | null,
6874
+ string | null,
6875
+ ]
6876
+ >(
6877
+ `
6878
+ WITH active_mirrors AS (
6879
+ SELECT DISTINCT mirror_hash
6880
+ FROM documents
6881
+ WHERE active = 1 AND mirror_hash IS NOT NULL
6882
+ AND (? IS NULL OR collection IN (SELECT value FROM json_each(?)))
6883
+ ),
6884
+ matching_vectors AS (
6885
+ SELECT mirror_hash, seq, MAX(embedded_at) AS embedded_at
6886
+ FROM content_vectors
6887
+ WHERE (? IS NULL OR (
6888
+ model = ? AND embed_fingerprint = ?
6889
+ ))
6890
+ GROUP BY mirror_hash, seq
6891
+ )
6892
+ SELECT COUNT(*) AS count
6893
+ FROM active_mirrors am
6894
+ JOIN content_chunks c ON c.mirror_hash = am.mirror_hash
6895
+ LEFT JOIN matching_vectors mv
6896
+ ON mv.mirror_hash = c.mirror_hash
6897
+ AND mv.seq = c.seq
6898
+ AND mv.embedded_at >= c.created_at
6899
+ WHERE mv.mirror_hash IS NULL
6900
+ `
6901
+ )
6902
+ .get(
6903
+ configuredJson,
6904
+ configuredJson,
6905
+ embedModel,
6906
+ embedModel,
6907
+ embedFingerprint
6908
+ )?.count ?? 0);
6471
6909
 
6472
6910
  // Recent errors (last 24h)
6473
6911
  const recentErrorsRow = db
@@ -6479,42 +6917,36 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
6479
6917
  )
6480
6918
  .get();
6481
6919
 
6482
- // Last updated (max updated_at from documents)
6483
- const lastUpdatedRow = db
6484
- .query<{ last_updated: string | null }, []>(
6485
- "SELECT strftime('%Y-%m-%dT%H:%M:%fZ', MAX(updated_at)) as last_updated FROM documents"
6486
- )
6487
- .get();
6488
-
6489
6920
  // Health check: no recent errors and DB is accessible
6490
6921
  const recentErrors = recentErrorsRow?.count ?? 0;
6491
6922
  const healthy = recentErrors === 0;
6492
6923
 
6493
- const metadataCoverage = await this.getTypedMetadataCoverage({});
6494
- if (!metadataCoverage.ok) return metadataCoverage;
6495
6924
  return ok({
6496
- typedMetadata: metadataCoverage.value,
6925
+ typedMetadata: { pending: metaPending, invalid: metaInvalid },
6497
6926
  version,
6498
6927
  indexName,
6499
6928
  configPath: this.configPath,
6500
6929
  dbPath: this.dbPath,
6501
6930
  ftsTokenizer: this.ftsTokenizer,
6502
- collections: collectionStats.map((s) => ({
6503
- name: s.name,
6504
- path: s.path,
6505
- egressPolicy: s.egress_policy,
6506
- egressPolicySource: s.egress_policy_source,
6507
- workspaceRoot: s.workspace_root,
6508
- workspaceSource: s.workspace_source ?? "none",
6509
- totalDocuments: s.total,
6510
- activeDocuments: s.active,
6511
- errorDocuments: s.errored,
6512
- chunkedDocuments: s.chunked,
6513
- totalChunks: s.chunk_count,
6514
- embeddedChunks: variantStatus
6515
- ? (variantStatus.embeddedByCollection.get(s.name) ?? 0)
6516
- : s.embedded_count,
6517
- })),
6931
+ collections: collectionStats.map((s) => {
6932
+ const ds = docStatsByCollection.get(s.name);
6933
+ return {
6934
+ name: s.name,
6935
+ path: s.path,
6936
+ egressPolicy: s.egress_policy,
6937
+ egressPolicySource: s.egress_policy_source,
6938
+ workspaceRoot: s.workspace_root,
6939
+ workspaceSource: s.workspace_source ?? "none",
6940
+ totalDocuments: ds?.total ?? 0,
6941
+ activeDocuments: ds?.active ?? 0,
6942
+ errorDocuments: ds?.errored ?? 0,
6943
+ chunkedDocuments: ds?.chunked ?? 0,
6944
+ totalChunks: s.chunk_count,
6945
+ embeddedChunks: variantStatus
6946
+ ? (variantStatus.embeddedByCollection.get(s.name) ?? 0)
6947
+ : s.embedded_count,
6948
+ };
6949
+ }),
6518
6950
  ...(vectorPartitions.length
6519
6951
  ? {
6520
6952
  vectorPartitions,
@@ -6523,13 +6955,13 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
6523
6955
  : {}),
6524
6956
  }
6525
6957
  : {}),
6526
- totalDocuments: totalsRow?.total ?? 0,
6527
- activeDocuments: totalsRow?.active ?? 0,
6958
+ totalDocuments,
6959
+ activeDocuments,
6528
6960
  totalChunks: chunkCount,
6529
- embeddingBacklog: variantStatus?.backlog ?? backlogRow?.count ?? 0,
6961
+ embeddingBacklog,
6530
6962
  chunking: getChunkingStatus(db, options?.chunking),
6531
6963
  recentErrors,
6532
- lastUpdatedAt: lastUpdatedRow?.last_updated ?? null,
6964
+ lastUpdatedAt,
6533
6965
  healthy,
6534
6966
  });
6535
6967
  } catch (cause) {
@@ -6591,6 +7023,86 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
6591
7023
  }
6592
7024
  }
6593
7025
 
7026
+ async getRecentBudgetStops(
7027
+ codes: readonly string[],
7028
+ scanLimit = 100,
7029
+ maxStops = 10
7030
+ ): Promise<
7031
+ StoreResult<
7032
+ Array<{
7033
+ collection: string;
7034
+ relPath: string;
7035
+ code: string;
7036
+ message: string;
7037
+ }>
7038
+ >
7039
+ > {
7040
+ if (codes.length === 0 || scanLimit <= 0 || maxStops <= 0) {
7041
+ return ok([]);
7042
+ }
7043
+ try {
7044
+ const db = this.ensureOpen();
7045
+ const rows = db
7046
+ .query<
7047
+ {
7048
+ collection: string;
7049
+ rel_path: string;
7050
+ code: string;
7051
+ message: string;
7052
+ },
7053
+ [number, string, number]
7054
+ >(
7055
+ `WITH recent AS (
7056
+ SELECT
7057
+ collection,
7058
+ rel_path,
7059
+ occurred_at,
7060
+ code,
7061
+ message,
7062
+ ROW_NUMBER() OVER (
7063
+ PARTITION BY collection, rel_path
7064
+ ORDER BY occurred_at DESC, id DESC
7065
+ ) AS rn
7066
+ FROM (
7067
+ SELECT id, collection, rel_path, occurred_at, code, message
7068
+ FROM ingest_errors
7069
+ ORDER BY occurred_at DESC
7070
+ LIMIT ?
7071
+ )
7072
+ )
7073
+ SELECT r.collection, r.rel_path, r.code, r.message
7074
+ FROM recent r
7075
+ INNER JOIN documents d
7076
+ ON d.collection = r.collection
7077
+ AND d.rel_path = r.rel_path
7078
+ WHERE r.rn = 1
7079
+ AND r.code IN (SELECT value FROM json_each(?))
7080
+ AND d.active = 1
7081
+ AND d.last_error_code = r.code
7082
+ ORDER BY r.occurred_at DESC
7083
+ LIMIT ?`
7084
+ )
7085
+ .all(scanLimit, JSON.stringify(codes), maxStops);
7086
+
7087
+ return ok(
7088
+ rows.map((row) => ({
7089
+ collection: row.collection,
7090
+ relPath: row.rel_path,
7091
+ code: row.code,
7092
+ message: row.message,
7093
+ }))
7094
+ );
7095
+ } catch (cause) {
7096
+ return err(
7097
+ "QUERY_FAILED",
7098
+ cause instanceof Error
7099
+ ? cause.message
7100
+ : "Failed to get recent budget stops",
7101
+ cause
7102
+ );
7103
+ }
7104
+ }
7105
+
6594
7106
  // ─────────────────────────────────────────────────────────────────────────
6595
7107
  // Cleanup
6596
7108
  // ─────────────────────────────────────────────────────────────────────────
@@ -6661,6 +7173,60 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
6661
7173
  }
6662
7174
  }
6663
7175
 
7176
+ async getLlmCache(key: string): Promise<StoreResult<string | null>> {
7177
+ try {
7178
+ const db = this.ensureOpen();
7179
+ const row = db
7180
+ .query<{ value: string }, [string]>(
7181
+ `SELECT value FROM llm_cache
7182
+ WHERE key = ? AND (expires_at IS NULL OR expires_at >= datetime('now'))`
7183
+ )
7184
+ .get(key);
7185
+ return ok(row?.value ?? null);
7186
+ } catch (cause) {
7187
+ return err(
7188
+ "QUERY_FAILED",
7189
+ cause instanceof Error ? cause.message : "Failed to read LLM cache",
7190
+ cause
7191
+ );
7192
+ }
7193
+ }
7194
+
7195
+ async setLlmCache(
7196
+ key: string,
7197
+ value: string,
7198
+ expiresAt?: string
7199
+ ): Promise<StoreResult<void>> {
7200
+ try {
7201
+ const db = this.ensureOpen();
7202
+ db.query<unknown, [string, string, string | null]>(
7203
+ `INSERT OR REPLACE INTO llm_cache (key, value, created_at, expires_at)
7204
+ VALUES (?, ?, datetime('now'), ?)`
7205
+ ).run(key, value, expiresAt ?? null);
7206
+ return ok(undefined);
7207
+ } catch (cause) {
7208
+ const message = cause instanceof Error ? cause.message : String(cause);
7209
+ const rawCode =
7210
+ cause && typeof cause === "object" && "code" in cause
7211
+ ? (cause as { code?: unknown }).code
7212
+ : undefined;
7213
+ const code = typeof rawCode === "string" ? rawCode : "";
7214
+ if (
7215
+ code.includes("READONLY") ||
7216
+ code.includes("BUSY") ||
7217
+ code.includes("LOCKED") ||
7218
+ /readonly|locked|busy/i.test(message)
7219
+ ) {
7220
+ return ok(undefined);
7221
+ }
7222
+ return err(
7223
+ "QUERY_FAILED",
7224
+ cause instanceof Error ? cause.message : "Failed to write LLM cache",
7225
+ cause
7226
+ );
7227
+ }
7228
+ }
7229
+
6664
7230
  async clearEmbeddingsForCollection(
6665
7231
  collection: string,
6666
7232
  options: { mode: "stale" | "all"; activeModel?: string }
@@ -7036,7 +7602,7 @@ function mapDocumentRow(row: DbDocumentRow): DocumentRow {
7036
7602
  frontmatterDate: row.frontmatter_date,
7037
7603
  dateFields,
7038
7604
  typedMetadata: row.typed_metadata
7039
- ? typedMetadataSchema.parse(JSON.parse(row.typed_metadata))
7605
+ ? parseStoredTypedMetadata(row.typed_metadata)
7040
7606
  : null,
7041
7607
  metadataError: row.metadata_error,
7042
7608
  recordKey: row.record_key,