Repository navigation
Expand file tree
/
Copy pathsqlite-index.mjs
More file actions
800 lines (730 loc) · 28 KB
/
Copy pathsqlite-index.mjs
File metadata and controls
800 lines (730 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
/**
* Rebuildable SQLite FTS5 derived search cache (Node >=24.9 built-in `node:sqlite`).
* Never a source of truth; Markdown/JSONL files remain canonical.
*/
import { closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync, rmSync } from 'node:fs'
import { dirname } from 'node:path'
import { DIR_MODE, FILE_MODE, normalizeText } from './security.mjs'
import { expandConceptSynonyms, extractEntities, normalizeQuery, tokenizeDocument } from './query-normalize.mjs'
let DatabaseSync = null
try {
const sqliteMod = await import('node:sqlite')
DatabaseSync = sqliteMod.DatabaseSync ?? null
} catch {
DatabaseSync = null
}
let cachedAvailable = null
/**
* Check whether Node built-in `node:sqlite` and FTS5 (`unicode61` + `trigram`) are available.
* @returns {boolean}
*/
export function sqliteAvailable() {
if (cachedAvailable !== null) return cachedAvailable
if (!DatabaseSync) {
cachedAvailable = false
return false
}
let db = null
try {
db = new DatabaseSync(':memory:')
db.exec(
"CREATE VIRTUAL TABLE _probe_u USING fts5(x, tokenize='unicode61');" +
"CREATE VIRTUAL TABLE _probe_t USING fts5(x, tokenize='trigram');"
)
cachedAvailable = true
} catch {
cachedAvailable = false
} finally {
try { db?.close() } catch {}
}
return cachedAvailable
}
const ENTITY_KIND_PRIORITY = {
preset_or_id: 0,
work: 1,
file: 2,
symbol: 3,
explicit: 4,
}
const SEARCH_INDEX_VERSION = '4'
const SYNONYM_WEIGHT = 0.55
const DAY_MS = 86_400_000
function timestamp(value) {
const ms = typeof value === 'string' ? Date.parse(value) : value instanceof Date ? value.getTime() : value
return Number.isFinite(ms) && Math.abs(ms) <= 8.64e15 ? ms : null
}
function freshness(modifiedAt, now) {
if (modifiedAt === null || now === null) return 1
const ageDays = Math.max(0, (now - modifiedAt) / DAY_MS)
return 0.85 + 0.15 * Math.pow(0.5, ageDays / 30)
}
function escapeFtsTerm(term) {
return `"${String(term).replace(/"/g, '""')}"`
}
function featureSimilarity(a, b) {
if (a.size === 0 || b.size === 0) return { overlap: 0, cosine: 0 }
let overlap = 0
const [smaller, larger] = a.size <= b.size ? [a, b] : [b, a]
for (const item of smaller) {
if (larger.has(item)) overlap += 1
}
return {
overlap,
cosine: overlap === 0 ? 0 : overlap / Math.sqrt(a.size * b.size),
}
}
function computeSupersededIds(hits) {
const ids = new Set()
for (const h of hits) {
if (h.status === 'superseded' && h.record_id) {
ids.add(h.record_id)
}
}
let changed = true
while (changed) {
changed = false
for (const h of hits) {
if (h.status !== 'superseded' && !ids.has(h.record_id) && h.supersedes) {
if (!ids.has(h.supersedes)) {
ids.add(h.supersedes)
changed = true
}
}
}
}
return ids
}
const STOP_TOKENS = new Set([
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'do', 'for', 'from', 'has', 'have',
'how', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'their', 'this', 'to',
'use', 'was', 'were', 'what', 'when', 'where', 'which', 'who', 'will', 'with', 'you', 'your',
])
function countDistinctBigramMatches(queryBigrams, docBigrams) {
let nonHan = 0
const han = []
for (const bg of queryBigrams) {
if (STOP_TOKENS.has(bg) || !docBigrams.has(bg)) continue
if (/\p{Script=Han}/u.test(bg)) han.push(bg)
else nonHan += 1
}
if (han.length <= 1) return han.length + nonHan
// Do not double-count overlapping Han bigrams from a single short word.
let independentHan = 0
const used = new Set()
for (const gram of han) {
if ([...gram].some((ch) => used.has(ch))) continue
independentHan += 1
for (const ch of gram) used.add(ch)
}
return independentHan + nonHan
}
function computeExactBonus(docLower, cleanedLower, clausesLower) {
if (cleanedLower.length >= 1 && docLower.trim() === cleanedLower) return 0.50
if (cleanedLower.length >= 2 && docLower.includes(cleanedLower)) return 0.35
if (clausesLower.length >= 2 && clausesLower.every((c) => docLower.includes(c))) return 0.20
if (clausesLower.some((c) => (c.length >= 3 || /[-_.\d]/.test(c)) && docLower.includes(c))) return 0.08
return 0
}
function buildFilterClause({ scope, branch, edition, includeSuperseded }) {
const clauses = []
const params = []
if (scope != null) {
clauses.push('d.scope = ?')
params.push(scope)
}
if (branch != null) {
clauses.push('(d.branch IS NULL OR d.branch = ?)')
params.push(branch)
} else {
clauses.push('d.branch IS NULL')
}
if (edition != null) {
clauses.push('d.edition = ?')
params.push(edition)
}
if (!includeSuperseded) {
clauses.push("(d.status IS NULL OR d.status != 'superseded')")
}
return {
key: `${scope != null ? 1 : 0}|${branch != null ? 1 : 0}|${edition != null ? 1 : 0}|${includeSuperseded ? 1 : 0}`,
whereSql: clauses.length > 0 ? clauses.join(' AND ') : '1=1',
params,
}
}
/**
* Open or initialize a rebuildable derived SQLite FTS5 index.
* @param {string} dbPath - `':memory:'` or a file path under `.cache/`.
*/
export function openDerivedIndex(dbPath) {
let handle
try { return initializeDerivedIndex(dbPath, db => { handle = db }) }
catch (error) {
try { handle?.close() } catch {}
const recoverable = [11, 26].includes(error?.errcode) ||
/SQLITE_CORRUPT|SQLITE_NOTADB|malformed|not a database|no such column|has no column|no such table/i.test(String(error?.message))
if (!dbPath || dbPath === ':memory:' || !recoverable) throw error
for (const suffix of ['', '-wal', '-shm']) rmSync(String(dbPath) + suffix, { force: true })
return initializeDerivedIndex(dbPath, () => {})
}
}
function initializeDerivedIndex(dbPath, opened) {
if (!sqliteAvailable()) return null
const targetPath = String(dbPath || ':memory:')
if (targetPath !== ':memory:') {
mkdirSync(dirname(targetPath), { recursive: true, mode: DIR_MODE })
const fd = openSync(targetPath, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK, FILE_MODE)
try {
const stat = fstatSync(fd)
if (!stat.isFile()) throw new Error('Unsafe derived index file')
if ((stat.mode & 0o077) !== 0) fchmodSync(fd, FILE_MODE)
} finally {
closeSync(fd)
}
}
const db = new DatabaseSync(targetPath)
opened(db)
if (targetPath !== ':memory:') {
db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;')
}
db.exec(`
CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS docs(
rowid INTEGER PRIMARY KEY,
doc_id TEXT UNIQUE,
scope TEXT,
branch TEXT,
edition TEXT,
file TEXT,
line INTEGER,
record_id TEXT,
status TEXT,
supersedes TEXT,
text TEXT,
body TEXT,
tokens TEXT,
modified_at INTEGER
);
CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(
tokens, text, content='docs', content_rowid='rowid', tokenize='unicode61'
);
CREATE VIRTUAL TABLE IF NOT EXISTS docs_tri USING fts5(
text, content='docs', content_rowid='rowid', tokenize='trigram'
);
CREATE TABLE IF NOT EXISTS entity_links(
record_id TEXT,
entity TEXT,
kind TEXT,
negated INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (record_id, entity)
);
CREATE INDEX IF NOT EXISTS idx_entity_links_entity ON entity_links(entity COLLATE NOCASE);
CREATE INDEX IF NOT EXISTS idx_docs_record_id ON docs(record_id);
`)
const entityCols = db.prepare('PRAGMA table_info(entity_links)').all()
if (!entityCols.some((c) => c.name === 'negated')) {
db.exec('ALTER TABLE entity_links ADD COLUMN negated INTEGER NOT NULL DEFAULT 0;')
db.exec("DELETE FROM meta WHERE key = 'revision';")
}
const docColumns = db.prepare('PRAGMA table_info(docs)').all()
if (!docColumns.some(column => column.name === 'body')) {
db.exec('ALTER TABLE docs ADD COLUMN body TEXT; UPDATE docs SET body = text;')
}
if (!docColumns.some(column => column.name === 'modified_at')) {
db.exec('ALTER TABLE docs ADD COLUMN modified_at INTEGER;')
}
const getMetaStmt = db.prepare('SELECT value FROM meta WHERE key = ?')
const setMetaStmt = db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)')
const insertDocStmt = db.prepare(
'INSERT INTO docs(doc_id, scope, branch, edition, file, line, record_id, status, supersedes, text, body, tokens, modified_at) ' +
'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
)
const insertEntityStmt = db.prepare(
'INSERT OR IGNORE INTO entity_links(record_id, entity, kind, negated) VALUES (?, ?, ?, ?)'
)
const getEntitiesByRecordStmt = db.prepare(
'SELECT record_id, entity, kind, negated FROM entity_links WHERE record_id = ?'
)
const countDocsStmt = db.prepare('SELECT COUNT(*) AS cnt FROM docs')
const countEntityDocsStmt = db.prepare(
'SELECT COUNT(DISTINCT record_id) AS cnt FROM entity_links WHERE entity COLLATE NOCASE = ?'
)
const stmtCache = new Map()
const featureCache = new Map()
function getRowFeatures(rowid, text) {
const key = Number(rowid)
let cached = featureCache.get(key)
if (!cached) {
const { bigrams, trigrams, concepts } = tokenizeDocument(text)
cached = {
bigrams,
trigrams,
concepts,
featureSet: new Set([...bigrams, ...trigrams]),
lowerText: text.toLowerCase(),
}
featureCache.set(key, cached)
}
return cached
}
function getSearchStmts(filterKey, whereSql) {
let entry = stmtCache.get(filterKey)
if (entry) return entry
entry = {
fts: db.prepare(
`SELECT d.rowid, d.doc_id, d.scope, d.branch, d.edition, d.file, d.line, d.record_id, d.status, d.supersedes, d.text, d.body, d.modified_at, ` +
`-bm25(docs_fts) AS fts_raw ` +
`FROM docs_fts JOIN docs d ON d.rowid = docs_fts.rowid ` +
`WHERE docs_fts MATCH ? AND (${whereSql}) ` +
`ORDER BY bm25(docs_fts) LIMIT ?`
),
tri: db.prepare(
`SELECT d.rowid, d.doc_id, d.scope, d.branch, d.edition, d.file, d.line, d.record_id, d.status, d.supersedes, d.text, d.body, d.modified_at, ` +
`-bm25(docs_tri) AS tri_raw ` +
`FROM docs_tri JOIN docs d ON d.rowid = docs_tri.rowid ` +
`WHERE docs_tri MATCH ? AND (${whereSql}) ` +
`ORDER BY bm25(docs_tri) LIMIT ?`
),
substr: db.prepare(
`SELECT d.rowid, d.doc_id, d.scope, d.branch, d.edition, d.file, d.line, d.record_id, d.status, d.supersedes, d.text, d.body, d.modified_at ` +
`FROM docs d WHERE (${whereSql}) AND instr(lower(d.text), ?) > 0 LIMIT ?`
),
hopWherePrefix: whereSql,
}
stmtCache.set(filterKey, entry)
return entry
}
let closed = false
function sync(revision, rows = []) {
if (closed) throw new Error('Derived index is closed')
const revStr = SEARCH_INDEX_VERSION + ':' + String(revision ?? '')
const current = getMetaStmt.get('revision')
if (current && current.value === revStr) {
return { rebuilt: false }
}
db.exec('BEGIN IMMEDIATE')
try {
db.exec('DELETE FROM entity_links; DELETE FROM docs;')
featureCache.clear()
for (let i = 0; i < rows.length; i += 1) {
const item = rows[i]
const body = normalizeText(String(item.text ?? ''))
const tags = Array.isArray(item.tags) ? item.tags.filter(tag => typeof tag === 'string') : []
const text = tags.length ? normalizeText([body, ...tags].join('\n')) : body
const docId = item.doc_id ?? item.docId ?? (item.file && item.line != null ? `${item.file}:${item.line}` : item.record_id ?? item.recordId ?? `doc_${i}`)
const recordId = item.record_id ?? item.recordId ?? docId
const scope = item.scope ?? null
const branch = item.branch ?? null
const edition = item.edition ?? null
const file = item.file ?? null
const line = item.line ?? null
const status = item.status ?? 'active'
const supersedes = item.supersedes ?? null
const { bigrams, trigrams, concepts, tokenString } = tokenizeDocument(text)
const modifiedAt = timestamp(item.updatedAt) ?? timestamp(item.createdAt)
const info = insertDocStmt.run(docId, scope, branch, edition, file, line, recordId, status, supersedes, text, body, tokenString, modifiedAt)
featureCache.set(Number(info.lastInsertRowid), {
bigrams,
trigrams,
concepts,
featureSet: new Set([...bigrams, ...trigrams]),
lowerText: text.toLowerCase(),
})
if (recordId != null) {
const entities = extractEntities(body)
if (Array.isArray(item.entities)) {
for (const extra of item.entities) {
if (!extra) continue
if (typeof extra === 'string') entities.push({ entity: extra, kind: 'explicit', negated: false })
else if (extra.entity) entities.push({ entity: String(extra.entity), kind: String(extra.kind ?? 'explicit'), negated: Boolean(extra.negated) })
}
}
for (const ent of entities) {
insertEntityStmt.run(recordId, ent.entity, ent.kind, ent.negated ? 1 : 0)
}
}
}
db.exec("INSERT INTO docs_fts(docs_fts) VALUES('rebuild'); INSERT INTO docs_tri(docs_tri) VALUES('rebuild');")
setMetaStmt.run('revision', revStr)
db.exec('COMMIT')
return { rebuilt: true, count: rows.length }
} catch (err) {
featureCache.clear()
try { db.exec('ROLLBACK') } catch {}
throw err
}
}
function search(query, { scope, branch, edition, includeSuperseded = false, expandHops = 1, limit = 8, now = Date.now() } = {}) {
if (closed) throw new Error('Derived index is closed')
if (limit <= 0) return { hits: [], expandedCount: 0, engine: 'sqlite-fts5' }
const parsed = normalizeQuery(query)
if (!parsed.cleaned.trim()) {
return { hits: [], expandedCount: 0, engine: 'sqlite-fts5' }
}
const filter = buildFilterClause({ scope, branch, edition, includeSuperseded })
const stmts = getSearchStmts(filter.key, filter.whereSql)
const candidateLimit = Math.max(limit * 6, 40)
const searchTime = timestamp(now)
const idClauses = new Set()
for (const c of parsed.clauses) {
if (/[_.\-\d]|[a-z][A-Z]/u.test(c) || (/\p{Script=Han}/u.test(c) && /[A-Za-z0-9]/.test(c))) {
idClauses.add(c.toLowerCase())
}
}
const allFtsCandidates = new Set([...parsed.words, ...parsed.bigrams, ...parsed.clauses.map((c) => c.toLowerCase())])
const idTerms = []
const regularTerms = []
const stopTerms = []
for (const term of allFtsCandidates) {
if (idClauses.has(term) || /[_.\-\d]/.test(term) || (/\p{Script=Han}/u.test(term) && /[a-z0-9]/.test(term))) {
idTerms.push(term)
} else if (STOP_TOKENS.has(term)) {
stopTerms.push(term)
} else {
regularTerms.push(term)
}
}
const ftsTerms = [...idTerms, ...regularTerms, ...stopTerms].slice(0, 32)
const synonymTerms = expandConceptSynonyms([...parsed.clauses, ...parsed.bigrams, ...parsed.words])
const triTerms = [...parsed.trigrams]
.filter((t) => [...t].length >= 3)
.slice(0, 24)
const candidates = new Map()
const upsertCandidate = (row, field, val) => {
let entry = candidates.get(row.rowid)
if (!entry) {
entry = {
rowid: row.rowid,
doc_id: row.doc_id,
scope: row.scope,
branch: row.branch,
edition: row.edition,
file: row.file,
line: row.line,
record_id: row.record_id,
status: row.status,
supersedes: row.supersedes,
text: row.text,
body: row.body,
modifiedAt: row.modified_at,
ftsRaw: 0,
triRaw: 0,
synonymRaw: 0,
}
candidates.set(row.rowid, entry)
}
if (field && val > entry[field]) entry[field] = val
}
if (ftsTerms.length > 0) {
const ftsMatch = ftsTerms.map(escapeFtsTerm).join(' OR ')
try {
for (const row of stmts.fts.all(ftsMatch, ...filter.params, candidateLimit)) {
upsertCandidate(row, 'ftsRaw', Math.max(0, Number(row.fts_raw) || 0))
}
} catch {}
}
if (triTerms.length > 0) {
const triMatch = triTerms.map(escapeFtsTerm).join(' OR ')
try {
for (const row of stmts.tri.all(triMatch, ...filter.params, candidateLimit)) {
upsertCandidate(row, 'triRaw', Math.max(0, Number(row.tri_raw) || 0))
}
} catch {}
}
if (candidates.size === 0) {
const needle = parsed.cleaned.trim().toLowerCase()
if (needle) {
try {
for (const row of stmts.substr.all(...filter.params, needle, candidateLimit)) {
upsertCandidate(row, 'ftsRaw', 1)
}
} catch {}
}
}
if (synonymTerms.size) {
const match = [...synonymTerms].map(escapeFtsTerm).join(' OR ')
for (const row of stmts.fts.all(match, ...filter.params, candidateLimit)) {
upsertCandidate(row, 'synonymRaw', Math.max(0, Number(row.fts_raw) || 0))
}
}
if (candidates.size === 0) {
return { hits: [], expandedCount: 0, engine: 'sqlite-fts5' }
}
let maxFts = 0
let maxTri = 0
let maxSynonym = 0
for (const c of candidates.values()) {
if (c.ftsRaw > maxFts) maxFts = c.ftsRaw
if (c.triRaw > maxTri) maxTri = c.triRaw
if (c.synonymRaw > maxSynonym) maxSynonym = c.synonymRaw
}
const queryFeatureSet = new Set([...parsed.bigrams, ...parsed.trigrams])
if (queryFeatureSet.size === 0) {
for (const c of parsed.clauses) queryFeatureSet.add(c.toLowerCase())
}
const cleanedLower = parsed.cleaned.toLowerCase()
const clausesLower = parsed.clauses.map((c) => c.toLowerCase())
const queryHanTrigrams = [...parsed.trigrams].filter((t) => /\p{Script=Han}/u.test(t))
const isMultiTermQuery = parsed.bigrams.size >= 2 || clausesLower.length >= 2
const directHits = []
const synonymOnly = new Set()
for (const c of candidates.values()) {
const ftsNorm = maxFts > 0 ? c.ftsRaw / maxFts : 0
const triNorm = maxTri > 0 ? c.triRaw / maxTri : 0
const docFeatures = getRowFeatures(c.rowid, c.text)
const { overlap, cosine: ngramCosine } = featureSimilarity(queryFeatureSet, docFeatures.featureSet)
const exactBonus = computeExactBonus(docFeatures.lowerText, cleanedLower, clausesLower)
const distinctBigrams = countDistinctBigramMatches(parsed.bigrams, docFeatures.bigrams)
const hanTrigramMatches = queryHanTrigrams.reduce(
(acc, tri) => acc + (docFeatures.trigrams.has(tri) ? 1 : 0),
0,
)
const synonymMatch = c.synonymRaw > 0 && [...docFeatures.concepts].some(term => synonymTerms.has(term))
const synonymScore = synonymMatch ? SYNONYM_WEIGHT * (0.50 * c.synonymRaw / maxSynonym + 0.25 * triNorm + 0.25 * ngramCosine) : 0
const score = 0.50 * ftsNorm + 0.25 * triNorm + 0.25 * ngramCosine + exactBonus
directHits.push({
doc_id: c.doc_id,
scope: c.scope,
branch: c.branch,
edition: c.edition,
file: c.file,
line: c.line,
record_id: c.record_id,
status: c.status,
supersedes: c.supersedes,
text: c.body,
score,
ftsNorm,
triNorm,
ngramCosine,
exactBonus,
viaHop: null,
supersededPath: false,
_synonymScore: synonymScore,
_freshness: freshness(c.modifiedAt, searchTime),
_overlap: overlap,
_distinctBigrams: distinctBigrams,
_hanTrigramMatches: hanTrigramMatches,
})
}
directHits.sort((a, b) => b.score - a.score)
const topScore = directHits[0]?.score ?? 0
const lexicalMatch = h => {
if (h.exactBonus > 0) return true
if (h._distinctBigrams === 0 && h._hanTrigramMatches === 0) return false
if (!isMultiTermQuery) return true
if (h._distinctBigrams < 2 && h._hanTrigramMatches === 0) return false
if (clausesLower.length < 2) return true
if (h._overlap <= 1 && (queryFeatureSet.size >= 5 || topScore >= 0.45)) return false
return !(topScore >= 0.5 && h.ngramCosine < 0.14 && h.score < topScore * 0.25)
}
const filteredDirect = directHits.filter(h => {
if (lexicalMatch(h)) return true
if (!h._synonymScore) return false
synonymOnly.add(h.doc_id)
h.score = h._synonymScore
return true
})
for (const h of filteredDirect) {
h.score *= h._freshness
delete h._freshness
}
const compareHits = (a, b) => Number(synonymOnly.has(a.doc_id)) - Number(synonymOnly.has(b.doc_id)) || b.score - a.score
filteredDirect.sort(compareHits)
for (const h of filteredDirect) {
delete h._synonymScore
delete h._overlap
delete h._distinctBigrams
delete h._hanTrigramMatches
}
const topDirect = filteredDirect.slice(0, limit)
if (topDirect.length === 0) {
return { hits: [], expandedCount: 0, engine: 'sqlite-fts5' }
}
// Compute supersession before 1-hop source selection so negated entities on active hits are skipped.
const preSupersededIds = computeSupersededIds(topDirect)
// Bounded 1-hop entity expansion.
const expandedHits = []
if (expandHops >= 1 && topDirect.length > 0) {
const entityPool = new Map()
for (let idx = 0; idx < topDirect.length; idx += 1) {
const hit = topDirect[idx]
if (!hit.record_id) continue
const selfSuperseded = Boolean(hit.status === 'superseded' || preSupersededIds.has(hit.record_id))
const linkedEnts = getEntitiesByRecordStmt.all(hit.record_id)
for (const ent of linkedEnts) {
if (!selfSuperseded && ent.negated) continue
const key = ent.entity.toLowerCase()
const priority = ENTITY_KIND_PRIORITY[ent.kind] ?? 9
let slot = entityPool.get(key)
if (!slot) {
slot = { entity: ent.entity, kind: ent.kind, priority, bestHitIdx: idx, sources: [] }
entityPool.set(key, slot)
} else {
if (priority < slot.priority) slot.priority = priority
if (idx < slot.bestHitIdx) slot.bestHitIdx = idx
}
slot.sources.push(hit)
}
}
const totalDocs = Number(countDocsStmt.get()?.cnt ?? 0)
const hubThreshold = Math.max(16, Math.floor(totalDocs * 0.25))
const selectedEntities = [...entityPool.values()]
.filter((slot) => Number(countEntityDocsStmt.get(slot.entity)?.cnt ?? 0) <= hubThreshold)
.sort((a, b) => a.priority - b.priority || a.bestHitIdx - b.bestHitIdx)
.slice(0, 4)
if (selectedEntities.length > 0) {
const directDocIds = new Set(topDirect.map((h) => h.doc_id))
const placeholders = selectedEntities.map(() => '?').join(', ')
const hopSql =
`SELECT d.rowid, d.doc_id, d.scope, d.branch, d.edition, d.file, d.line, d.record_id, d.status, d.supersedes, d.text, d.body, d.modified_at, el.entity AS matched_entity ` +
`FROM entity_links el JOIN docs d ON d.record_id = el.record_id ` +
`WHERE el.entity COLLATE NOCASE IN (${placeholders}) AND (${filter.whereSql})`
const hopRows = db.prepare(hopSql).all(
...selectedEntities.map((s) => s.entity),
...filter.params
)
const grouped = new Map()
for (const row of hopRows) {
if (directDocIds.has(row.doc_id)) continue
const slot = entityPool.get(row.matched_entity.toLowerCase())
if (!slot) continue
let entry = grouped.get(row.doc_id)
if (!entry) {
entry = { row, sources: [] }
grouped.set(row.doc_id, entry)
}
for (const srcHit of slot.sources) {
if (srcHit.record_id !== row.record_id) {
entry.sources.push({
fromRecordId: srcHit.record_id,
entity: slot.entity,
fromScore: srcHit.score,
fromHitIdx: topDirect.indexOf(srcHit),
})
}
}
}
const hopCandidates = [...grouped.values()]
.filter((g) => g.sources.length > 0)
.sort((a, b) => {
const bestA = Math.min(...a.sources.map((s) => s.fromHitIdx))
const bestB = Math.min(...b.sources.map((s) => s.fromHitIdx))
return bestA - bestB || b.sources.length - a.sources.length
})
.slice(0, 4)
for (const cand of hopCandidates) {
const { row, sources } = cand
const docFeatures = getRowFeatures(row.rowid, row.text)
const { cosine: ngramCosine } = featureSimilarity(queryFeatureSet, docFeatures.featureSet)
const bestFromScore = Math.max(...sources.map((s) => s.fromScore))
const score = (bestFromScore * 0.65 + 0.25 * ngramCosine) * freshness(row.modified_at, searchTime)
expandedHits.push({
doc_id: row.doc_id,
scope: row.scope,
branch: row.branch,
edition: row.edition,
file: row.file,
line: row.line,
record_id: row.record_id,
status: row.status,
supersedes: row.supersedes,
text: row.body,
score,
ftsNorm: 0,
triNorm: 0,
ngramCosine,
exactBonus: 0,
viaHop: null,
supersededPath: false,
_sources: sources,
})
}
}
}
// Supersession awareness across direct + expanded hits.
const allHits = [...topDirect, ...expandedHits]
const supersededIds = computeSupersededIds(allHits)
for (const h of topDirect) {
h.supersededPath = Boolean(h.status === 'superseded' || (h.record_id && supersededIds.has(h.record_id)))
}
for (const h of expandedHits) {
const sources = h._sources
delete h._sources
const activeSources = sources.filter((s) => !supersededIds.has(s.fromRecordId))
const selfSuperseded = Boolean(h.status === 'superseded' || (h.record_id && supersededIds.has(h.record_id)))
if (selfSuperseded || activeSources.length === 0) {
h.supersededPath = true
const chosen = activeSources[0] ?? sources[0]
h.viaHop = { fromRecordId: chosen.fromRecordId, entity: chosen.entity }
} else {
h.supersededPath = false
h.viaHop = { fromRecordId: activeSources[0].fromRecordId, entity: activeSources[0].entity }
}
}
allHits.sort((a, b) => Number(a.supersededPath) - Number(b.supersededPath) || compareHits(a, b))
const hits = allHits.slice(0, limit)
const expandedCount = hits.filter((h) => h.viaHop !== null).length
return {
hits,
expandedCount,
engine: 'sqlite-fts5',
}
}
function close() {
if (closed) return
closed = true
stmtCache.clear()
featureCache.clear()
db.close()
}
return { sync, search, close }
}
/**
* Bounded LRU cache of in-memory (`:memory:`) derived SQLite indexes with zero disk I/O.
* @param {number} [maxEntries=16]
* @returns {{ get: (cacheKey: string, revision: string | number, rows?: Array<object>) => ReturnType<typeof openDerivedIndex>, clear: () => void }}
*/
export function createMemoryIndexCache(maxEntries = 16) {
const cap = Number.isFinite(maxEntries) ? Math.floor(maxEntries) : 16
if (cap <= 0) {
return {
get() { return null },
clear() {},
}
}
const cache = new Map()
function get(cacheKey, revision, rows = []) {
if (!sqliteAvailable()) return null
const key = String(cacheKey ?? '')
const existing = cache.get(key)
if (existing) {
cache.delete(key)
cache.set(key, existing)
existing.sync(revision, rows)
return existing
}
if (cache.size >= cap) {
const oldestKey = cache.keys().next().value
const oldestIdx = cache.get(oldestKey)
cache.delete(oldestKey)
try { oldestIdx?.close() } catch {}
}
const idx = openDerivedIndex(':memory:')
if (!idx) return null
try {
idx.sync(revision, rows)
} catch (err) {
try { idx.close() } catch {}
throw err
}
cache.set(key, idx)
return idx
}
function clear() {
for (const idx of cache.values()) {
try { idx.close() } catch {}
}
cache.clear()
}
return { get, clear }
}