sensemaking 0.19.1 → 0.20.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 (167) hide show
  1. package/dist/cjs/chunk/extract.d.cts +1 -0
  2. package/dist/cjs/chunk/extract.d.ts +1 -0
  3. package/dist/cjs/chunk/extract.js +23 -5
  4. package/dist/cjs/chunk/extract.js.map +1 -1
  5. package/dist/cjs/chunk/index.d.cts +1 -1
  6. package/dist/cjs/chunk/index.d.ts +1 -1
  7. package/dist/cjs/chunk/index.js +3 -0
  8. package/dist/cjs/chunk/index.js.map +1 -1
  9. package/dist/cjs/index.d.cts +1 -1
  10. package/dist/cjs/index.d.ts +1 -1
  11. package/dist/cjs/index.js +3 -0
  12. package/dist/cjs/index.js.map +1 -1
  13. package/dist/cjs/scan/pool.d.cts +15 -0
  14. package/dist/cjs/scan/pool.d.ts +15 -0
  15. package/dist/cjs/scan/pool.js +263 -0
  16. package/dist/cjs/scan/pool.js.map +1 -0
  17. package/dist/cjs/scan/reparse.d.cts +2 -0
  18. package/dist/cjs/scan/reparse.d.ts +2 -0
  19. package/dist/cjs/scan/reparse.js +15 -76
  20. package/dist/cjs/scan/reparse.js.map +1 -1
  21. package/dist/cjs/store/builder.d.cts +11 -0
  22. package/dist/cjs/store/builder.d.ts +11 -0
  23. package/dist/cjs/store/builder.js +27 -0
  24. package/dist/cjs/store/builder.js.map +1 -0
  25. package/dist/cjs/store/duckdb/fieldStats.js +87 -10
  26. package/dist/cjs/store/duckdb/fieldStats.js.map +1 -1
  27. package/dist/cjs/store/duckdb/lexical.d.cts +1 -0
  28. package/dist/cjs/store/duckdb/lexical.d.ts +1 -0
  29. package/dist/cjs/store/duckdb/lexical.js +21 -5
  30. package/dist/cjs/store/duckdb/lexical.js.map +1 -1
  31. package/dist/cjs/store/duckdb/open.d.cts +9 -8
  32. package/dist/cjs/store/duckdb/open.d.ts +9 -8
  33. package/dist/cjs/store/duckdb/open.js +69 -120
  34. package/dist/cjs/store/duckdb/open.js.map +1 -1
  35. package/dist/cjs/store/duckdb/reconcile.d.cts +2 -6
  36. package/dist/cjs/store/duckdb/reconcile.d.ts +2 -6
  37. package/dist/cjs/store/duckdb/reconcile.js +45 -581
  38. package/dist/cjs/store/duckdb/reconcile.js.map +1 -1
  39. package/dist/cjs/store/duckdb/store.d.cts +1 -2
  40. package/dist/cjs/store/duckdb/store.d.ts +1 -2
  41. package/dist/cjs/store/duckdb/store.js +3 -26
  42. package/dist/cjs/store/duckdb/store.js.map +1 -1
  43. package/dist/cjs/store/index.d.cts +9 -3
  44. package/dist/cjs/store/index.d.ts +9 -3
  45. package/dist/cjs/store/index.js +40 -7
  46. package/dist/cjs/store/index.js.map +1 -1
  47. package/dist/cjs/store/open.d.cts +15 -0
  48. package/dist/cjs/store/open.d.ts +15 -0
  49. package/dist/cjs/store/open.js +516 -0
  50. package/dist/cjs/store/open.js.map +1 -0
  51. package/dist/cjs/store/reconcile.d.cts +7 -0
  52. package/dist/cjs/store/reconcile.d.ts +7 -0
  53. package/dist/cjs/store/reconcile.js +752 -0
  54. package/dist/cjs/store/reconcile.js.map +1 -0
  55. package/dist/cjs/store/shared.d.cts +1 -0
  56. package/dist/cjs/store/shared.d.ts +1 -0
  57. package/dist/cjs/store/shared.js +37 -0
  58. package/dist/cjs/store/shared.js.map +1 -1
  59. package/dist/cjs/store/signature.d.cts +3 -0
  60. package/dist/cjs/store/signature.d.ts +3 -0
  61. package/dist/cjs/store/signature.js +162 -0
  62. package/dist/cjs/store/signature.js.map +1 -0
  63. package/dist/cjs/store/sqlite/open.d.cts +9 -9
  64. package/dist/cjs/store/sqlite/open.d.ts +9 -9
  65. package/dist/cjs/store/sqlite/open.js +188 -198
  66. package/dist/cjs/store/sqlite/open.js.map +1 -1
  67. package/dist/cjs/store/sqlite/reconcile.d.cts +5 -10
  68. package/dist/cjs/store/sqlite/reconcile.d.ts +5 -10
  69. package/dist/cjs/store/sqlite/reconcile.js +48 -850
  70. package/dist/cjs/store/sqlite/reconcile.js.map +1 -1
  71. package/dist/cjs/store/sqlite/store.d.cts +1 -1
  72. package/dist/cjs/store/sqlite/store.d.ts +1 -1
  73. package/dist/cjs/store/sqlite/store.js +3 -13
  74. package/dist/cjs/store/sqlite/store.js.map +1 -1
  75. package/dist/cjs/store/turso/open.d.cts +6 -11
  76. package/dist/cjs/store/turso/open.d.ts +6 -11
  77. package/dist/cjs/store/turso/open.js +78 -169
  78. package/dist/cjs/store/turso/open.js.map +1 -1
  79. package/dist/cjs/store/turso/reconcile.d.cts +5 -6
  80. package/dist/cjs/store/turso/reconcile.d.ts +5 -6
  81. package/dist/cjs/store/turso/reconcile.js +169 -729
  82. package/dist/cjs/store/turso/reconcile.js.map +1 -1
  83. package/dist/cjs/store/turso/store.d.cts +1 -2
  84. package/dist/cjs/store/turso/store.d.ts +1 -2
  85. package/dist/cjs/store/turso/store.js +1 -12
  86. package/dist/cjs/store/turso/store.js.map +1 -1
  87. package/dist/cjs/store/types.d.cts +28 -6
  88. package/dist/cjs/store/types.d.ts +28 -6
  89. package/dist/cjs/store/types.js +14 -0
  90. package/dist/cjs/store/types.js.map +1 -1
  91. package/dist/cjs/text/strip.js +3 -6
  92. package/dist/cjs/text/strip.js.map +1 -1
  93. package/dist/cjs/watch.js +28 -16
  94. package/dist/cjs/watch.js.map +1 -1
  95. package/dist/esm/chunk/extract.d.ts +1 -0
  96. package/dist/esm/chunk/extract.js +10 -2
  97. package/dist/esm/chunk/extract.js.map +1 -1
  98. package/dist/esm/chunk/index.d.ts +1 -1
  99. package/dist/esm/chunk/index.js +1 -1
  100. package/dist/esm/chunk/index.js.map +1 -1
  101. package/dist/esm/index.d.ts +1 -1
  102. package/dist/esm/index.js +1 -1
  103. package/dist/esm/index.js.map +1 -1
  104. package/dist/esm/scan/pool.d.ts +15 -0
  105. package/dist/esm/scan/pool.js +77 -0
  106. package/dist/esm/scan/pool.js.map +1 -0
  107. package/dist/esm/scan/reparse.d.ts +2 -0
  108. package/dist/esm/scan/reparse.js +11 -58
  109. package/dist/esm/scan/reparse.js.map +1 -1
  110. package/dist/esm/store/builder.d.ts +11 -0
  111. package/dist/esm/store/builder.js +14 -0
  112. package/dist/esm/store/builder.js.map +1 -0
  113. package/dist/esm/store/duckdb/fieldStats.js +32 -19
  114. package/dist/esm/store/duckdb/fieldStats.js.map +1 -1
  115. package/dist/esm/store/duckdb/lexical.d.ts +1 -0
  116. package/dist/esm/store/duckdb/lexical.js +22 -9
  117. package/dist/esm/store/duckdb/lexical.js.map +1 -1
  118. package/dist/esm/store/duckdb/open.d.ts +9 -8
  119. package/dist/esm/store/duckdb/open.js +32 -57
  120. package/dist/esm/store/duckdb/open.js.map +1 -1
  121. package/dist/esm/store/duckdb/reconcile.d.ts +2 -6
  122. package/dist/esm/store/duckdb/reconcile.js +24 -117
  123. package/dist/esm/store/duckdb/reconcile.js.map +1 -1
  124. package/dist/esm/store/duckdb/store.d.ts +1 -2
  125. package/dist/esm/store/duckdb/store.js +4 -11
  126. package/dist/esm/store/duckdb/store.js.map +1 -1
  127. package/dist/esm/store/index.d.ts +9 -3
  128. package/dist/esm/store/index.js +23 -7
  129. package/dist/esm/store/index.js.map +1 -1
  130. package/dist/esm/store/open.d.ts +15 -0
  131. package/dist/esm/store/open.js +137 -0
  132. package/dist/esm/store/open.js.map +1 -0
  133. package/dist/esm/store/reconcile.d.ts +7 -0
  134. package/dist/esm/store/reconcile.js +132 -0
  135. package/dist/esm/store/reconcile.js.map +1 -0
  136. package/dist/esm/store/shared.d.ts +1 -0
  137. package/dist/esm/store/shared.js +9 -0
  138. package/dist/esm/store/shared.js.map +1 -1
  139. package/dist/esm/store/signature.d.ts +3 -0
  140. package/dist/esm/store/signature.js +35 -0
  141. package/dist/esm/store/signature.js.map +1 -0
  142. package/dist/esm/store/sqlite/open.d.ts +9 -9
  143. package/dist/esm/store/sqlite/open.js +81 -111
  144. package/dist/esm/store/sqlite/open.js.map +1 -1
  145. package/dist/esm/store/sqlite/reconcile.d.ts +5 -10
  146. package/dist/esm/store/sqlite/reconcile.js +31 -201
  147. package/dist/esm/store/sqlite/reconcile.js.map +1 -1
  148. package/dist/esm/store/sqlite/store.d.ts +1 -1
  149. package/dist/esm/store/sqlite/store.js +4 -7
  150. package/dist/esm/store/sqlite/store.js.map +1 -1
  151. package/dist/esm/store/turso/open.d.ts +6 -11
  152. package/dist/esm/store/turso/open.js +30 -77
  153. package/dist/esm/store/turso/open.js.map +1 -1
  154. package/dist/esm/store/turso/reconcile.d.ts +5 -6
  155. package/dist/esm/store/turso/reconcile.js +42 -146
  156. package/dist/esm/store/turso/reconcile.js.map +1 -1
  157. package/dist/esm/store/turso/store.d.ts +1 -2
  158. package/dist/esm/store/turso/store.js +2 -6
  159. package/dist/esm/store/turso/store.js.map +1 -1
  160. package/dist/esm/store/types.d.ts +28 -6
  161. package/dist/esm/store/types.js +12 -1
  162. package/dist/esm/store/types.js.map +1 -1
  163. package/dist/esm/text/strip.js +3 -4
  164. package/dist/esm/text/strip.js.map +1 -1
  165. package/dist/esm/watch.js +5 -3
  166. package/dist/esm/watch.js.map +1 -1
  167. package/package.json +2 -2
