sensemaking 0.24.6 → 0.25.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 (249) hide show
  1. package/README.md +20 -11
  2. package/dist/cjs/cli/build.d.cts +3 -0
  3. package/dist/cjs/cli/build.d.ts +3 -0
  4. package/dist/cjs/cli/build.js +195 -0
  5. package/dist/cjs/cli/build.js.map +1 -0
  6. package/dist/cjs/cli/index.d.cts +7 -6
  7. package/dist/cjs/cli/index.d.ts +7 -6
  8. package/dist/cjs/cli/index.js +12 -6
  9. package/dist/cjs/cli/index.js.map +1 -1
  10. package/dist/cjs/cli/init.js +2 -2
  11. package/dist/cjs/cli/init.js.map +1 -1
  12. package/dist/cjs/cli/map.js +7 -2
  13. package/dist/cjs/cli/map.js.map +1 -1
  14. package/dist/cjs/cli/named.js +63 -21
  15. package/dist/cjs/cli/named.js.map +1 -1
  16. package/dist/cjs/cli/path.js +7 -2
  17. package/dist/cjs/cli/path.js.map +1 -1
  18. package/dist/cjs/cli/peek.js +7 -2
  19. package/dist/cjs/cli/peek.js.map +1 -1
  20. package/dist/cjs/cli/related.js +55 -6
  21. package/dist/cjs/cli/related.js.map +1 -1
  22. package/dist/cjs/cli/search.js +54 -15
  23. package/dist/cjs/cli/search.js.map +1 -1
  24. package/dist/cjs/cli/shared.d.cts +9 -3
  25. package/dist/cjs/cli/shared.d.ts +9 -3
  26. package/dist/cjs/cli/shared.js +109 -74
  27. package/dist/cjs/cli/shared.js.map +1 -1
  28. package/dist/cjs/cli/sql.js +8 -3
  29. package/dist/cjs/cli/sql.js.map +1 -1
  30. package/dist/cjs/cli/status.js +142 -50
  31. package/dist/cjs/cli/status.js.map +1 -1
  32. package/dist/cjs/cli/types.d.cts +4 -2
  33. package/dist/cjs/cli/types.d.ts +4 -2
  34. package/dist/cjs/cli.js +10 -4
  35. package/dist/cjs/cli.js.map +1 -1
  36. package/dist/cjs/commands/map.js +10 -6
  37. package/dist/cjs/commands/map.js.map +1 -1
  38. package/dist/cjs/commands/peek.js +10 -6
  39. package/dist/cjs/commands/peek.js.map +1 -1
  40. package/dist/cjs/commands/related.d.cts +1 -0
  41. package/dist/cjs/commands/related.d.ts +1 -0
  42. package/dist/cjs/commands/related.js +56 -21
  43. package/dist/cjs/commands/related.js.map +1 -1
  44. package/dist/cjs/commands/scope.js +1 -1
  45. package/dist/cjs/commands/scope.js.map +1 -1
  46. package/dist/cjs/commands/search.js +102 -84
  47. package/dist/cjs/commands/search.js.map +1 -1
  48. package/dist/cjs/config/index.d.cts +1 -1
  49. package/dist/cjs/config/index.d.ts +1 -1
  50. package/dist/cjs/config/index.js.map +1 -1
  51. package/dist/cjs/config/load.d.cts +6 -1
  52. package/dist/cjs/config/load.d.ts +6 -1
  53. package/dist/cjs/config/load.js +38 -1
  54. package/dist/cjs/config/load.js.map +1 -1
  55. package/dist/cjs/config/types.d.cts +2 -1
  56. package/dist/cjs/config/types.d.ts +2 -1
  57. package/dist/cjs/config/types.js +1 -1
  58. package/dist/cjs/config/types.js.map +1 -1
  59. package/dist/cjs/config/validate.js +20 -0
  60. package/dist/cjs/config/validate.js.map +1 -1
  61. package/dist/cjs/embed/query.d.cts +2 -1
  62. package/dist/cjs/embed/query.d.ts +2 -1
  63. package/dist/cjs/embed/query.js +186 -109
  64. package/dist/cjs/embed/query.js.map +1 -1
  65. package/dist/cjs/errors.d.cts +1 -1
  66. package/dist/cjs/errors.d.ts +1 -1
  67. package/dist/cjs/errors.js.map +1 -1
  68. package/dist/cjs/features/embed.js.map +1 -1
  69. package/dist/cjs/graph/traverse.js +11 -6
  70. package/dist/cjs/graph/traverse.js.map +1 -1
  71. package/dist/cjs/index.d.cts +3 -3
  72. package/dist/cjs/index.d.ts +3 -3
  73. package/dist/cjs/index.js +3 -0
  74. package/dist/cjs/index.js.map +1 -1
  75. package/dist/cjs/lib/atomic-write.js +20 -6
  76. package/dist/cjs/lib/atomic-write.js.map +1 -1
  77. package/dist/cjs/lib/serial-query.d.cts +1 -0
  78. package/dist/cjs/lib/serial-query.d.ts +1 -0
  79. package/dist/cjs/lib/serial-query.js +22 -0
  80. package/dist/cjs/lib/serial-query.js.map +1 -0
  81. package/dist/cjs/scan/index.d.cts +5 -0
  82. package/dist/cjs/scan/index.d.ts +5 -0
  83. package/dist/cjs/scan/index.js +12 -4
  84. package/dist/cjs/scan/index.js.map +1 -1
  85. package/dist/cjs/scan/pool.d.cts +5 -0
  86. package/dist/cjs/scan/pool.d.ts +5 -0
  87. package/dist/cjs/scan/pool.js +167 -55
  88. package/dist/cjs/scan/pool.js.map +1 -1
  89. package/dist/cjs/store/builder.d.cts +6 -1
  90. package/dist/cjs/store/builder.d.ts +6 -1
  91. package/dist/cjs/store/builder.js +135 -5
  92. package/dist/cjs/store/builder.js.map +1 -1
  93. package/dist/cjs/store/duckdb/lexical.d.cts +2 -0
  94. package/dist/cjs/store/duckdb/lexical.d.ts +2 -0
  95. package/dist/cjs/store/duckdb/lexical.js +139 -7
  96. package/dist/cjs/store/duckdb/lexical.js.map +1 -1
  97. package/dist/cjs/store/duckdb/open.d.cts +3 -3
  98. package/dist/cjs/store/duckdb/open.d.ts +3 -3
  99. package/dist/cjs/store/duckdb/open.js +61 -42
  100. package/dist/cjs/store/duckdb/open.js.map +1 -1
  101. package/dist/cjs/store/duckdb/reconcile.js +2 -2
  102. package/dist/cjs/store/duckdb/reconcile.js.map +1 -1
  103. package/dist/cjs/store/duckdb/vectors.d.cts +1 -0
  104. package/dist/cjs/store/duckdb/vectors.d.ts +1 -0
  105. package/dist/cjs/store/duckdb/vectors.js +55 -43
  106. package/dist/cjs/store/duckdb/vectors.js.map +1 -1
  107. package/dist/cjs/store/index.d.cts +23 -4
  108. package/dist/cjs/store/index.d.ts +23 -4
  109. package/dist/cjs/store/index.js +224 -15
  110. package/dist/cjs/store/index.js.map +1 -1
  111. package/dist/cjs/store/open.d.cts +9 -1
  112. package/dist/cjs/store/open.d.ts +9 -1
  113. package/dist/cjs/store/open.js +479 -128
  114. package/dist/cjs/store/open.js.map +1 -1
  115. package/dist/cjs/store/reconcile.js +93 -63
  116. package/dist/cjs/store/reconcile.js.map +1 -1
  117. package/dist/cjs/store/sqlite/open.d.cts +3 -3
  118. package/dist/cjs/store/sqlite/open.d.ts +3 -3
  119. package/dist/cjs/store/sqlite/open.js +44 -36
  120. package/dist/cjs/store/sqlite/open.js.map +1 -1
  121. package/dist/cjs/store/turso/open.d.cts +3 -3
  122. package/dist/cjs/store/turso/open.d.ts +3 -3
  123. package/dist/cjs/store/turso/open.js +83 -66
  124. package/dist/cjs/store/turso/open.js.map +1 -1
  125. package/dist/cjs/store/turso/store.d.cts +3 -1
  126. package/dist/cjs/store/turso/store.d.ts +3 -1
  127. package/dist/cjs/store/turso/store.js +46 -31
  128. package/dist/cjs/store/turso/store.js.map +1 -1
  129. package/dist/cjs/store/types.d.cts +12 -3
  130. package/dist/cjs/store/types.d.ts +12 -3
  131. package/dist/cjs/store/types.js.map +1 -1
  132. package/dist/cjs/watch.js +155 -35
  133. package/dist/cjs/watch.js.map +1 -1
  134. package/dist/esm/cli/build.d.ts +3 -0
  135. package/dist/esm/cli/build.js +18 -0
  136. package/dist/esm/cli/build.js.map +1 -0
  137. package/dist/esm/cli/index.d.ts +7 -6
  138. package/dist/esm/cli/index.js +8 -6
  139. package/dist/esm/cli/index.js.map +1 -1
  140. package/dist/esm/cli/init.js +2 -2
  141. package/dist/esm/cli/init.js.map +1 -1
  142. package/dist/esm/cli/map.js +8 -2
  143. package/dist/esm/cli/map.js.map +1 -1
  144. package/dist/esm/cli/named.js +38 -14
  145. package/dist/esm/cli/named.js.map +1 -1
  146. package/dist/esm/cli/path.js +8 -2
  147. package/dist/esm/cli/path.js.map +1 -1
  148. package/dist/esm/cli/peek.js +8 -2
  149. package/dist/esm/cli/peek.js.map +1 -1
  150. package/dist/esm/cli/related.js +21 -3
  151. package/dist/esm/cli/related.js.map +1 -1
  152. package/dist/esm/cli/search.js +28 -7
  153. package/dist/esm/cli/search.js.map +1 -1
  154. package/dist/esm/cli/shared.d.ts +9 -3
  155. package/dist/esm/cli/shared.js +44 -24
  156. package/dist/esm/cli/shared.js.map +1 -1
  157. package/dist/esm/cli/sql.js +8 -2
  158. package/dist/esm/cli/sql.js.map +1 -1
  159. package/dist/esm/cli/status.js +166 -111
  160. package/dist/esm/cli/status.js.map +1 -1
  161. package/dist/esm/cli/types.d.ts +4 -2
  162. package/dist/esm/cli/types.js.map +1 -1
  163. package/dist/esm/cli.js +9 -4
  164. package/dist/esm/cli.js.map +1 -1
  165. package/dist/esm/commands/map.js +5 -1
  166. package/dist/esm/commands/map.js.map +1 -1
  167. package/dist/esm/commands/peek.js +5 -1
  168. package/dist/esm/commands/peek.js.map +1 -1
  169. package/dist/esm/commands/related.d.ts +1 -0
  170. package/dist/esm/commands/related.js +19 -10
  171. package/dist/esm/commands/related.js.map +1 -1
  172. package/dist/esm/commands/scope.js +1 -1
  173. package/dist/esm/commands/scope.js.map +1 -1
  174. package/dist/esm/commands/search.js +11 -10
  175. package/dist/esm/commands/search.js.map +1 -1
  176. package/dist/esm/config/index.d.ts +1 -1
  177. package/dist/esm/config/index.js.map +1 -1
  178. package/dist/esm/config/load.d.ts +6 -1
  179. package/dist/esm/config/load.js +32 -3
  180. package/dist/esm/config/load.js.map +1 -1
  181. package/dist/esm/config/types.d.ts +2 -1
  182. package/dist/esm/config/types.js +1 -1
  183. package/dist/esm/config/types.js.map +1 -1
  184. package/dist/esm/config/validate.js +20 -0
  185. package/dist/esm/config/validate.js.map +1 -1
  186. package/dist/esm/embed/query.d.ts +2 -1
  187. package/dist/esm/embed/query.js +40 -34
  188. package/dist/esm/embed/query.js.map +1 -1
  189. package/dist/esm/errors.d.ts +1 -1
  190. package/dist/esm/errors.js.map +1 -1
  191. package/dist/esm/features/embed.js.map +1 -1
  192. package/dist/esm/graph/traverse.js +5 -1
  193. package/dist/esm/graph/traverse.js.map +1 -1
  194. package/dist/esm/index.d.ts +3 -3
  195. package/dist/esm/index.js +1 -1
  196. package/dist/esm/index.js.map +1 -1
  197. package/dist/esm/lib/atomic-write.js +14 -6
  198. package/dist/esm/lib/atomic-write.js.map +1 -1
  199. package/dist/esm/lib/serial-query.d.ts +1 -0
  200. package/dist/esm/lib/serial-query.js +13 -0
  201. package/dist/esm/lib/serial-query.js.map +1 -0
  202. package/dist/esm/scan/index.d.ts +5 -0
  203. package/dist/esm/scan/index.js +7 -3
  204. package/dist/esm/scan/index.js.map +1 -1
  205. package/dist/esm/scan/pool.d.ts +5 -0
  206. package/dist/esm/scan/pool.js +41 -16
  207. package/dist/esm/scan/pool.js.map +1 -1
  208. package/dist/esm/store/builder.d.ts +6 -1
  209. package/dist/esm/store/builder.js +19 -0
  210. package/dist/esm/store/builder.js.map +1 -1
  211. package/dist/esm/store/duckdb/lexical.d.ts +2 -0
  212. package/dist/esm/store/duckdb/lexical.js +32 -4
  213. package/dist/esm/store/duckdb/lexical.js.map +1 -1
  214. package/dist/esm/store/duckdb/open.d.ts +3 -3
  215. package/dist/esm/store/duckdb/open.js +16 -7
  216. package/dist/esm/store/duckdb/open.js.map +1 -1
  217. package/dist/esm/store/duckdb/reconcile.js +2 -2
  218. package/dist/esm/store/duckdb/reconcile.js.map +1 -1
  219. package/dist/esm/store/duckdb/vectors.d.ts +1 -0
  220. package/dist/esm/store/duckdb/vectors.js +18 -14
  221. package/dist/esm/store/duckdb/vectors.js.map +1 -1
  222. package/dist/esm/store/index.d.ts +23 -4
  223. package/dist/esm/store/index.js +80 -15
  224. package/dist/esm/store/index.js.map +1 -1
  225. package/dist/esm/store/open.d.ts +9 -1
  226. package/dist/esm/store/open.js +175 -84
  227. package/dist/esm/store/open.js.map +1 -1
  228. package/dist/esm/store/reconcile.js +12 -0
  229. package/dist/esm/store/reconcile.js.map +1 -1
  230. package/dist/esm/store/sqlite/open.d.ts +3 -3
  231. package/dist/esm/store/sqlite/open.js +9 -6
  232. package/dist/esm/store/sqlite/open.js.map +1 -1
  233. package/dist/esm/store/turso/open.d.ts +3 -3
  234. package/dist/esm/store/turso/open.js +14 -10
  235. package/dist/esm/store/turso/open.js.map +1 -1
  236. package/dist/esm/store/turso/store.d.ts +3 -1
  237. package/dist/esm/store/turso/store.js +5 -1
  238. package/dist/esm/store/turso/store.js.map +1 -1
  239. package/dist/esm/store/types.d.ts +12 -3
  240. package/dist/esm/store/types.js.map +1 -1
  241. package/dist/esm/watch.js +57 -19
  242. package/dist/esm/watch.js.map +1 -1
  243. package/package.json +1 -1
  244. package/schema.json +7 -2
  245. package/skills/sense/SKILL.md +3 -3
  246. package/skills/sense-bases/SKILL.md +1 -2
  247. package/skills/sense-setup/SKILL.md +1 -1
  248. package/skills/sense-setup/references/embeddings.md +1 -1
  249. package/skills/sense-setup/references/store-benchmarks.md +6 -6