@@ -17,21 +17,19 @@ _export(exports, {
17
17
  get SCHEMA_VERSION () {
18
18
  return SCHEMA_VERSION;
19
19
  },
20
- get docCount () {
21
- return docCount;
22
- },
23
20
  get openSqlite () {
24
21
  return openSqlite;
22
+ },
23
+ get sqliteOpenDialect () {
24
+ return sqliteOpenDialect;
25
25
  }
26
26
  });
27
- var _nodefs = require("node:fs");
28
- var _nodepath = require("node:path");
29
27
  var _nodesqlite = require("node:sqlite");
30
28
  var _indexts = require("../../config/index.js");
31
- var _handoffts = require("../../embed/handoff.js");
32
29
  var _errorsts = require("../../errors.js");
33
30
  var _indexts1 = require("../../features/index.js");
34
- var _cachets = require("../cache.js");
31
+ var _indexts2 = require("../../scan/index.js");
32
+ var _opents = require("../open.js");
35
33
  var _sharedts = require("../shared.js");
36
34
  var _transactionts = require("../transaction.js");
37
35
  var _connectionts = require("./connection.js");
@@ -191,7 +189,7 @@ function _unsupported_iterable_to_array(o, minLen) {
191
189
  if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
192
190
  }
193
191
  var DB_FILENAME = 'cache.db';
194
- var SCHEMA_VERSION = '18';
192
+ var SCHEMA_VERSION = '19';
195
193
  // unicode61 splits on spaces, so a language written without them indexes a whole run as one
196
194
  // token and word search finds nothing; `content.tokenize` is how such a tree picks trigram.
197
195
  var DEFAULT_TOKENIZE = 'porter unicode61';
@@ -240,7 +238,7 @@ function createContentTable(conn, tokenize) {
240
238
  }
241
239
  // Content is a separate table (not a column on frontmatter) so `SELECT * FROM frontmatter`
242
240
  // can't dump file text into context. Features add their own tables after the core ones.