@@ -1,4 +1,6 @@
1
1
  import type { Database } from '@tursodatabase/database';
2
2
  import type { Capability, Connection, Store } from '../types.js';
3
3
  export declare const CAPABILITIES: ReadonlySet<Capability>;
4
- export declare function createStore(db: Database, conn: Connection): Store;
4
+ export declare function createStore(db: Database, conn: Connection, options?: {
5
+ observational?: boolean;
6
+ }): Store;
@@ -1,4 +1,6 @@
1
1
  import type { Database } from '@tursodatabase/database';
2
2
  import type { Capability, Connection, Store } from '../types.js';
3
3
  export declare const CAPABILITIES: ReadonlySet<Capability>;
4
- export declare function createStore(db: Database, conn: Connection): Store;
4
+ export declare function createStore(db: Database, conn: Connection, options?: {
5
+ observational?: boolean;
6
+ }): Store;
@@ -370,6 +370,7 @@ var CAPABILITIES = new Set([
370
370
  // overhead a user should accept (PLAN 3.52), in postgres autovacuum scale-factor shape.
371
371
  var BLOAT_FACTOR = 1.5;
372
372
  function createStore(db, conn) {
373
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
373
374
  return {
374
375
  name: 'turso',
375
376
  capabilities: CAPABILITIES,
@@ -561,116 +562,130 @@ function createStore(db, conn) {
561
562
  return _ts_generator(this, function(_state) {
562
563
  switch(_state.label){
563
564
  case 0:
565
+ if (!options.observational) return [
566
+ 3,
567
+ 2
568
+ ];
569
+ return [
570
+ 4,
571
+ db.close()
572
+ ];
573
+ case 1:
574
+ _state.sent();
575
+ return [
576
+ 2
577
+ ];
578
+ case 2:
564
579
  // Checkpoint before measuring: the last reconcile's pages sit in the WAL, not the file yet.
565
580
  return [
566
581
  4,
567
582
  (0, _connectionts.checkpointWal)(db)
568
583
  ];
569
- case 1:
584
+ case 3:
570
585
  _state.sent();
571
586
  reclaimPath = null;
572
- _state.label = 2;
573
- case 2:
587
+ _state.label = 4;
588
+ case 4:
574
589
  _state.trys.push([
575
- 2,
576
- 12,
590
+ 4,
591
+ 14,
577
592
  ,
578
- 13
593
+ 15
579
594
  ]);
580
595
  return [
581
596
  4,
582
597
  (0, _connectionts.cacheFilePath)(conn)
583
598
  ];
584
- case 3:
599
+ case 5:
585
600
  path = _state.sent();
586
601
  return [
587
602
  4,
588
603
  (0, _sharedts.getMeta)(conn, 'compact_size')
589
604
  ];
590
- case 4:
605
+ case 6:
591
606
  base = Number.apply(void 0, [
592
607
  (_ref = _state.sent()) !== null && _ref !== void 0 ? _ref : '0'
593
608
  ]);
594
609
  if (!(path === null)) return [
595
610
  3,
596
- 5
611
+ 7
597
612
  ];
598
613
  _tmp = null;
599
614
  return [
600
615
  3,
601
- 7
616
+ 9
602
617
  ];
603
- case 5:
618
+ case 7:
604
619
  return [
605
620
  4,
606
621
  (0, _connectionts.fileSize)(path)
607
622
  ];
608
- case 6:
623
+ case 8:
609
624
  _tmp = _state.sent();
610
- _state.label = 7;
611
- case 7:
625
+ _state.label = 9;
626
+ case 9:
612
627
  size = _tmp;
613
628
  if (!(size !== null)) return [
614
629
  3,
615
- 11
630
+ 13
616
631
  ];
617
632
  if (!(base === 0)) return [
618
633
  3,
619
- 10
634
+ 12
620
635
  ];
621
636
  return [
622
637
  4,
623
638
  (0, _sharedts.setMeta)(conn, 'compact_size', String(size))
624
639
  ];
625
- case 8:
640
+ case 10:
626
641
  _state.sent();
627
642
  // The meta write landed past the checkpoint; leave no WAL for the next opener.
628
643
  return [
629
644
  4,
630
645
  (0, _connectionts.checkpointWal)(db)
631
646
  ];
632
- case 9:
647
+ case 11:
633
648
  _state.sent();
634
649
  return [
635
650
  3,
636
- 11
651
+ 13
637
652
  ];
638
- case 10:
653
+ case 12:
639
654
  if (size > BLOAT_FACTOR * base) {
640
655
  reclaimPath = path;
641
656
  }
642
- _state.label = 11;
643
- case 11:
657
+ _state.label = 13;
658
+ case 13:
644
659
  return [
645
660
  3,
646
- 13
661
+ 15
647
662
  ];
648
- case 12:
663
+ case 14:
649
664
  err = _state.sent();
650
665
  console.error("sense: turso cache bloat check failed, the cache will keep its space until one succeeds: ".concat(err.message));
651
666
  return [
652
667
  3,
653
- 13
668
+ 15
654
669
  ];
655
- case 13:
670
+ case 15:
656
671
  return [
657
672
  4,
658
673
  db.close()
659
674
  ];
660
- case 14:
675
+ case 16:
661
676
  _state.sent();
662
677
  if (!(reclaimPath !== null)) return [
663
678
  3,
664
- 16
679
+ 18
665
680
  ];
666
681
  return [
667
682
  4,
668
683
  (0, _connectionts.reclaimSpace)(reclaimPath)
669
684
  ];
670
- case 15:
685
+ case 17:
671
686
  _state.sent();
672
- _state.label = 16;
673
- case 16:
687
+ _state.label = 18;
688
+ case 18:
674
689
  return [
675
690
  2
676
691
  ];
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/turso/store.ts"],"sourcesContent":["import type { Database } from '@tursodatabase/database';\nimport { STORE_DIMS } from '../../embed/types.ts';\nimport { getColumns, getMeta, setMeta } from '../shared.ts';\nimport { withTransaction } from '../transaction.ts';\nimport type { Capability, Connection, Statement, Store } from '../types.ts';\nimport { hasVectorRow, pendingRows } from '../vectors.ts';\nimport { cacheFilePath, checkpointWal, fileSize, reclaimSpace } from './connection.ts';\nimport { fieldStats } from './fieldStats.ts';\nimport { queryLexical } from './lexical.ts';\nimport { rewriteFunctions } from './sql-functions.ts';\nimport { scanCandidates, scanSimilar, writeVectorBatch } from './vectors.ts';\n\n// No 'segment': has()/basename() resolve via SQL rewrite below (sql-functions.ts), but segment() has no SQL form and the client cannot register it as a UDF.\nexport const CAPABILITIES: ReadonlySet<Capability> = new Set(['vectors']);\n\n// close() reclaims once the cache file outgrows its compact size by this factor: the disk\n// overhead a user should accept (PLAN 3.52), in postgres autovacuum scale-factor shape.\nconst BLOAT_FACTOR = 1.5;\n\n// Shares one Connection instance (conn) with the builder's own reconcile call so transaction depth\n// (see transaction.ts) is tracked against the same object everywhere.\nexport function createStore(db: Database, conn: Connection): Store {\n return {\n name: 'turso',\n capabilities: CAPABILITIES,\n async exec(sql: string): Promise<void> {\n await conn.exec(sql);\n },\n async prepare(sql: string): Promise<Statement> {\n return conn.prepare(sql);\n },\n async runBatch(sql: string, paramRows: unknown[][]): Promise<void> {\n await conn.runBatch(sql, paramRows);\n },\n async transaction<T>(fn: () => Promise<T>): Promise<T> {\n return withTransaction(conn, fn);\n },\n docs: {\n async columns() {\n return [...(await getColumns(conn))];\n },\n fieldStats: (columns, scopeWhere) => fieldStats(conn, columns, scopeWhere),\n },\n lexical: {\n query: (terms, opts) => queryLexical(conn, terms, opts),\n },\n // The column's fixed DDL width (STORE_DIMS) is what every scan binds against, not the\n // interface's per-call storeDims -- see vectors.ts's padded() for why a shorter vector is still correct against a wider column.\n vectors: {\n pending: () => pendingRows(conn),\n writeVectors: (rows) => writeVectorBatch(conn, STORE_DIMS, rows),\n candidates: (qv, _storeDims, fetch, allowed) => scanCandidates(conn, qv, STORE_DIMS, fetch, allowed),\n similar: (path, opts) => scanSimilar(conn, STORE_DIMS, path, opts),\n hasVector: (path) => hasVectorRow(conn, path),\n },\n async engineStatus() {\n // Read back rather than recomputed: this is what open() actually set (3x the largest\n // recorded reconcile, floored at 30s, capped at 10min). Turso's PRAGMA busy_timeout names its column \"busy_timeout\" (spike-verified), not \"timeout\" like real SQLite.\n const row = (await (await db.prepare('PRAGMA busy_timeout')).get()) as { busy_timeout: number };\n return { busy_timeout: `${row.busy_timeout}ms (derived: 3x the largest reconcile this cache has recorded, floored at 30000ms)` };\n },\n raw: {\n async prepare(sql: string) {\n const stmt = await db.prepare(rewriteFunctions(sql));\n stmt.safeIntegers(true); // int64 past 2^53 arrives as BigInt instead of losing precision\n return {\n columns: () => stmt.columns(),\n // sense sql streams through the client's own async generator.\n iterate: async function* (...params: unknown[]) {\n yield* stmt.iterate(...params);\n },\n };\n },\n },\n async close() {\n // Checkpoint before measuring: the last reconcile's pages sit in the WAL, not the file yet.\n await checkpointWal(db);\n let reclaimPath: string | null = null;\n try {\n const path = await cacheFilePath(conn);\n const base = Number((await getMeta(conn, 'compact_size')) ?? '0');\n const size = path === null ? null : await fileSize(path);\n if (size !== null) {\n // No baseline yet (cold build or an upgraded cache): record it, never reclaim here, so a\n // cold build pays no VACUUM (PLAN 3.49 Track A) and an upgraded cache heals on a crossing.\n if (base === 0) {\n await setMeta(conn, 'compact_size', String(size));\n // The meta write landed past the checkpoint; leave no WAL for the next opener.\n await checkpointWal(db);\n } else if (size > BLOAT_FACTOR * base) {\n reclaimPath = path;\n }\n }\n } catch (err) {\n console.error(`sense: turso cache bloat check failed, the cache will keep its space until one succeeds: ${(err as Error).message}`);\n }\n await db.close();\n // After this store's connection is closed, never before: turso hands the file to one\n // connection at a time, and reclaimSpace opens its own to carry the `vacuum` flag (PLAN 3.54).\n if (reclaimPath !== null) await reclaimSpace(reclaimPath);\n },\n };\n}\n"],"names":["CAPABILITIES","createStore","Set","BLOAT_FACTOR","db","conn","name","capabilities","exec","sql","prepare","runBatch","paramRows","transaction","fn","withTransaction","docs","columns","getColumns","fieldStats","scopeWhere","lexical","query","terms","opts","queryLexical","vectors","pending","pendingRows","writeVectors","rows","writeVectorBatch","STORE_DIMS","candidates","qv","_storeDims","fetch","allowed","scanCandidates","similar","path","scanSimilar","hasVector","hasVectorRow","engineStatus","row","get","busy_timeout","raw","stmt","rewriteFunctions","safeIntegers","iterate","params","close","reclaimPath","base","size","err","checkpointWal","cacheFilePath","getMeta","Number","fileSize","setMeta","String","console","error","message","reclaimSpace"],"mappings":";;;;;;;;;;;QAaaA;eAAAA;;QAQGC;eAAAA;;;uBApBW;wBACkB;6BACb;yBAEU;4BAC2B;4BAC1C;yBACE;8BACI;0BAC6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGvD,IAAMD,eAAwC,IAAIE,IAAI;IAAC;CAAU;AAExE,0FAA0F;AAC1F,wFAAwF;AACxF,IAAMC,eAAe;AAId,SAASF,YAAYG,EAAY,EAAEC,IAAgB;IACxD,OAAO;QACLC,MAAM;QACNC,cAAcP;QACRQ,MAAN,SAAMA,KAAKC,GAAW;;;;;4BACpB;;gCAAMJ,KAAKG,IAAI,CAACC;;;4BAAhB;;;;;;YACF;;QACMC,SAAN,SAAMA,QAAQD,GAAW;;;oBACvB;;wBAAOJ,KAAKK,OAAO,CAACD;;;YACtB;;QACME,UAAN,SAAMA,SAASF,GAAW,EAAEG,SAAsB;;;;;4BAChD;;gCAAMP,KAAKM,QAAQ,CAACF,KAAKG;;;4BAAzB;;;;;;YACF;;QACMC,aAAN,SAAMA,YAAeC,EAAoB;;;oBACvC;;wBAAOC,IAAAA,8BAAe,EAACV,MAAMS;;;YAC/B;;QACAE,MAAM;YACEC,SAAN,SAAMA;;;;;gCACQ;;oCAAMC,IAAAA,oBAAU,EAACb;;;gCAA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.ts"],"sourcesContent":["import type { Database } from '@tursodatabase/database';\nimport { STORE_DIMS } from '../../embed/types.ts';\nimport { getColumns, getMeta, setMeta } from '../shared.ts';\nimport { withTransaction } from '../transaction.ts';\nimport type { Capability, Connection, Statement, Store } from '../types.ts';\nimport { hasVectorRow, pendingRows } from '../vectors.ts';\nimport { cacheFilePath, checkpointWal, fileSize, reclaimSpace } from './connection.ts';\nimport { fieldStats } from './fieldStats.ts';\nimport { queryLexical } from './lexical.ts';\nimport { rewriteFunctions } from './sql-functions.ts';\nimport { scanCandidates, scanSimilar, writeVectorBatch } from './vectors.ts';\n\n// No 'segment': has()/basename() resolve via SQL rewrite below (sql-functions.ts), but segment() has no SQL form and the client cannot register it as a UDF.\nexport const CAPABILITIES: ReadonlySet<Capability> = new Set(['vectors']);\n\n// close() reclaims once the cache file outgrows its compact size by this factor: the disk\n// overhead a user should accept (PLAN 3.52), in postgres autovacuum scale-factor shape.\nconst BLOAT_FACTOR = 1.5;\n\n// Shares one Connection instance (conn) with the builder's own reconcile call so transaction depth\n// (see transaction.ts) is tracked against the same object everywhere.\nexport function createStore(db: Database, conn: Connection, options: { observational?: boolean } = {}): Store {\n return {\n name: 'turso',\n capabilities: CAPABILITIES,\n async exec(sql: string): Promise<void> {\n await conn.exec(sql);\n },\n async prepare(sql: string): Promise<Statement> {\n return conn.prepare(sql);\n },\n async runBatch(sql: string, paramRows: unknown[][]): Promise<void> {\n await conn.runBatch(sql, paramRows);\n },\n async transaction<T>(fn: () => Promise<T>): Promise<T> {\n return withTransaction(conn, fn);\n },\n docs: {\n async columns() {\n return [...(await getColumns(conn))];\n },\n fieldStats: (columns, scopeWhere) => fieldStats(conn, columns, scopeWhere),\n },\n lexical: {\n query: (terms, opts) => queryLexical(conn, terms, opts),\n },\n // The column's fixed DDL width (STORE_DIMS) is what every scan binds against, not the\n // interface's per-call storeDims -- see vectors.ts's padded() for why a shorter vector is still correct against a wider column.\n vectors: {\n pending: () => pendingRows(conn),\n writeVectors: (rows) => writeVectorBatch(conn, STORE_DIMS, rows),\n candidates: (qv, _storeDims, fetch, allowed) => scanCandidates(conn, qv, STORE_DIMS, fetch, allowed),\n similar: (path, opts) => scanSimilar(conn, STORE_DIMS, path, opts),\n hasVector: (path) => hasVectorRow(conn, path),\n },\n async engineStatus() {\n // Read back rather than recomputed: this is what open() actually set (3x the largest\n // recorded reconcile, floored at 30s, capped at 10min). Turso's PRAGMA busy_timeout names its column \"busy_timeout\" (spike-verified), not \"timeout\" like real SQLite.\n const row = (await (await db.prepare('PRAGMA busy_timeout')).get()) as { busy_timeout: number };\n return { busy_timeout: `${row.busy_timeout}ms (derived: 3x the largest reconcile this cache has recorded, floored at 30000ms)` };\n },\n raw: {\n async prepare(sql: string) {\n const stmt = await db.prepare(rewriteFunctions(sql));\n stmt.safeIntegers(true); // int64 past 2^53 arrives as BigInt instead of losing precision\n return {\n columns: () => stmt.columns(),\n // sense sql streams through the client's own async generator.\n iterate: async function* (...params: unknown[]) {\n yield* stmt.iterate(...params);\n },\n };\n },\n },\n async close() {\n if (options.observational) {\n await db.close();\n return;\n }\n // Checkpoint before measuring: the last reconcile's pages sit in the WAL, not the file yet.\n await checkpointWal(db);\n let reclaimPath: string | null = null;\n try {\n const path = await cacheFilePath(conn);\n const base = Number((await getMeta(conn, 'compact_size')) ?? '0');\n const size = path === null ? null : await fileSize(path);\n if (size !== null) {\n // No baseline yet (cold build or an upgraded cache): record it, never reclaim here, so a\n // cold build pays no VACUUM (PLAN 3.49 Track A) and an upgraded cache heals on a crossing.\n if (base === 0) {\n await setMeta(conn, 'compact_size', String(size));\n // The meta write landed past the checkpoint; leave no WAL for the next opener.\n await checkpointWal(db);\n } else if (size > BLOAT_FACTOR * base) {\n reclaimPath = path;\n }\n }\n } catch (err) {\n console.error(`sense: turso cache bloat check failed, the cache will keep its space until one succeeds: ${(err as Error).message}`);\n }\n await db.close();\n // After this store's connection is closed, never before: turso hands the file to one\n // connection at a time, and reclaimSpace opens its own to carry the `vacuum` flag (PLAN 3.54).\n if (reclaimPath !== null) await reclaimSpace(reclaimPath);\n },\n };\n}\n"],"names":["CAPABILITIES","createStore","Set","BLOAT_FACTOR","db","conn","options","name","capabilities","exec","sql","prepare","runBatch","paramRows","transaction","fn","withTransaction","docs","columns","getColumns","fieldStats","scopeWhere","lexical","query","terms","opts","queryLexical","vectors","pending","pendingRows","writeVectors","rows","writeVectorBatch","STORE_DIMS","candidates","qv","_storeDims","fetch","allowed","scanCandidates","similar","path","scanSimilar","hasVector","hasVectorRow","engineStatus","row","get","busy_timeout","raw","stmt","rewriteFunctions","safeIntegers","iterate","params","close","reclaimPath","base","size","err","observational","checkpointWal","cacheFilePath","getMeta","Number","fileSize","setMeta","String","console","error","message","reclaimSpace"],"mappings":";;;;;;;;;;;QAaaA;eAAAA;;QAQGC;eAAAA;;;uBApBW;wBACkB;6BACb;yBAEU;4BAC2B;4BAC1C;yBACE;8BACI;0BAC6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGvD,IAAMD,eAAwC,IAAIE,IAAI;IAAC;CAAU;AAExE,0FAA0F;AAC1F,wFAAwF;AACxF,IAAMC,eAAe;AAId,SAASF,YAAYG,EAAY,EAAEC,IAAgB;QAAEC,UAAAA,iEAAuC,CAAC;IAClG,OAAO;QACLC,MAAM;QACNC,cAAcR;QACRS,MAAN,SAAMA,KAAKC,GAAW;;;;;4BACpB;;gCAA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AAAA,iBAAO,EAAC7D,MAAM,gBAAgB8D,OAAOT;;;4BAA3C;4BACA,+EAA+E;4BAC/E;;gCAAMG,IAAAA,2BAAa,EAACzD;;;4BAApB;;;;;;4BACK,IAAIsD,OAAOvD,eAAesD,MAAM;gCACrCD,cAAcf;4BAChB;;;;;;;;4BAEKkB;4BACPS,QAAQC,KAAK,CAAC,AAAC,4FAAkH,OAAvB,AAACV,IAAcW,OAAO;;;;;;4BAElI;;gCAAMlE,GAAGmD,KAAK;;;4BAAd;iCAGIC,CAAAA,gBAAgB,IAAG,GAAnBA;;;;4BAAsB;;gCAAMe,IAAAA,0BAAY,EAACf;;;4BAAnB;;;;;;;;YAC5B;;IACF;AACF"}
@@ -34,15 +34,24 @@ export interface OpenDialect<Handle> {
34
34
  filename: string;
35
35
  schemaVersion: string;
36
36
  reconcileDialect: ReconcileDialect;
37
- connect(dbPath: string, cfg: ResolvedConfig): Promise<{
37
+ connect(dbPath: string, cfg: ResolvedConfig, options: {
38
+ existingOnly: boolean;
39
+ observational: boolean;
40
+ }): Promise<{
38
41
  handle: Handle;
39
42
  conn: Connection;
40
43
  }>;
41
- close(handle: Handle): Promise<void>;
44
+ close(handle: Handle, options?: {
45
+ observational?: boolean;
46
+ }): Promise<void>;
42
47
  isLocked?(err: Error): boolean;
43
48
  ensureSchema(handle: Handle, conn: Connection, cfg: Config): Promise<void>;
44
49
  setDerivedBusyTimeout?(handle: Handle, conn: Connection, ms: number): Promise<void>;
45
- createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig): Store;
50
+ prepareLexical?(conn: Connection): Promise<void>;
51
+ assertLexicalReady?(conn: Connection): Promise<void>;
52
+ createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig, options: {
53
+ observational: boolean;
54
+ }): Store;
46
55
  }
47
56
  export interface FieldStat {
48
57
  field: string;
@@ -34,15 +34,24 @@ export interface OpenDialect<Handle> {
34
34
  filename: string;
35
35
  schemaVersion: string;
36
36
  reconcileDialect: ReconcileDialect;
37
- connect(dbPath: string, cfg: ResolvedConfig): Promise<{
37
+ connect(dbPath: string, cfg: ResolvedConfig, options: {
38
+ existingOnly: boolean;
39
+ observational: boolean;
40
+ }): Promise<{
38
41
  handle: Handle;
39
42
  conn: Connection;
40
43
  }>;
41
- close(handle: Handle): Promise<void>;
44
+ close(handle: Handle, options?: {
45
+ observational?: boolean;
46
+ }): Promise<void>;
42
47
  isLocked?(err: Error): boolean;
43
48
  ensureSchema(handle: Handle, conn: Connection, cfg: Config): Promise<void>;
44
49
  setDerivedBusyTimeout?(handle: Handle, conn: Connection, ms: number): Promise<void>;
45
- createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig): Store;
50
+ prepareLexical?(conn: Connection): Promise<void>;
51
+ assertLexicalReady?(conn: Connection): Promise<void>;
52
+ createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig, options: {
53
+ observational: boolean;
54
+ }): Store;
46
55
  }
47
56
  export interface FieldStat {
48
57
  field: string;
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/types.ts"],"sourcesContent":["// The backing-store interface: a minimal portable statement surface (exec/prepare), plus\n// dedicated interfaces exactly where engines diverge (lexical index, vector scan, raw sql).\n\nimport type { Config, ResolvedConfig, StoreName } from '../config/index.ts';\nimport type { ReconcileDelta } from '../features/types.ts';\nimport type { ParsedDoc } from '../scan/index.ts';\n\n// 'vectors': the store's VectorStore is functionally implemented, not present-but-inert; checked\n// at open (index.ts) before a config with an \"embed\" block is allowed onto a store lacking it.\n// 'segment': the engine can run segment() (Intl.Segmenter grapheme clustering) as a SQL function;\n// turso's client cannot register it and has no rewrite for it, unlike has()/basename(), which now\n// work everywhere. An array, not a bare union, so a runtime check reads the same list the type does.\nexport const CAPABILITY_NAMES = ['vectors', 'segment'] as const;\nexport type Capability = (typeof CAPABILITY_NAMES)[number];\n\nexport interface RunResult {\n changes: number | bigint;\n lastInsertRowid: number | bigint;\n}\n\n// A prepared statement's async surface: every supported engine crosses a real async boundary\n// for a query (DuckDB has no synchronous client), so run/get/all return Promises.\nexport interface Statement {\n run(...params: unknown[]): Promise<RunResult>;\n get(...params: unknown[]): Promise<unknown>;\n all(...params: unknown[]): Promise<unknown[]>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n columns(): Array<{ name: string }>;\n setReadBigInts(enabled: boolean): void;\n}\n\n// Connection surface feature-owned SQL runs against inside a store's hot loops (schema,\n// reconcile), portable so a feature never imports an engine-specific client type.\nexport interface Connection {\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n // Bulk-inserts rows that cannot conflict, through a path that binds no per-value parameters.\n // Optional: a store that has nothing faster than its own INSERT omits it and callers fall back\n // (appendRows in shared.ts). `columns` names the values each row carries; a table column the\n // caller does not write takes its default.\n appendRows?(table: string, columns: string[], rows: unknown[][]): Promise<void>;\n}\n\n// One reconcile algorithm (src/store/reconcile.ts), parameterised per engine. reconcileContent is\n// the load-bearing member: it lands every content-table change and owns its own multi-step\n// strategy (sqlite FTS5 incremental, duckdb combined delete/insert, turso incremental-or-rebuild).\nexport interface ReconcileDialect {\n // BEGIN mode for the whole reconcile: sqlite/turso 'BEGIN IMMEDIATE', duckdb 'BEGIN'.\n beginMode(): string;\n // Throws SenseError('COLUMN_LIMIT', ...) past this store's own column ceiling and reasoning.\n checkColumnLimit(count: number): void;\n // Adds `names` to frontmatter, already filtered to columns this connection doesn't have yet.\n // sqlite/turso loop (their ADD COLUMN is metadata-only); duckdb issues one statement per call.\n addColumns(conn: Connection, names: string[]): Promise<void>;\n // Deletes content rows for `touched`, inserts rows for `docs`; `delta` carries the tree state a\n // strategy may need. Must not open its own transaction, and must not return before its own\n // multi-step strategy (e.g. turso's DROP/rebuild) completes.\n reconcileContent(conn: Connection, touched: string[], docs: ParsedDoc[], delta: ReconcileDelta, cfg: Config): Promise<void>;\n // Records this reconcile's write-transaction duration. sqlite/turso use it for open()'s derived\n // busy_timeout; duckdb has no such PRAGMA and omits it.\n recordDuration?(conn: Connection, ms: number): Promise<void>;\n}\n\n// One open algorithm (src/store/open.ts), parameterised per engine. `Handle` is whatever this\n// store needs to close the connection and construct its Store (sqlite: {db}; duckdb:\n// {instance, duckdb}; turso: db) -- opaque to the shared orchestration, threaded through unchanged.\nexport interface OpenDialect<Handle> {\n // Cache filename under STATE_DIR, e.g. 'cache.db'.\n filename: string;\n // Cache shape version, independent of the config's own `version`; bumping it rebuilds an existing tree.\n schemaVersion: string;\n reconcileDialect: ReconcileDialect;\n // Opens the physical connection and applies pragmas due before any SQL runs (sqlite: busy_timeout\n // + WAL; turso: connect-time timeout; duckdb: none).\n connect(dbPath: string, cfg: ResolvedConfig): Promise<{ handle: Handle; conn: Connection }>;\n // Releases the handle, for both the rebuild-and-reopen branch and error cleanup on this attempt.\n close(handle: Handle): Promise<void>;\n // True when connect() failed because another process holds the cache file, which the orchestration\n // retries. Each engine words it differently, so the match is the dialect's own (`native-not-emulated`).\n // Absent for sqlite, whose file lock is shared and whose concurrent-open failure is a different defect.\n // Matching on message text is forced, not chosen: measured 2026-09-02, duckdb throws a plain Error\n // whose only own properties are stack and message, and turso sets code to the constant\n // 'GenericFailure' on every failure alike with rawCode undefined. Neither exposes anything a\n // predicate could switch on, so each dialect pins its engine's wordings and unit-tests them.\n isLocked?(err: Error): boolean;\n // Schema DDL beyond frontmatter/preset_files/meta (content table, feature hooks); sole owner of\n // whether it wraps itself in a write transaction (sqlite: yes, guards a cold-open ALTER race; duckdb/turso: no).\n ensureSchema(handle: Handle, conn: Connection, cfg: Config): Promise<void>;\n // Installs the derived busy_timeout PRAGMA right before reconcile (sqlite/turso); absent for\n // duckdb, which has no such PRAGMA.\n setDerivedBusyTimeout?(handle: Handle, conn: Connection, ms: number): Promise<void>;\n createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig): Store;\n}\n\nexport interface FieldStat {\n field: string;\n coverage: number;\n type: string;\n}\n\nexport interface DocumentStore {\n // Frontmatter column names (including internal ones; callers filter).\n columns(): Promise<string[]>;\n // Per-column coverage (non-null count) and observed type set, aggregated in one SQL query,\n // never one row per note. `scopeWhere` is a caller-built WHERE fragment, per LexicalQueryOptions.\n fieldStats(columns: string[], scopeWhere: string): Promise<FieldStat[]>;\n}\n\n// A ranked match, nothing more. Snippets are cut from the document above the store\n// (commands/search.ts), identically for every engine, so no store carries them.\nexport interface LexicalHit {\n path: string;\n}\n\nexport interface LexicalQueryOptions {\n whereJoin: string;\n whereCond: string;\n scopeCond: string;\n limit: number;\n}\n\nexport interface LexicalIndex {\n // Ranked word-match query with snippet, scoped by the caller-built SQL fragments (the same\n // fragments narrowByWhere/materializeScope produce elsewhere).\n query(terms: string, opts: LexicalQueryOptions): Promise<LexicalHit[]>;\n}\n\nexport interface VectorCandidate {\n path: string;\n lines: string;\n similarity: number;\n}\n\nexport interface VectorSimilar {\n path: string;\n similarity: number;\n}\n\nexport interface VectorWriteRow {\n path: string;\n chunk: number;\n scale: number;\n vector: Buffer;\n}\n\nexport interface VectorStore {\n // Rows whose vector is NULL: never embedded, or added since.\n pending(): Promise<Array<{ path: string; chunk: number }>>;\n // One batch write per call (never per row) so a provider's embedding batch stays inside a\n // single store method.\n writeVectors(rows: VectorWriteRow[]): Promise<void>;\n candidates(queryVector: Float32Array, storeDims: number, fetch: number, allowed?: Set<string>): Promise<VectorCandidate[]>;\n similar(path: string, opts: { exclude: Set<string>; allowed?: Set<string>; k: number }): Promise<VectorSimilar[]>;\n hasVector(path: string): Promise<boolean>;\n}\n\n// The `sense sql` passthrough: string in, streamed rows out. Each store registers the same\n// sense-supplied functions and applies its own read-bigints/error-translation behavior.\nexport interface RawStatement {\n columns(): Array<{ name: string }>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n}\n\nexport interface SqlSession {\n prepare(sql: string): Promise<RawStatement>;\n}\n\nexport interface Store {\n readonly name: StoreName;\n readonly capabilities: ReadonlySet<Capability>;\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n // One crossing, N rows: every external write loop (search's candidate insert, graph ring's\n // temp-table writes) goes through this instead of looping over `run()`. Same contract as Connection.runBatch.\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n // Pins one snapshot across multi-statement reads; `map` and `peek` use it. A network-bound\n // write (search's embedding top-up) must stay outside it. Nesting joins the enclosing transaction.\n transaction<T>(fn: () => Promise<T>): Promise<T>;\n docs: DocumentStore;\n lexical: LexicalIndex;\n vectors: VectorStore;\n raw: SqlSession;\n // Engine-level facts for `sense status` (e.g. a derived busy_timeout PRAGMA reading); each\n // store owns what it reports and how it is worded. Empty when there is nothing to report.\n engineStatus(): Promise<Record<string, string>>;\n close(): Promise<void>;\n}\n"],"names":["CAPABILITY_NAMES"],"mappings":"AAAA,yFAAyF;AACzF,4FAA4F;;;;;+BAW/EA;;;eAAAA;;;AAAN,IAAMA,mBAAmB;IAAC;IAAW;CAAU"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/types.ts"],"sourcesContent":["// The backing-store interface: a minimal portable statement surface (exec/prepare), plus\n// dedicated interfaces exactly where engines diverge (lexical index, vector scan, raw sql).\n\nimport type { Config, ResolvedConfig, StoreName } from '../config/index.ts';\nimport type { ReconcileDelta } from '../features/types.ts';\nimport type { ParsedDoc } from '../scan/index.ts';\n\n// 'vectors': the store's VectorStore is functionally implemented, not present-but-inert; checked\n// at open (index.ts) before a config with an \"embed\" block is allowed onto a store lacking it.\n// 'segment': the engine can run segment() (Intl.Segmenter grapheme clustering) as a SQL function;\n// turso's client cannot register it and has no rewrite for it, unlike has()/basename(), which now\n// work everywhere. An array, not a bare union, so a runtime check reads the same list the type does.\nexport const CAPABILITY_NAMES = ['vectors', 'segment'] as const;\nexport type Capability = (typeof CAPABILITY_NAMES)[number];\n\nexport interface RunResult {\n changes: number | bigint;\n lastInsertRowid: number | bigint;\n}\n\n// A prepared statement's async surface: every supported engine crosses a real async boundary\n// for a query (DuckDB has no synchronous client), so run/get/all return Promises.\nexport interface Statement {\n run(...params: unknown[]): Promise<RunResult>;\n get(...params: unknown[]): Promise<unknown>;\n all(...params: unknown[]): Promise<unknown[]>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n columns(): Array<{ name: string }>;\n setReadBigInts(enabled: boolean): void;\n}\n\n// Connection surface feature-owned SQL runs against inside a store's hot loops (schema,\n// reconcile), portable so a feature never imports an engine-specific client type.\nexport interface Connection {\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n // Bulk-inserts rows that cannot conflict, through a path that binds no per-value parameters.\n // Optional: a store that has nothing faster than its own INSERT omits it and callers fall back\n // (appendRows in shared.ts). `columns` names the values each row carries; a table column the\n // caller does not write takes its default.\n appendRows?(table: string, columns: string[], rows: unknown[][]): Promise<void>;\n}\n\n// One reconcile algorithm (src/store/reconcile.ts), parameterised per engine. reconcileContent is\n// the load-bearing member: it lands every content-table change and owns its own multi-step\n// strategy (sqlite FTS5 incremental, duckdb combined delete/insert, turso incremental-or-rebuild).\nexport interface ReconcileDialect {\n // BEGIN mode for the whole reconcile: sqlite/turso 'BEGIN IMMEDIATE', duckdb 'BEGIN'.\n beginMode(): string;\n // Throws SenseError('COLUMN_LIMIT', ...) past this store's own column ceiling and reasoning.\n checkColumnLimit(count: number): void;\n // Adds `names` to frontmatter, already filtered to columns this connection doesn't have yet.\n // sqlite/turso loop (their ADD COLUMN is metadata-only); duckdb issues one statement per call.\n addColumns(conn: Connection, names: string[]): Promise<void>;\n // Deletes content rows for `touched`, inserts rows for `docs`; `delta` carries the tree state a\n // strategy may need. Must not open its own transaction, and must not return before its own\n // multi-step strategy (e.g. turso's DROP/rebuild) completes.\n reconcileContent(conn: Connection, touched: string[], docs: ParsedDoc[], delta: ReconcileDelta, cfg: Config): Promise<void>;\n // Records this reconcile's write-transaction duration. sqlite/turso use it for open()'s derived\n // busy_timeout; duckdb has no such PRAGMA and omits it.\n recordDuration?(conn: Connection, ms: number): Promise<void>;\n}\n\n// One open algorithm (src/store/open.ts), parameterised per engine. `Handle` is whatever this\n// store needs to close the connection and construct its Store (sqlite: {db}; duckdb:\n// {instance, duckdb}; turso: db) -- opaque to the shared orchestration, threaded through unchanged.\nexport interface OpenDialect<Handle> {\n // Cache filename under STATE_DIR, e.g. 'cache.db'.\n filename: string;\n // Cache shape version, independent of the config's own `version`; bumping it rebuilds an existing tree.\n schemaVersion: string;\n reconcileDialect: ReconcileDialect;\n // Opens the physical connection and applies pragmas due before any SQL runs (sqlite: busy_timeout\n // + WAL; turso: connect-time timeout; duckdb: none).\n connect(dbPath: string, cfg: ResolvedConfig, options: { existingOnly: boolean; observational: boolean }): Promise<{ handle: Handle; conn: Connection }>;\n // Releases the handle, for both the rebuild-and-reopen branch and error cleanup on this attempt.\n close(handle: Handle, options?: { observational?: boolean }): Promise<void>;\n // True when connect() failed because another process holds the cache file, which the orchestration\n // retries. Each engine words it differently, so the match is the dialect's own (`native-not-emulated`).\n // Absent for sqlite, whose file lock is shared and whose concurrent-open failure is a different defect.\n // Matching on message text is forced, not chosen: measured 2026-09-02, duckdb throws a plain Error\n // whose only own properties are stack and message, and turso sets code to the constant\n // 'GenericFailure' on every failure alike with rawCode undefined. Neither exposes anything a\n // predicate could switch on, so each dialect pins its engine's wordings and unit-tests them.\n isLocked?(err: Error): boolean;\n // Schema DDL beyond frontmatter/preset_files/meta (content table, feature hooks); sole owner of\n // whether it wraps itself in a write transaction (sqlite: yes, guards a cold-open ALTER race; duckdb/turso: no).\n ensureSchema(handle: Handle, conn: Connection, cfg: Config): Promise<void>;\n // Installs the derived busy_timeout PRAGMA right before reconcile (sqlite/turso); absent for\n // duckdb, which has no such PRAGMA.\n setDerivedBusyTimeout?(handle: Handle, conn: Connection, ms: number): Promise<void>;\n // Persistent lexical preparation belongs to build, while no-build calls only the readiness\n // check. SQLite and Turso maintain lexical state during reconcile and omit both hooks.\n prepareLexical?(conn: Connection): Promise<void>;\n assertLexicalReady?(conn: Connection): Promise<void>;\n createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig, options: { observational: boolean }): Store;\n}\n\nexport interface FieldStat {\n field: string;\n coverage: number;\n type: string;\n}\n\nexport interface DocumentStore {\n // Frontmatter column names (including internal ones; callers filter).\n columns(): Promise<string[]>;\n // Per-column coverage (non-null count) and observed type set, aggregated in one SQL query,\n // never one row per note. `scopeWhere` is a caller-built WHERE fragment, per LexicalQueryOptions.\n fieldStats(columns: string[], scopeWhere: string): Promise<FieldStat[]>;\n}\n\n// A ranked match, nothing more. Snippets are cut from the document above the store\n// (commands/search.ts), identically for every engine, so no store carries them.\nexport interface LexicalHit {\n path: string;\n}\n\nexport interface LexicalQueryOptions {\n whereJoin: string;\n whereCond: string;\n scopeCond: string;\n limit: number;\n}\n\nexport interface LexicalIndex {\n // Ranked word-match query with snippet, scoped by the caller-built SQL fragments (the same\n // fragments narrowByWhere/materializeScope produce elsewhere).\n query(terms: string, opts: LexicalQueryOptions): Promise<LexicalHit[]>;\n}\n\nexport interface VectorCandidate {\n path: string;\n lines: string;\n similarity: number;\n}\n\nexport interface VectorSimilar {\n path: string;\n similarity: number;\n}\n\nexport interface VectorWriteRow {\n path: string;\n chunk: number;\n scale: number;\n vector: Buffer;\n}\n\nexport interface VectorStore {\n // Rows whose vector is NULL: never embedded, or added since.\n pending(): Promise<Array<{ path: string; chunk: number }>>;\n // One batch write per call (never per row) so a provider's embedding batch stays inside a\n // single store method.\n writeVectors(rows: VectorWriteRow[]): Promise<void>;\n candidates(queryVector: Float32Array, storeDims: number, fetch: number, allowed?: Set<string>): Promise<VectorCandidate[]>;\n similar(path: string, opts: { exclude: Set<string>; allowed?: Set<string>; k: number }): Promise<VectorSimilar[]>;\n hasVector(path: string): Promise<boolean>;\n}\n\n// The `sense sql` passthrough: string in, streamed rows out. Each store registers the same\n// sense-supplied functions and applies its own read-bigints/error-translation behavior.\nexport interface RawStatement {\n columns(): Array<{ name: string }>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n}\n\nexport interface SqlSession {\n prepare(sql: string): Promise<RawStatement>;\n}\n\nexport interface Store {\n readonly name: StoreName;\n readonly capabilities: ReadonlySet<Capability>;\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n // One crossing, N rows: every external write loop (search's candidate insert, graph ring's\n // temp-table writes) goes through this instead of looping over `run()`. Same contract as Connection.runBatch.\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n // Pins one snapshot across multi-statement reads; `map` and `peek` use it. A network-bound\n // write (search's embedding top-up) must stay outside it. Nesting joins the enclosing transaction.\n transaction<T>(fn: () => Promise<T>): Promise<T>;\n docs: DocumentStore;\n lexical: LexicalIndex;\n vectors: VectorStore;\n raw: SqlSession;\n // Engine-level facts for `sense status` (e.g. a derived busy_timeout PRAGMA reading); each\n // store owns what it reports and how it is worded. Empty when there is nothing to report.\n engineStatus(): Promise<Record<string, string>>;\n close(): Promise<void>;\n}\n"],"names":["CAPABILITY_NAMES"],"mappings":"AAAA,yFAAyF;AACzF,4FAA4F;;;;;+BAW/EA;;;eAAAA;;;AAAN,IAAMA,mBAAmB;IAAC;IAAW;CAAU"}
package/dist/cjs/watch.js CHANGED
@@ -40,12 +40,38 @@ function _async_to_generator(fn) {
40
40
  });
41
41
  };
42
42
  }
43
+ function _define_property(obj, key, value) {
44
+ if (key in obj) {
45
+ Object.defineProperty(obj, key, {
46
+ value: value,
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true
50
+ });
51
+ } else obj[key] = value;
52
+ return obj;
53
+ }
43
54
  function _instanceof(left, right) {
44
55
  "@swc/helpers - instanceof";
45
56
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
46
57
  return !!right[Symbol.hasInstance](left);
47
58
  } else return left instanceof right;
48
59
  }
60
+ function _object_spread(target) {
61
+ for(var i = 1; i < arguments.length; i++){
62
+ var source = arguments[i] != null ? arguments[i] : {};
63
+ var ownKeys = Object.keys(source);
64
+ if (typeof Object.getOwnPropertySymbols === "function") {
65
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
66
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
67
+ }));
68
+ }
69
+ ownKeys.forEach(function(key) {
70
+ _define_property(target, key, source[key]);
71
+ });
72
+ }
73
+ return target;
74
+ }
49
75
  function _ts_generator(thisArg, body) {
50
76
  var f, y, t, _ = {
51
77
  label: 0,
@@ -145,11 +171,12 @@ function _ts_generator(thisArg, body) {
145
171
  };
146
172
  }
147
173
  }
148
- // Watch is a cache pre-warmer, not a correctness mechanism: open() always reconciles anyway, so any fs event just triggers a debounced full reconcile.
174
+ // Watch prepares the index for snapshot queries; filesystem events request debounced builds
175
+ // and periodic reconciliation recovers missed notifications.
149
176
  var DEBOUNCE_MS = 200;
150
177
  function runWatch(_0) {
151
178
  return _async_to_generator(function(cfg) {
152
- var opts, _opts_onEvent, _opts_debounceMs, _opts_heartbeatIntervalMs, _cfg_rootDir, _cfg_configDir, _opts_force, onEvent, debounceMs, reconcileIntervalMs, claimIntervalMs, rootDir, configDir, claimFailure, requestShutdown, claim, claimCloseStarted, closeClaim, _ref, initialStore, dbPath, initialWarnings, initialParsed, initialTotal, _tmp, stopping, running, queuedAlways, tick, startCycle, requestCycle, debounceTimer, scheduleReconcile, watcher, reconcileTimer, err, closeError;
179
+ var opts, _opts_onEvent, _opts_debounceMs, _opts_heartbeatIntervalMs, _cfg_rootDir, _cfg_configDir, _opts_force, onEvent, debounceMs, reconcileIntervalMs, claimIntervalMs, rootDir, configDir, claimFailure, requestShutdown, claim, claimCloseStarted, closeClaim, watcher, startup, startupNotification, scheduleReconcile, stopping, _opts_signal, startupEvents, _ref, initialStore, dbPath, initialWarnings, initialParsed, initialTotal, _tmp, _ref1, store, parsed, warnings, _, _tmp1, running, queuedAlways, tick, startCycle, requestCycle, debounceTimer, reconcileTimer, err, closeError;
153
180
  var _arguments = arguments;
154
181
  return _ts_generator(this, function(_state) {
155
182
  switch(_state.label){
@@ -178,14 +205,31 @@ function runWatch(_0) {
178
205
  claimCloseStarted = true;
179
206
  return claim.close();
180
207
  };
208
+ startup = true;
209
+ startupNotification = false;
210
+ stopping = false;
181
211
  _state.label = 2;
182
212
  case 2:
183
213
  _state.trys.push([
184
214
  2,
185
- 12,
186
- 17,
187
- 18
215
+ 22,
216
+ 27,
217
+ 28
188
218
  ]);
219
+ // Subscribe before the first build. Native watchers have no ready barrier, so startup also
220
+ // performs an unconditional catch-up pass after the initial build.
221
+ watcher = (0, _nodefs.watch)(rootDir, {
222
+ recursive: true
223
+ }, function(_event, filename) {
224
+ if (!(0, _watchnotificationts.shouldReconcileWatchNotification)(filename)) return;
225
+ if (startup) startupNotification = true;
226
+ else scheduleReconcile === null || scheduleReconcile === void 0 ? void 0 : scheduleReconcile();
227
+ });
228
+ watcher.on('error', function(err) {
229
+ claimFailure !== null && claimFailure !== void 0 ? claimFailure : claimFailure = err;
230
+ requestShutdown === null || requestShutdown === void 0 ? void 0 : requestShutdown(err);
231
+ });
232
+ startupEvents = [];
189
233
  return [
190
234
  4,
191
235
  (0, _indexts.openStore)(cfg)
@@ -237,7 +281,71 @@ function runWatch(_0) {
237
281
  ];
238
282
  case 10:
239
283
  if (claimFailure) throw claimFailure;
240
- stopping = false;
284
+ startupEvents.push({
285
+ parsed: initialParsed,
286
+ total: initialTotal,
287
+ warnings: initialWarnings
288
+ });
289
+ _state.label = 11;
290
+ case 11:
291
+ startupNotification = false;
292
+ return [
293
+ 4,
294
+ (0, _indexts.openStore)(cfg)
295
+ ];
296
+ case 12:
297
+ _ref1 = _state.sent(), store = _ref1.store, parsed = _ref1.parsed, warnings = _ref1.warnings;
298
+ _state.label = 13;
299
+ case 13:
300
+ _state.trys.push([
301
+ 13,
302
+ ,
303
+ 16,
304
+ 18
305
+ ]);
306
+ if (!(parsed > 0 || warnings.length > 0)) return [
307
+ 3,
308
+ 15
309
+ ];
310
+ _ = startupEvents.push;
311
+ _tmp1 = {
312
+ parsed: parsed
313
+ };
314
+ return [
315
+ 4,
316
+ (0, _indexts.docCount)(store)
317
+ ];
318
+ case 14:
319
+ _.apply(startupEvents, [
320
+ (_tmp1.total = _state.sent(), _tmp1.warnings = warnings, _tmp1)
321
+ ]);
322
+ _state.label = 15;
323
+ case 15:
324
+ return [
325
+ 3,
326
+ 18
327
+ ];
328
+ case 16:
329
+ return [
330
+ 4,
331
+ store.close()
332
+ ];
333
+ case 17:
334
+ _state.sent();
335
+ return [
336
+ 7
337
+ ];
338
+ case 18:
339
+ if (claimFailure) throw claimFailure;
340
+ _state.label = 19;
341
+ case 19:
342
+ if (startupNotification && !((_opts_signal = opts.signal) === null || _opts_signal === void 0 ? void 0 : _opts_signal.aborted)) return [
343
+ 3,
344
+ 11
345
+ ];
346
+ _state.label = 20;
347
+ case 20:
348
+ startup = false;
241
349
  // At most one open+reconcile+close cycle runs at a time; a trigger that arrives mid-cycle is
242
350
  // coalesced into a single rerun instead of opening a second, overlapping connection.
243
351
  running = null;
@@ -342,6 +450,8 @@ function runWatch(_0) {
342
450
  startCycle(alwaysEmit);
343
451
  };
344
452
  debounceTimer = null;
453
+ // Ignore our own state files, or cache and claim writes would retrigger reconciliation forever.
454
+ // An unresolvable filename reconciles because parsing nothing costs less than missing a real edit.
345
455
  scheduleReconcile = function scheduleReconcile() {
346
456
  if (debounceTimer) clearTimeout(debounceTimer);
347
457
  debounceTimer = setTimeout(function() {
@@ -349,14 +459,6 @@ function runWatch(_0) {
349
459
  requestCycle(true);
350
460
  }, debounceMs);
351
461
  };
352
- // Ignore our own state files, or cache and claim writes would retrigger reconciliation forever.
353
- // An unresolvable filename reconciles because parsing nothing costs less than missing a real edit.
354
- watcher = (0, _nodefs.watch)(rootDir, {
355
- recursive: true
356
- }, function(_event, filename) {
357
- if (!(0, _watchnotificationts.shouldReconcileWatchNotification)(filename)) return;
358
- scheduleReconcile();
359
- });
360
462
  reconcileTimer = setInterval((0, _guardedtickts.guardedTick)(function() {
361
463
  return _async_to_generator(function() {
362
464
  return _ts_generator(this, function(_state) {
@@ -389,7 +491,7 @@ function runWatch(_0) {
389
491
  (_opts_signal = opts.signal) === null || _opts_signal === void 0 ? void 0 : _opts_signal.removeEventListener('abort', stopNormally);
390
492
  clearInterval(reconcileTimer);
391
493
  if (debounceTimer) clearTimeout(debounceTimer);
392
- watcher.close();
494
+ watcher === null || watcher === void 0 ? void 0 : watcher.close();
393
495
  return [
394
496
  4,
395
497
  running
@@ -488,13 +590,30 @@ function runWatch(_0) {
488
590
  rootDir: rootDir,
489
591
  dbPath: dbPath
490
592
  });
491
- if (!stopping && (initialWarnings.length > 0 || initialParsed > 0)) {
492
- onEvent({
493
- type: 'reconciled',
494
- parsed: initialParsed,
495
- total: initialTotal,
496
- warnings: initialWarnings
497
- });
593
+ if (!stopping) {
594
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
595
+ try {
596
+ for(var _iterator = startupEvents[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
597
+ var event = _step.value;
598
+ if (stopping) break;
599
+ if (event.warnings.length > 0 || event.parsed > 0) onEvent(_object_spread({
600
+ type: 'reconciled'
601
+ }, event));
602
+ }
603
+ } catch (err) {
604
+ _didIteratorError = true;
605
+ _iteratorError = err;
606
+ } finally{
607
+ try {
608
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
609
+ _iterator.return();
610
+ }
611
+ } finally{
612
+ if (_didIteratorError) {
613
+ throw _iteratorError;
614
+ }
615
+ }
616
+ }
498
617
  }
499
618
  } catch (err) {
500
619
  shutdown(_instanceof(err, Error) ? err : new Error(String(err)));
@@ -502,46 +621,47 @@ function runWatch(_0) {
502
621
  }
503
622
  })
504
623
  ];
505
- case 11:
624
+ case 21:
506
625
  return [
507
626
  2,
508
627
  _state.sent()
509
628
  ];
510
- case 12:
629
+ case 22:
511
630
  err = _state.sent();
631
+ watcher === null || watcher === void 0 ? void 0 : watcher.close();
512
632
  if (claimCloseStarted) throw err;
513
- _state.label = 13;
514
- case 13:
633
+ _state.label = 23;
634
+ case 23:
515
635
  _state.trys.push([
516
- 13,
517
- 15,
636
+ 23,
637
+ 25,
518
638
  ,
519
- 16
639
+ 26
520
640
  ]);
521
641
  return [
522
642
  4,
523
643
  closeClaim()
524
644
  ];
525
- case 14:
645
+ case 24:
526
646
  _state.sent();
527
647
  return [
528
648
  3,
529
- 16
649
+ 26
530
650
  ];
531
- case 15:
651
+ case 25:
532
652
  closeError = _state.sent();
533
653
  throw new AggregateError([
534
654
  err,
535
655
  closeError
536
656
  ], 'watch setup and claim cleanup both failed');
537
- case 16:
657
+ case 26:
538
658
  throw err;
539
- case 17:
659
+ case 27:
540
660
  requestShutdown = undefined;
541
661
  return [
542
662
  7
543
663
  ];
544
- case 18:
664
+ case 28:
545
665
  return [
546
666
  2
547
667
  ];