243
- function ensureSchema(conn, cfg, tokenize) {
241
+ function ensureSchemaTables(conn, cfg, tokenize) {
244
242
  return _async_to_generator(function() {
245
243
  var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, feature, err;
246
244
  return _ts_generator(this, function(_state) {
@@ -386,75 +384,65 @@ function setJournalWal(db) {
386
384
  }
387
385
  }
388
386
  }
389
- function connect(cfg) {
387
+ function connect(dbPath, cfg) {
388
+ return _async_to_generator(function() {
389
+ var db, conn, tokenize;
390
+ return _ts_generator(this, function(_state) {
391
+ db = new _nodesqlite.DatabaseSync(dbPath);
392
+ try {
393
+ // Before journal_mode, not after: converting a fresh database to WAL takes a brief exclusive
394
+ // lock, and with no timeout set yet a second process opening the same tree fails in 1ms.
395
+ db.exec('PRAGMA busy_timeout = 30000');
396
+ // busy_timeout does not cover the WAL conversion itself: SQLite does not invoke the busy
397
+ // handler for it, so a concurrent cold open needs its own bounded wait.
398
+ setJournalWal(db);
399
+ (0, _sqlfunctionsts.registerFunctions)(db, (0, _indexts.contentTokenize)(cfg) === undefined);
400
+ conn = (0, _connectionts.createConnection)(db);
401
+ // Before the rebuild branch below, never after: that branch deletes the cache, so a typo'd
402
+ // tokenizer validated later would cost a full re-index (and re-embed) to reach its own error.
403
+ tokenize = resolveTokenize(db, cfg);
404
+ return [
405
+ 2,
406
+ {
407
+ handle: {
408
+ db: db,
409
+ tokenize: tokenize
410
+ },
411
+ conn: conn
412
+ }
413
+ ];
414
+ } catch (err) {
415
+ // A throw here must release this handle, or on Windows the leaked WAL db is undeletable and
416
+ // scratch cleanup fails with EPERM/EBUSY.
417
+ db.close();
418
+ throw err;
419
+ }
420
+ return [
421
+ 2
422
+ ];
423
+ });
424
+ })();
425
+ }
426
+ function close(handle) {
427
+ return _async_to_generator(function() {
428
+ return _ts_generator(this, function(_state) {
429
+ handle.db.close();
430
+ return [
431
+ 2
432
+ ];
433
+ });
434
+ })();
435
+ }
436
+ // Only the tokenizer moved, and frontmatter, links, sections and embeddings are file-derived
437
+ // and tokenizer-independent. Any other signature change takes the full clear/reopen in open.ts.
438
+ function partialRebuild(handle, conn, _cfg, changedKeys) {
390
439
  return _async_to_generator(function() {
391
- var stateDir, dbPath, db, closed, _ref, conn, tokenize, version, features, wantFeatures, tokenizeOnlyRebuild, changedKeys, changed, stored, rebuildWarnings, recordedMaxMs, _ref1, parsed, warnings, err;
392
440
  return _ts_generator(this, function(_state) {
393
441
  switch(_state.label){
394
442
  case 0:
395
- stateDir = (0, _nodepath.join)(cfg.baseDir, _indexts.STATE_DIR);
396
- (0, _nodefs.mkdirSync)(stateDir, {
397
- recursive: true
398
- });
399
- dbPath = (0, _nodepath.join)(stateDir, DB_FILENAME);
400
- db = new _nodesqlite.DatabaseSync(dbPath);
401
- // A throw below must release this handle, or on Windows the leaked WAL db is undeletable and
402
- // scratch cleanup fails with EPERM/EBUSY. `closed` keeps the catch from double-closing.
403
- closed = false;
404
- _state.label = 1;
405
- case 1:
406
- _state.trys.push([
407
- 1,
408
- 15,
409
- ,
410
- 16
411
- ]);
412
- // Before journal_mode, not after: converting a fresh database to WAL takes a brief exclusive
413
- // lock, and with no timeout set yet a second process opening the same tree fails in 1ms.
414
- db.exec('PRAGMA busy_timeout = 30000');
415
- // busy_timeout does not cover the WAL conversion itself: SQLite does not invoke the busy
416
- // handler for it, so a concurrent cold open needs its own bounded wait.
417
- setJournalWal(db);
418
- (0, _sqlfunctionsts.registerFunctions)(db, (0, _indexts.contentTokenize)(cfg) === undefined);
419
- conn = (0, _connectionts.createConnection)(db);
420
- db.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)');
421
- // Before the rebuild branch below, never after: that branch deletes the cache, so a typo'd
422
- // tokenizer validated later would cost a full re-index (and re-embed) to reach its own error.
423
- tokenize = resolveTokenize(db, cfg);
424
- return [
425
- 4,
426
- (0, _sharedts.getMeta)(conn, 'schema_version')
427
- ];
428
- case 2:
429
- version = _state.sent();
430
- return [
431
- 4,
432
- (0, _sharedts.getMeta)(conn, 'features')
433
- ];
434
- case 3:
435
- features = _state.sent();
436
- wantFeatures = (0, _indexts.featureSignature)(cfg, _indexts1.FEATURES);
437
- tokenizeOnlyRebuild = false;
438
- if (!(version !== null && version !== SCHEMA_VERSION || features !== null && features !== wantFeatures)) return [
439
- 3,
440
- 8
441
- ];
442
- // Indexing derives from presets, so a config edit rebuilding the cache must say so and
443
- // name what changed -- silent rebuilds make derived indexing look like a hang or a bug.
444
- if (version !== null && version !== SCHEMA_VERSION) {
445
- console.error('sense: cache format changed (new sensemaking version); rebuilding the index');
446
- closed = true;
447
- db.close();
448
- (0, _cachets.clearCache)(cfg);
449
- return [
450
- 2,
451
- connect(cfg)
452
- ];
453
- }
454
- changedKeys = (0, _reconcilets.changedSignatureKeys)(features !== null && features !== void 0 ? features : '', wantFeatures);
455
443
  if (!(changedKeys.size === 1 && changedKeys.has('tokenize'))) return [
456
- 3,
457
- 5
444
+ 2,
445
+ false
458
446
  ];
459
447
  console.error('sense: config change (content tokenizer) rebuilds the text index; vectors, links, and sections are kept');
460
448
  // One transaction, so a crash before COMMIT rolls back to the old tokenizer's table rather
@@ -474,7 +462,7 @@ function connect(cfg) {
474
462
  _state.sent();
475
463
  return [
476
464
  4,
477
- createContentTable(conn, tokenize)
465
+ createContentTable(conn, handle.tokenize)
478
466
  ];
479
467
  case 2:
480
468
  _state.sent();
@@ -486,173 +474,175 @@ function connect(cfg) {
486
474
  })();
487
475
  }, _transactionts.BEGIN_WRITE)
488
476
  ];
489
- case 4:
477
+ case 1:
490
478
  _state.sent();
491
- tokenizeOnlyRebuild = true;
492
479
  return [
493
- 3,
494
- 8
495
- ];
496
- case 5:
497
- if (!(changedKeys.size === 1 && changedKeys.has('embed') && (0, _reconcilets.embedIdentityAdopted)(features !== null && features !== void 0 ? features : '', wantFeatures))) return [
498
- 3,
499
- 7
480
+ 2,
481
+ true
500
482
  ];
501
- // First sight of a resolved weight identity: the model itself hasn't changed, so
502
- // adopt it into meta with no rebuild and no re-embed, mirroring the tokenize precedent.
503
- console.error("sense: recorded the embedding model's resolved identity; vectors are unaffected");
483
+ }
484
+ });
485
+ })();
486
+ }
487
+ // Tokenize-only rebuild: only `content` is repopulated (the other tables are tokenizer-independent)
488
+ // and no feature extractors run. Warnings come from the reparse, since mtimes stay untouched and reconcile would never reparse them.
489
+ function postSchemaRebuild(_handle, conn, cfg, baseDir, wantFeatures) {
490
+ return _async_to_generator(function() {
491
+ var stmt, known, _, files, segmenting, warnings, rows, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, file, _warnings, _parseFile, doc, fileWarnings;
492
+ return _ts_generator(this, function(_state) {
493
+ switch(_state.label){
494
+ case 0:
504
495
  return [
505
496
  4,
506
- (0, _sharedts.setMeta)(conn, 'features', wantFeatures)
507
- ];
508
- case 6:
509
- _state.sent();
510
- return [
511
- 3,
512
- 8
497
+ conn.prepare('SELECT "path" FROM frontmatter')
513
498
  ];
514
- case 7:
515
- changed = (0, _reconcilets.signatureDiff)(features !== null && features !== void 0 ? features : '', wantFeatures);
516
- console.error("sense: config change (".concat(changed, ") rebuilds the index"));
517
- closed = true;
518
- db.close();
519
- (0, _cachets.clearCache)(cfg);
499
+ case 1:
500
+ stmt = _state.sent();
501
+ _ = Set.bind;
520
502
  return [
521
- 2,
522
- connect(cfg)
503
+ 4,
504
+ stmt.all()
523
505
  ];
524
- case 8:
525
- // Meta can lie after a crash between table creation and the signature write; the table's own
526
- // DDL cannot, so a mismatch here rebuilds whatever meta says.
527
- stored = storedTokenize(db);
528
- if (stored !== null && stored !== tokenize) {
529
- console.error('sense: cache was built with a different content tokenizer; rebuilding the index');
530
- closed = true;
531
- db.close();
532
- (0, _cachets.clearCache)(cfg);
533
- return [
534
- 2,
535
- connect(cfg)
536
- ];
506
+ case 2:
507
+ known = new (_.apply(Set, [
508
+ void 0,
509
+ _state.sent().map(function(r) {
510
+ return r.path;
511
+ })
512
+ ]));
513
+ files = (0, _indexts2.listFiles)(cfg, baseDir).filter(function(f) {
514
+ return known.has(f.relPath);
515
+ });
516
+ segmenting = (0, _indexts.contentTokenize)(cfg) === undefined;
517
+ warnings = [];
518
+ rows = [];
519
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
520
+ try {
521
+ for(_iterator = files[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
522
+ file = _step.value;
523
+ ;
524
+ _parseFile = (0, _indexts2.parseFile)(file), doc = _parseFile.doc, fileWarnings = _parseFile.warnings;
525
+ (_warnings = warnings).push.apply(_warnings, _to_consumable_array(fileWarnings));
526
+ rows.push((0, _reconcilets.contentRow)(doc, segmenting));
527
+ }
528
+ } catch (err) {
529
+ _didIteratorError = true;
530
+ _iteratorError = err;
531
+ } finally{
532
+ try {
533
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
534
+ _iterator.return();
535
+ }
536
+ } finally{
537
+ if (_didIteratorError) {
538
+ throw _iteratorError;
539
+ }
540
+ }
537
541
  }
538
- // One writer at a time: the feature hooks check a column then add it, so two cold opens racing
539
- // here both see it missing and the second ALTER fails with a duplicate column.
540
542
  return [
541
543
  4,
542
544
  (0, _transactionts.withTransaction)(conn, function() {
543
- return ensureSchema(conn, cfg, tokenize);
545
+ return _async_to_generator(function() {
546
+ return _ts_generator(this, function(_state) {
547
+ switch(_state.label){
548
+ case 0:
549
+ if (!(rows.length > 0)) return [
550
+ 3,
551
+ 2
552
+ ];
553
+ return [
554
+ 4,
555
+ conn.runBatch(_reconcilets.INSERT_CONTENT_SQL, rows)
556
+ ];
557
+ case 1:
558
+ _state.sent();
559
+ _state.label = 2;
560
+ case 2:
561
+ return [
562
+ 2
563
+ ];
564
+ }
565
+ });
566
+ })();
544
567
  }, _transactionts.BEGIN_WRITE)
545
568
  ];
546
- case 9:
569
+ case 3:
547
570
  _state.sent();
548
- rebuildWarnings = [];
549
- if (!tokenizeOnlyRebuild) return [
550
- 3,
551
- 12
552
- ];
553
- return [
554
- 4,
555
- (0, _reconcilets.rebuildContentTable)(conn, cfg, cfg.baseDir)
556
- ];
557
- case 10:
558
- rebuildWarnings = _state.sent();
559
571
  return [
560
572
  4,
561
573
  (0, _sharedts.setMeta)(conn, 'features', wantFeatures)
562
574
  ];
563
- case 11:
575
+ case 4:
564
576
  _state.sent();
565
- _state.label = 12;
566
- case 12:
567
- return [
568
- 4,
569
- (0, _sharedts.getMeta)(conn, 'reconcile_max_ms')
570
- ];
571
- case 13:
572
- recordedMaxMs = Number.apply(void 0, [
573
- (_ref = _state.sent()) !== null && _ref !== void 0 ? _ref : '0'
574
- ]);
575
- db.exec("PRAGMA busy_timeout = ".concat(Math.min(Math.max(30000, 3 * recordedMaxMs), 600000)));
576
- return [
577
- 4,
578
- (0, _reconcilets.reconcile)(conn, cfg, cfg.baseDir)
579
- ];
580
- case 14:
581
- _ref1 = _state.sent(), parsed = _ref1.parsed, warnings = _ref1.warnings;
582
577
  return [
583
578
  2,
584
- {
585
- db: db,
586
- conn: conn,
587
- cfg: cfg,
588
- dbPath: dbPath,
589
- parsed: parsed,
590
- warnings: _to_consumable_array(rebuildWarnings).concat(_to_consumable_array(warnings))
591
- }
592
- ];
593
- case 15:
594
- err = _state.sent();
595
- if (!closed) db.close();
596
- throw err;
597
- case 16:
598
- return [
599
- 2
579
+ warnings
600
580
  ];
601
581
  }
602
582
  });
603
583
  })();
604
584
  }
605
- function openSqlite(cfg) {
585
+ // Meta can lie after a crash between table creation and the signature write; the table's own
586
+ // DDL cannot, so a mismatch here rebuilds whatever meta says.
587
+ function extraRebuildReason(handle) {
588
+ var stored = storedTokenize(handle.db);
589
+ if (stored !== null && stored !== handle.tokenize) return 'cache was built with a different content tokenizer';
590
+ return null;
591
+ }
592
+ function ensureSchema(handle, conn, cfg) {
606
593
  return _async_to_generator(function() {
607
- var _ref, db, conn, resolvedCfg, dbPath, parsed, warnings, store;
608
594
  return _ts_generator(this, function(_state) {
609
595
  switch(_state.label){
610
596
  case 0:
597
+ // One writer at a time: the feature hooks check a column then add it, so two cold opens racing
598
+ // here both see it missing and the second ALTER fails with a duplicate column.
611
599
  return [
612
600
  4,
613
- connect(cfg)
601
+ (0, _transactionts.withTransaction)(conn, function() {
602
+ return ensureSchemaTables(conn, cfg, handle.tokenize);
603
+ }, _transactionts.BEGIN_WRITE)
614
604
  ];
615
605
  case 1:
616
- _ref = _state.sent(), db = _ref.db, conn = _ref.conn, resolvedCfg = _ref.cfg, dbPath = _ref.dbPath, parsed = _ref.parsed, warnings = _ref.warnings;
617
- store = (0, _storets.createStore)(db, conn, resolvedCfg, resolvedCfg.baseDir);
618
- // reconcile ran before this object existed, so its chunk text is keyed by the connection.
619
- (0, _handoffts.rekeyChunkText)(conn, store);
606
+ _state.sent();
620
607
  return [
621
- 2,
622
- {
623
- store: store,
624
- cfg: resolvedCfg,
625
- dbPath: dbPath,
626
- parsed: parsed,
627
- warnings: warnings
628
- }
608
+ 2
629
609
  ];
630
610
  }
631
611
  });
632
612
  })();
633
613
  }
634
- function docCount(store) {
614
+ function setDerivedBusyTimeout(handle, _conn, ms) {
635
615
  return _async_to_generator(function() {
636
- var stmt;
637
616
  return _ts_generator(this, function(_state) {
638
- switch(_state.label){
639
- case 0:
640
- return [
641
- 4,
642
- store.prepare('SELECT COUNT(*) AS n FROM frontmatter')
643
- ];
644
- case 1:
645
- stmt = _state.sent();
646
- return [
647
- 4,
648
- stmt.get()
649
- ];
650
- case 2:
651
- return [
652
- 2,
653
- _state.sent().n
654
- ];
655
- }
617
+ handle.db.exec("PRAGMA busy_timeout = ".concat(ms));
618
+ return [
619
+ 2
620
+ ];
621
+ });
622
+ })();
623
+ }
624
+ var sqliteOpenDialect = {
625
+ filename: DB_FILENAME,
626
+ schemaVersion: SCHEMA_VERSION,
627
+ reconcileDialect: _reconcilets.sqliteDialect,
628
+ connect: connect,
629
+ close: close,
630
+ partialRebuild: partialRebuild,
631
+ postSchemaRebuild: postSchemaRebuild,
632
+ extraRebuildReason: extraRebuildReason,
633
+ ensureSchema: ensureSchema,
634
+ setDerivedBusyTimeout: setDerivedBusyTimeout,
635
+ createStore: function createStore(handle, conn, cfg) {
636
+ return (0, _storets.createStore)(handle.db, conn, cfg);
637
+ }
638
+ };
639
+ function openSqlite(cfg) {
640
+ return _async_to_generator(function() {
641
+ return _ts_generator(this, function(_state) {
642
+ return [
643
+ 2,
644
+ (0, _opents.openWithDialect)(cfg, sqliteOpenDialect)
645
+ ];
656
646
  });
657
647
  })();
658
648
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/sqlite/open.ts"],"sourcesContent":["// The Node floor (>=22.20) is explained here and nowhere else: 22.20 is the first release with\n// both FTS5 and row-returning INSERT ... RETURNING. Raise it only for a load-bearing capability.\nimport { mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\nimport type { Config, ResolvedConfig } from '../../config/index.ts';\nimport { contentTokenize, featureSignature, STATE_DIR } from '../../config/index.ts';\nimport { rekeyChunkText } from '../../embed/handoff.ts';\nimport { SenseError } from '../../errors.ts';\nimport { activeFeatures, FEATURES } from '../../features/index.ts';\nimport { clearCache } from '../cache.ts';\nimport { getMeta, setMeta } from '../shared.ts';\nimport { BEGIN_WRITE, withTransaction } from '../transaction.ts';\nimport type { Connection, Store } from '../types.ts';\nimport { createConnection } from './connection.ts';\nimport { changedSignatureKeys, embedIdentityAdopted, rebuildContentTable, reconcile, signatureDiff } from './reconcile.ts';\nimport { registerFunctions } from './sql-functions.ts';\nimport { createStore } from './store.ts';\n\nexport const DB_FILENAME = 'cache.db';\n// Cache shape version, independent of the config's own `version`. Bumping it rebuilds\n// existing trees on first query.\nexport const SCHEMA_VERSION = '18';\n\ninterface ConnectResult {\n db: DatabaseSync;\n conn: Connection;\n cfg: ResolvedConfig;\n dbPath: string;\n parsed: number;\n warnings: string[];\n}\n\nexport interface OpenResult {\n store: Store;\n cfg: ResolvedConfig;\n dbPath: string;\n parsed: number;\n warnings: string[];\n}\n\n// unicode61 splits on spaces, so a language written without them indexes a whole run as one\n// token and word search finds nothing; `content.tokenize` is how such a tree picks trigram.\nconst DEFAULT_TOKENIZE = 'porter unicode61';\n\n// FTS5 takes its tokenizer as a DDL string literal where nothing can bind, so the configured\n// value is concatenated; probing a throwaway table first is both the safety and the validation.\nfunction resolveTokenize(db: DatabaseSync, cfg: Config): string {\n const configured = contentTokenize(cfg);\n if (configured === undefined) return DEFAULT_TOKENIZE;\n const literal = configured.replace(/'/g, \"''\");\n try {\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n db.exec(`CREATE VIRTUAL TABLE temp.sense_tokenize_probe USING fts5(x, tokenize = '${literal}')`);\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n } catch (err) {\n throw new SenseError('CONFIG_INVALID', `content.tokenize \"${configured}\" is not a tokenizer this SQLite accepts (${(err as Error).message}); the built-in choices are unicode61, ascii, porter, and trigram, each with their own options`);\n }\n return literal;\n}\n\n// The tokenizer the content table was actually built with, from its own DDL -- the one\n// record that cannot desynchronize from the table. NULL when the table does not exist yet.\nfunction storedTokenize(db: DatabaseSync): string | null {\n const row = db.prepare(`SELECT sql FROM sqlite_master WHERE name = 'content'`).get() as { sql: string } | undefined;\n if (!row) return null;\n const m = row.sql.match(/tokenize = '((?:[^']|'')*)'/);\n return m ? m[1] : null;\n}\n\n// The `_seg` sidecars are appended after path, never inserted: bm25() and snippet(content, 2)\n// are documented against the first three columns. Each holds its field's exploded unspaced runs.\nasync function createContentTable(conn: Connection, tokenize: string): Promise<void> {\n await conn.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS content USING fts5(title, summary, text, path UNINDEXED, title_seg, summary_seg, text_seg, tokenize = '${tokenize}')`);\n}\n\n// Content is a separate table (not a column on frontmatter) so `SELECT * FROM frontmatter`\n// can't dump file text into context. Features add their own tables after the core ones.\nasync function ensureSchema(conn: Connection, cfg: Config, tokenize: string): Promise<void> {\n await conn.exec(`CREATE TABLE IF NOT EXISTS frontmatter (\"path\" TEXT PRIMARY KEY, \"_mtime\" REAL, \"_ctime\" REAL, \"_size\" INTEGER, \"_parse_error\" TEXT)`);\n // IF NOT EXISTS is safe against a tokenizer change: open() compares the table's own DDL\n // against the resolved tokenizer before this runs, so a stale table is already gone by now.\n await createContentTable(conn, tokenize);\n // Coverage, not ownership: a path can appear under several presets. path leads the PK so the\n // per-doc delete is an index hit -- keyed the other way, cold builds went quadratic.\n await conn.exec(`CREATE TABLE IF NOT EXISTS preset_files (\"path\" TEXT, preset TEXT, PRIMARY KEY (\"path\", preset))`);\n await conn.exec('CREATE INDEX IF NOT EXISTS preset_files_preset ON preset_files(preset)');\n for (const feature of activeFeatures(cfg)) await feature.schema(conn);\n if ((await getMeta(conn, 'schema_version')) === null) await setMeta(conn, 'schema_version', SCHEMA_VERSION);\n if ((await getMeta(conn, 'features')) === null) await setMeta(conn, 'features', featureSignature(cfg, FEATURES));\n}\n\n// Two processes opening the same fresh tree both try to convert it, and the loser gets SQLITE_BUSY\n// with no busy handler behind it. Bounded because a lock held past this is a real problem, not a race.\nfunction setJournalWal(db: DatabaseSync): void {\n const deadline = Date.now() + 5000;\n for (;;) {\n try {\n db.exec('PRAGMA journal_mode = WAL');\n return;\n } catch (err) {\n if (Date.now() >= deadline || !/database is locked|busy/i.test((err as Error).message)) throw err;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);\n }\n }\n}\n\nasync function connect(cfg: ResolvedConfig): Promise<ConnectResult> {\n const stateDir = join(cfg.baseDir, STATE_DIR);\n mkdirSync(stateDir, { recursive: true });\n const dbPath = join(stateDir, DB_FILENAME);\n\n const db = new DatabaseSync(dbPath);\n // A throw below must release this handle, or on Windows the leaked WAL db is undeletable and\n // scratch cleanup fails with EPERM/EBUSY. `closed` keeps the catch from double-closing.\n let closed = false;\n try {\n // Before journal_mode, not after: converting a fresh database to WAL takes a brief exclusive\n // lock, and with no timeout set yet a second process opening the same tree fails in 1ms.\n db.exec('PRAGMA busy_timeout = 30000');\n // busy_timeout does not cover the WAL conversion itself: SQLite does not invoke the busy\n // handler for it, so a concurrent cold open needs its own bounded wait.\n setJournalWal(db);\n registerFunctions(db, contentTokenize(cfg) === undefined);\n const conn = createConnection(db);\n\n db.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)');\n\n // Before the rebuild branch below, never after: that branch deletes the cache, so a typo'd\n // tokenizer validated later would cost a full re-index (and re-embed) to reach its own error.\n const tokenize = resolveTokenize(db, cfg);\n\n // Schema-version or feature-set mismatch: reconcile only reparses changed files, so an\n // old cache can't be patched incrementally -- rebuild instead (cheap: nothing expensive lives here).\n const version = await getMeta(conn, 'schema_version');\n const features = await getMeta(conn, 'features');\n const wantFeatures = featureSignature(cfg, FEATURES);\n let tokenizeOnlyRebuild = false;\n if ((version !== null && version !== SCHEMA_VERSION) || (features !== null && features !== wantFeatures)) {\n // Indexing derives from presets, so a config edit rebuilding the cache must say so and\n // name what changed -- silent rebuilds make derived indexing look like a hang or a bug.\n if (version !== null && version !== SCHEMA_VERSION) {\n console.error('sense: cache format changed (new sensemaking version); rebuilding the index');\n closed = true;\n db.close();\n clearCache(cfg);\n return connect(cfg);\n }\n const changedKeys = changedSignatureKeys(features ?? '', wantFeatures);\n // Only the tokenizer moved, and frontmatter, links, sections and embeddings are file-derived\n // and tokenizer-independent. Any other signature change takes the full clear/reopen below.\n if (changedKeys.size === 1 && changedKeys.has('tokenize')) {\n console.error('sense: config change (content tokenizer) rebuilds the text index; vectors, links, and sections are kept');\n // One transaction, so a crash before COMMIT rolls back to the old tokenizer's table rather\n // than to no table. IF EXISTS makes a retry after such a crash a no-op, not a raw error.\n await withTransaction(\n conn,\n async () => {\n await conn.exec('DROP TABLE IF EXISTS content');\n await createContentTable(conn, tokenize);\n },\n BEGIN_WRITE\n );\n tokenizeOnlyRebuild = true;\n } else if (changedKeys.size === 1 && changedKeys.has('embed') && embedIdentityAdopted(features ?? '', wantFeatures)) {\n // First sight of a resolved weight identity: the model itself hasn't changed, so\n // adopt it into meta with no rebuild and no re-embed, mirroring the tokenize precedent.\n console.error(\"sense: recorded the embedding model's resolved identity; vectors are unaffected\");\n await setMeta(conn, 'features', wantFeatures);\n } else {\n const changed = signatureDiff(features ?? '', wantFeatures);\n console.error(`sense: config change (${changed}) rebuilds the index`);\n closed = true;\n db.close();\n clearCache(cfg);\n return connect(cfg);\n }\n }\n\n // Meta can lie after a crash between table creation and the signature write; the table's own\n // DDL cannot, so a mismatch here rebuilds whatever meta says.\n const stored = storedTokenize(db);\n if (stored !== null && stored !== tokenize) {\n console.error('sense: cache was built with a different content tokenizer; rebuilding the index');\n closed = true;\n db.close();\n clearCache(cfg);\n return connect(cfg);\n }\n\n // One writer at a time: the feature hooks check a column then add it, so two cold opens racing\n // here both see it missing and the second ALTER fails with a duplicate column.\n await withTransaction(conn, () => ensureSchema(conn, cfg, tokenize), BEGIN_WRITE);\n\n let rebuildWarnings: string[] = [];\n if (tokenizeOnlyRebuild) {\n rebuildWarnings = await rebuildContentTable(conn, cfg, cfg.baseDir);\n await setMeta(conn, 'features', wantFeatures);\n }\n\n // 3x the largest reconcile this cache has recorded, floored at 30s and capped at 10min.\n // Installed before reconcile() -- that call is the one that races a watcher's transaction.\n const recordedMaxMs = Number((await getMeta(conn, 'reconcile_max_ms')) ?? '0');\n db.exec(`PRAGMA busy_timeout = ${Math.min(Math.max(30000, 3 * recordedMaxMs), 600_000)}`);\n\n const { parsed, warnings } = await reconcile(conn, cfg, cfg.baseDir);\n\n return { db, conn, cfg, dbPath, parsed, warnings: [...rebuildWarnings, ...warnings] };\n } catch (err) {\n if (!closed) db.close();\n throw err;\n }\n}\n\n// The sqlite store's open: connects synchronously (see connect() above), then wraps the\n// resulting connection in the async Store interface.\nexport async function openSqlite(cfg: ResolvedConfig): Promise<OpenResult> {\n const { db, conn, cfg: resolvedCfg, dbPath, parsed, warnings } = await connect(cfg);\n const store = createStore(db, conn, resolvedCfg, resolvedCfg.baseDir);\n // reconcile ran before this object existed, so its chunk text is keyed by the connection.\n rekeyChunkText(conn, store);\n return { store: store, cfg: resolvedCfg, dbPath, parsed, warnings };\n}\n\nexport async function docCount(store: Store): Promise<number> {\n const stmt = await store.prepare('SELECT COUNT(*) AS n FROM frontmatter');\n return ((await stmt.get()) as { n: number }).n;\n}\n"],"names":["DB_FILENAME","SCHEMA_VERSION","docCount","openSqlite","DEFAULT_TOKENIZE","resolveTokenize","db","cfg","configured","contentTokenize","undefined","literal","replace","exec","err","SenseError","message","storedTokenize","row","prepare","get","m","sql","match","createContentTable","conn","tokenize","ensureSchema","feature","activeFeatures","schema","getMeta","setMeta","featureSignature","FEATURES","setJournalWal","deadline","Date","now","test","Atomics","wait","Int32Array","SharedArrayBuffer","connect","stateDir","dbPath","closed","version","features","wantFeatures","tokenizeOnlyRebuild","changedKeys","changed","stored","rebuildWarnings","recordedMaxMs","parsed","warnings","join","baseDir","STATE_DIR","mkdirSync","recursive","DatabaseSync","registerFunctions","createConnection","console","error","close","clearCache","changedSignatureKeys","size","has","withTransaction","BEGIN_WRITE","embedIdentityAdopted","signatureDiff","rebuildContentTable","Number","Math","min","max","reconcile","resolvedCfg","store","createStore","rek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C9C2B;;;;oBAD2D;;wBAAMzC,QAAQrC;;;oBAAd,OAAA,eAAzDD,KAAyD,KAAzDA,IAAImB,OAAqD,KAArDA,MAAW2D,cAA0C,KAA/C7E,KAAkBuC,SAA6B,KAA7BA,QAAQW,SAAqB,KAArBA,QAAQC,WAAa,KAAbA;oBAC9C2B,QAAQC,IAAAA,oBAAW,EAAChF,IAAImB,MAAM2D,aAAaA,YAAYxB,OAAO;oBACpE,0FAA0F;oBAC1F2B,IAAAA,yBAAc,EAAC9D,MAAM4D;oBACrB;;wBAAO;4BAAEA,OAAOA;4BAAO9E,KAAK6E;4BAAatC,QAAAA;4BAAQW,QAAAA;4BAAQC,UAAAA;wBAAS;;;;IACpE;;AAEO,SAAexD,SAASmF,KAAY;;YACnCG;;;;oBAAO;;wBAAMH,MAAMlE,OAAO,CAAC;;;oBAA3BqE,OAAO;oBACJ;;wBAAMA,KAAKpE,GAAG;;;oBAAvB;;wBAAS,cAAoCqE,CAAC;;;;IAChD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/sqlite/open.ts"],"sourcesContent":["// The Node floor (>=22.20) is explained here and nowhere else: 22.20 is the first release with\n// both FTS5 and row-returning INSERT ... RETURNING. Raise it only for a load-bearing capability.\nimport { DatabaseSync } from 'node:sqlite';\nimport type { Config, ResolvedConfig } from '../../config/index.ts';\nimport { contentTokenize, featureSignature } from '../../config/index.ts';\nimport { SenseError } from '../../errors.ts';\nimport { activeFeatures, FEATURES } from '../../features/index.ts';\nimport { listFiles, parseFile } from '../../scan/index.ts';\nimport type { OpenResult } from '../open.ts';\nimport { openWithDialect } from '../open.ts';\nimport { getMeta, setMeta } from '../shared.ts';\nimport { BEGIN_WRITE, withTransaction } from '../transaction.ts';\nimport type { Connection, OpenDialect } from '../types.ts';\nimport { createConnection } from './connection.ts';\nimport { contentRow, INSERT_CONTENT_SQL, sqliteDialect } from './reconcile.ts';\nimport { registerFunctions } from './sql-functions.ts';\nimport { createStore } from './store.ts';\n\nexport const DB_FILENAME = 'cache.db';\n// Cache shape version, independent of the config's own `version`. Bumping it rebuilds\n// existing trees on first query.\nexport const SCHEMA_VERSION = '19';\n\nexport type { OpenResult };\n\n// unicode61 splits on spaces, so a language written without them indexes a whole run as one\n// token and word search finds nothing; `content.tokenize` is how such a tree picks trigram.\nconst DEFAULT_TOKENIZE = 'porter unicode61';\n\n// The connection plus this store's own extra state (types.ts's OpenDialect<Handle>): the\n// resolved tokenizer, threaded through connect, the tokenize-only rebuild, and ensureSchema.\ninterface SqliteHandle {\n db: DatabaseSync;\n tokenize: string;\n}\n\n// FTS5 takes its tokenizer as a DDL string literal where nothing can bind, so the configured\n// value is concatenated; probing a throwaway table first is both the safety and the validation.\nfunction resolveTokenize(db: DatabaseSync, cfg: Config): string {\n const configured = contentTokenize(cfg);\n if (configured === undefined) return DEFAULT_TOKENIZE;\n const literal = configured.replace(/'/g, \"''\");\n try {\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n db.exec(`CREATE VIRTUAL TABLE temp.sense_tokenize_probe USING fts5(x, tokenize = '${literal}')`);\n db.exec('DROP TABLE IF EXISTS temp.sense_tokenize_probe');\n } catch (err) {\n throw new SenseError('CONFIG_INVALID', `content.tokenize \"${configured}\" is not a tokenizer this SQLite accepts (${(err as Error).message}); the built-in choices are unicode61, ascii, porter, and trigram, each with their own options`);\n }\n return literal;\n}\n\n// The tokenizer the content table was actually built with, from its own DDL -- the one\n// record that cannot desynchronize from the table. NULL when the table does not exist yet.\nfunction storedTokenize(db: DatabaseSync): string | null {\n const row = db.prepare(`SELECT sql FROM sqlite_master WHERE name = 'content'`).get() as { sql: string } | undefined;\n if (!row) return null;\n const m = row.sql.match(/tokenize = '((?:[^']|'')*)'/);\n return m ? m[1] : null;\n}\n\n// The `_seg` sidecars are appended after path, never inserted: bm25() and snippet(content, 2)\n// are documented against the first three columns. Each holds its field's exploded unspaced runs.\nasync function createContentTable(conn: Connection, tokenize: string): Promise<void> {\n await conn.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS content USING fts5(title, summary, text, path UNINDEXED, title_seg, summary_seg, text_seg, tokenize = '${tokenize}')`);\n}\n\n// Content is a separate table (not a column on frontmatter) so `SELECT * FROM frontmatter`\n// can't dump file text into context. Features add their own tables after the core ones.\nasync function ensureSchemaTables(conn: Connection, cfg: Config, tokenize: string): Promise<void> {\n await conn.exec(`CREATE TABLE IF NOT EXISTS frontmatter (\"path\" TEXT PRIMARY KEY, \"_mtime\" REAL, \"_ctime\" REAL, \"_size\" INTEGER, \"_parse_error\" TEXT)`);\n // IF NOT EXISTS is safe against a tokenizer change: open() compares the table's own DDL\n // against the resolved tokenizer before this runs, so a stale table is already gone by now.\n await createContentTable(conn, tokenize);\n // Coverage, not ownership: a path can appear under several presets. path leads the PK so the\n // per-doc delete is an index hit -- keyed the other way, cold builds went quadratic.\n await conn.exec(`CREATE TABLE IF NOT EXISTS preset_files (\"path\" TEXT, preset TEXT, PRIMARY KEY (\"path\", preset))`);\n await conn.exec('CREATE INDEX IF NOT EXISTS preset_files_preset ON preset_files(preset)');\n for (const feature of activeFeatures(cfg)) await feature.schema(conn);\n if ((await getMeta(conn, 'schema_version')) === null) await setMeta(conn, 'schema_version', SCHEMA_VERSION);\n if ((await getMeta(conn, 'features')) === null) await setMeta(conn, 'features', featureSignature(cfg, FEATURES));\n}\n\n// Two processes opening the same fresh tree both try to convert it, and the loser gets SQLITE_BUSY\n// with no busy handler behind it. Bounded because a lock held past this is a real problem, not a race.\nfunction setJournalWal(db: DatabaseSync): void {\n const deadline = Date.now() + 5000;\n for (;;) {\n try {\n db.exec('PRAGMA journal_mode = WAL');\n return;\n } catch (err) {\n if (Date.now() >= deadline || !/database is locked|busy/i.test((err as Error).message)) throw err;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);\n }\n }\n}\n\nasync function connect(dbPath: string, cfg: ResolvedConfig): Promise<{ handle: SqliteHandle; conn: Connection }> {\n const db = new DatabaseSync(dbPath);\n try {\n // Before journal_mode, not after: converting a fresh database to WAL takes a brief exclusive\n // lock, and with no timeout set yet a second process opening the same tree fails in 1ms.\n db.exec('PRAGMA busy_timeout = 30000');\n // busy_timeout does not cover the WAL conversion itself: SQLite does not invoke the busy\n // handler for it, so a concurrent cold open needs its own bounded wait.\n setJournalWal(db);\n registerFunctions(db, contentTokenize(cfg) === undefined);\n const conn = createConnection(db);\n // Before the rebuild branch below, never after: that branch deletes the cache, so a typo'd\n // tokenizer validated later would cost a full re-index (and re-embed) to reach its own error.\n const tokenize = resolveTokenize(db, cfg);\n return { handle: { db, tokenize }, conn };\n } catch (err) {\n // A throw here must release this handle, or on Windows the leaked WAL db is undeletable and\n // scratch cleanup fails with EPERM/EBUSY.\n db.close();\n throw err;\n }\n}\n\nasync function close(handle: SqliteHandle): Promise<void> {\n handle.db.close();\n}\n\n// Only the tokenizer moved, and frontmatter, links, sections and embeddings are file-derived\n// and tokenizer-independent. Any other signature change takes the full clear/reopen in open.ts.\nasync function partialRebuild(handle: SqliteHandle, conn: Connection, _cfg: Config, changedKeys: Set<string>): Promise<boolean> {\n if (!(changedKeys.size === 1 && changedKeys.has('tokenize'))) return false;\n console.error('sense: config change (content tokenizer) rebuilds the text index; vectors, links, and sections are kept');\n // One transaction, so a crash before COMMIT rolls back to the old tokenizer's table rather\n // than to no table. IF EXISTS makes a retry after such a crash a no-op, not a raw error.\n await withTransaction(\n conn,\n async () => {\n await conn.exec('DROP TABLE IF EXISTS content');\n await createContentTable(conn, handle.tokenize);\n },\n BEGIN_WRITE\n );\n return true;\n}\n\n// Tokenize-only rebuild: only `content` is repopulated (the other tables are tokenizer-independent)\n// and no feature extractors run. Warnings come from the reparse, since mtimes stay untouched and reconcile would never reparse them.\nasync function postSchemaRebuild(_handle: SqliteHandle, conn: Connection, cfg: Config, baseDir: string, wantFeatures: string): Promise<string[]> {\n const stmt = await conn.prepare('SELECT \"path\" FROM frontmatter');\n const known = new Set(((await stmt.all()) as Array<{ path: string }>).map((r) => r.path));\n const files = listFiles(cfg, baseDir).filter((f) => known.has(f.relPath));\n const segmenting = contentTokenize(cfg) === undefined;\n const warnings: string[] = [];\n const rows: unknown[][] = [];\n for (const file of files) {\n const { doc, warnings: fileWarnings } = parseFile(file);\n warnings.push(...fileWarnings);\n rows.push(contentRow(doc, segmenting));\n }\n await withTransaction(\n conn,\n async () => {\n if (rows.length > 0) await conn.runBatch(INSERT_CONTENT_SQL, rows);\n },\n BEGIN_WRITE\n );\n await setMeta(conn, 'features', wantFeatures);\n return warnings;\n}\n\n// Meta can lie after a crash between table creation and the signature write; the table's own\n// DDL cannot, so a mismatch here rebuilds whatever meta says.\nfunction extraRebuildReason(handle: SqliteHandle): string | null {\n const stored = storedTokenize(handle.db);\n if (stored !== null && stored !== handle.tokenize) return 'cache was built with a different content tokenizer';\n return null;\n}\n\nasync function ensureSchema(handle: SqliteHandle, conn: Connection, cfg: Config): Promise<void> {\n // One writer at a time: the feature hooks check a column then add it, so two cold opens racing\n // here both see it missing and the second ALTER fails with a duplicate column.\n await withTransaction(conn, () => ensureSchemaTables(conn, cfg, handle.tokenize), BEGIN_WRITE);\n}\n\nasync function setDerivedBusyTimeout(handle: SqliteHandle, _conn: Connection, ms: number): Promise<void> {\n handle.db.exec(`PRAGMA busy_timeout = ${ms}`);\n}\n\n// This store's dialect (types.ts's OpenDialect) for the shared orchestration in store/open.ts.\nexport const sqliteOpenDialect: OpenDialect<SqliteHandle> = {\n filename: DB_FILENAME,\n schemaVersion: SCHEMA_VERSION,\n reconcileDialect: sqliteDialect,\n connect,\n close,\n partialRebuild,\n postSchemaRebuild,\n extraRebuildReason,\n ensureSchema,\n setDerivedBusyTimeout,\n createStore: (handle, conn, cfg) => createStore(handle.db, conn, cfg),\n};\n\nexport async function openSqlite(cfg: ResolvedConfig): Promise<OpenResult> {\n return openWithDialect(cfg, sqliteOpenDialect);\n}\n"],"names":["DB_FILENAME","SCHEMA_VERSION","openSqlite","sqliteOpenDialect","DEFAULT_TOKENIZE","resolveTokenize","db","cfg","configured","contentTokenize","undefined","literal","replace","exec","err","SenseError","message","storedTokenize","row","prepare","get","m","sql","match","createContentTable","conn","tokenize","ensureSchemaTables","feature","activeFeatures","schema","getMeta","setMeta","featureSignature","FEATURES","setJournalWal","deadline","Date","now","test","Atomics","wait","Int32Array","SharedArrayBuffer","connect","dbPath","DatabaseSync","registerFunctions","createConnection","handle","close","partialRebuild","_cfg","changedKeys","size","has","console","error","withTransaction","BEGIN_WRITE","postSchemaRebuild","_handle","baseDir","wantFeatures","stmt","known","files","segmenting","warnings","rows","file","parseFile","doc","fileWarnings","Set","all","map","r","path","listFiles","filter","f","relPath","push","contentRow","length","runBatch","INSERT_CONTENT_SQL","extraRebuildReason","stored","ensureSchema","setDerivedBusyTimeout","_conn","ms","filename","schemaVersion","reconcileDialect","sqliteDialect","createStore","openWithDialect"],"mappings":"AAAA,+FAA+F;AAC/F,iGAAiG;;;;;;;;;;;;QAiBpFA;eAAAA;;QAGAC;eAAAA;;QAoLSC;eAAAA;;QAdTC;eAAAA;;;0BAzLgB;uBAEqB;wBACvB;wBACc;wBACJ;sBAEL;wBACC;6BACY;4BAEZ;2BAC6B;8BAC5B;uBACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,IAAMH,cAAc;AAGpB,IAAMC,iBAAiB;AAI9B,4FAA4F;AAC5F,4FAA4F;AAC5F,IAAMG,mBAAmB;AASzB,6FAA6F;AAC7F,gGAAgG;AAChG,SAASC,gBAAgBC,EAAgB,EAAEC,GAAW;IACpD,IAAMC,aAAaC,IAAAA,wBAAe,EAACF;IACnC,IAAIC,eAAeE,WAAW,OAAON;IACrC,IAAMO,UAAUH,WAAWI,OAAO,CAAC,MAAM;IACzC,IAAI;QACFN,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B,EAAE2C,KAAiB,EAAEC,EAAU;;;YACtF5C,OAAO3C,EAAE,CAACO,IAAI,CAAC,AAAC,yBAA2B,OAAHgF;;;;;IAC1C;;AAGO,IAAM1F,oBAA+C;IAC1D2F,UAAU9F;IACV+F,eAAe9F;IACf+F,kBAAkBC,0BAAa;IAC/BrD,SAAAA;IACAM,OAAAA;IACAC,gBAAAA;IACAS,mBAAAA;IACA4B,oBAAAA;IACAE,cAAAA;IACAC,uBAAAA;IACAO,aAAa,SAAbA,YAAcjD,QAAQxB,MAAMlB;eAAQ2F,IAAAA,oBAAW,EAACjD,OAAO3C,EAAE,EAAEmB,MAAMlB;;AACnE;AAEO,SAAeL,WAAWK,GAAmB;;;YAClD;;gBAAO4F,IAAAA,uBAAe,EAAC5F,KAAKJ;;;IAC9B"}
@@ -1,10 +1,5 @@
1
- import type { Config } from '../../config/index.js';
2
- import type { Connection } from '../types.js';
3
- export declare function reconcile(conn: Connection, cfg: Config, baseDir: string): Promise<{
4
- parsed: number;
5
- warnings: string[];
6
- }>;
7
- export declare function changedSignatureKeys(before: string, after: string): Set<string>;
8
- export declare function embedIdentityAdopted(before: string, after: string): boolean;
9
- export declare function signatureDiff(before: string, after: string): string;
10
- export declare function rebuildContentTable(conn: Connection, cfg: Config, baseDir: string): Promise<string[]>;
1
+ import type { ParsedDoc } from '../../scan/index.js';
2
+ import type { ReconcileDialect } from '../types.js';
3
+ export declare const INSERT_CONTENT_SQL = "INSERT INTO content (rowid, title, summary, text, \"path\", title_seg, summary_seg, text_seg) VALUES ((SELECT rowid FROM frontmatter WHERE \"path\" = ?), ?, ?, ?, ?, ?, ?, ?)";
4
+ export declare function contentRow(doc: ParsedDoc, segmenting: boolean): unknown[];
5
+ export declare const sqliteDialect: ReconcileDialect;
@@ -1,10 +1,5 @@
1
- import type { Config } from '../../config/index.js';
2
- import type { Connection } from '../types.js';
3
- export declare function reconcile(conn: Connection, cfg: Config, baseDir: string): Promise<{
4
- parsed: number;
5
- warnings: string[];
6
- }>;
7
- export declare function changedSignatureKeys(before: string, after: string): Set<string>;
8
- export declare function embedIdentityAdopted(before: string, after: string): boolean;
9
- export declare function signatureDiff(before: string, after: string): string;
10
- export declare function rebuildContentTable(conn: Connection, cfg: Config, baseDir: string): Promise<string[]>;
1
+ import type { ParsedDoc } from '../../scan/index.js';
2
+ import type { ReconcileDialect } from '../types.js';
3
+ export declare const INSERT_CONTENT_SQL = "INSERT INTO content (rowid, title, summary, text, \"path\", title_seg, summary_seg, text_seg) VALUES ((SELECT rowid FROM frontmatter WHERE \"path\" = ?), ?, ?, ?, ?, ?, ?, ?)";
4
+ export declare function contentRow(doc: ParsedDoc, segmenting: boolean): unknown[];
5
+ export declare const sqliteDialect: ReconcileDialect;