/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/db/BxcDB * * Local agent index: documents, structure-aware chunks with provenance, a * title-boosted FTS5 index and dense embeddings. * * Storage decisions: * - Embeddings are `Float32Array` bytes in BLOB columns (4 bytes/dim), never * JSON text: search reads typed-array views instead of parsing strings. * - Every chunk carries provenance (`url`, `canonical_url`, `fetched_at`, * `profile`, `simhash`, `content_hash`, HTTP validators) and byte offsets * into the document text, so agents can cite and re-validate. * - SimHash is also stored as four 16-bit bands (indexed). Two 64-bit hashes * within 3 bits share at least one band (pigeonhole), so near-duplicate * lookup is an indexed query instead of a table scan. * - Semantic search uses an attached {@link VectorIndex} (native HNSW when * available) and falls back to an exact scan over BLOB embeddings. */ import { Database } from "bun:sqlite"; import { mkdirSync } from "node:fs"; import { homedir } from "node:os"; import { resolve } from "node:path"; import type { VectorIndex } from "../index/vector-index.ts"; import { cosineSimilarity } from "../utils/vector.ts"; export interface ScrapeRecordInput { url: string; profile: string; status: number; content: string; metadata: unknown; markdown?: string; jsonData?: unknown; openapiSpec?: unknown; /** Legacy dense vector; stored as a float32 BLOB. */ vector?: number[] | Float32Array; } /** Fetch provenance attached to a document and each of its chunks. */ export interface Provenance { canonicalUrl?: string | null; /** Hex digest of the extracted text (idempotency key). */ contentHash?: string | null; /** 16-hex-digit SimHash of the extracted text. */ simhash?: string | null; etag?: string | null; lastModified?: string | null; /** Epoch milliseconds. Default: now. */ fetchedAt?: number; } export interface ChunkInput { text: string; headingPath?: string[]; /** Offsets of `text` inside the document's extracted text. */ charStart?: number; charEnd?: number; embedding?: Float32Array | number[]; } export interface DocumentInput extends ScrapeRecordInput { provenance?: Provenance; embeddingModel?: string; chunks?: ChunkInput[]; chunkEmbeddingModel?: string; } export interface UpsertResult { id: number; /** `false` when the stored document already had the same content hash. */ changed: boolean; /** `true` when no row existed for the URL. */ inserted: boolean; } export interface SemanticHit { url: string; title: string; markdown: string; similarity: number; } export interface HybridHit { url: string; title: string; markdown: string; score: number; } export interface ChunkHit { chunkId: number; url: string; canonicalUrl: string | null; title: string; headingPath: string[]; text: string; charStart: number | null; charEnd: number | null; fetchedAt: number | null; profile: string | null; contentHash: string | null; score: number; } export interface NearDuplicate { id: number; url: string; simhash: string; distance: number; } /** Column weights for `bm25(scrapes_fts, url, title, markdown)`. */ const DOCUMENT_BM25 = "bm25(2.0, 10.0, 1.0)"; /** Column weights for `bm25(chunks_fts, heading, text)`. */ const CHUNK_BM25 = "bm25(4.0, 1.0)"; function toFloat32(vector: Float32Array | number[]): Float32Array { return vector instanceof Float32Array ? vector : Float32Array.from(vector); } function toBlob(vector: Float32Array | number[] | undefined | null): Uint8Array | null { if (!vector || vector.length === 0) return null; const f32 = toFloat32(vector); return new Uint8Array(f32.buffer, f32.byteOffset, f32.byteLength); } /** Zero-copy float32 view over a BLOB (copies only when misaligned). */ export function blobToFloat32(blob: Uint8Array | ArrayBuffer | null | undefined): Float32Array | null { if (!blob) return null; const bytes = blob instanceof Uint8Array ? blob : new Uint8Array(blob); if (bytes.byteLength === 0 || bytes.byteLength % 4 !== 0) return null; if (bytes.byteOffset % 4 === 0) { return new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4); } return new Float32Array(bytes.slice().buffer); } function dot(a: Float32Array, b: Float32Array): number { let sum = 0; for (let i = 0; i < a.length; i++) sum += (a[i] as number) * (b[i] as number); return sum; } function norm(a: Float32Array): number { return Math.sqrt(dot(a, a)); } /** Split a 16-hex-digit SimHash into four 16-bit bands. */ export function simhashBands(simhash: string): [number, number, number, number] | null { if (!/^[0-9a-f]{16}$/i.test(simhash)) return null; return [0, 4, 8, 12].map((i) => Number.parseInt(simhash.slice(i, i + 4), 16)) as [ number, number, number, number, ]; } export function simhashDistance(a: string, b: string): number { let x = BigInt(`0x${a}`) ^ BigInt(`0x${b}`); let count = 0; while (x) { x &= x - 1n; count++; } return count; } /** * Build an FTS5 query from free text. Terms are quoted (no operator * injection), Unicode letters/digits are kept (accents included), and terms * are joined with `mode` (`AND` for precision, `OR` for recall). */ export function ftsQuery(text: string, mode: "AND" | "OR" = "AND"): string { const terms = text.match(/[\p{L}\p{N}_]+/gu) ?? []; return terms.map((term) => `"${term}"`).join(mode === "AND" ? " " : " OR "); } function parseJson(value: string | null | undefined, fallback: T): T { if (!value) return fallback; try { return JSON.parse(value) as T; } catch { return fallback; } } export class BxcDB { private db: Database; #vectorIndex: VectorIndex | null = null; readonly #path: string; constructor(path?: string) { // Never derive the default from the working directory: each launch // directory would otherwise get its own database (and cache). const dbPath = path ?? Bun.env.BXC_DB_PATH ?? resolve(homedir(), ".bxc", "bxc.sqlite"); this.#path = dbPath; if (dbPath !== ":memory:") mkdirSync(resolve(dbPath, ".."), { recursive: true }); this.db = new Database(dbPath); this.db.exec("PRAGMA journal_mode = WAL;"); this.db.exec("PRAGMA synchronous = NORMAL;"); this.db.exec("PRAGMA busy_timeout = 5000;"); this.db.exec("PRAGMA cache_size = -16000;"); this.db.exec("PRAGMA foreign_keys = ON;"); this.initSchema(); this.insertStmt = this.db.prepare(` INSERT INTO scrapes (url, profile, status, content, metadata, markdown, json_data, openapi_spec, embedding, embedding_model, canonical_url, content_hash, simhash, simhash_b0, simhash_b1, simhash_b2, simhash_b3, etag, last_modified, fetched_at) VALUES ($url, $profile, $status, $content, $metadata, $markdown, $json, $openapi, $embedding, $embeddingModel, $canonical, $contentHash, $simhash, $b0, $b1, $b2, $b3, $etag, $lastModified, $fetchedAt) `); this.checkUrlStmt = this.db.prepare( "SELECT id, content_hash FROM scrapes WHERE url = ? ORDER BY id DESC LIMIT 1", ); this.updateStmt = this.db.prepare(` UPDATE scrapes SET profile = $profile, status = $status, content = $content, metadata = $metadata, markdown = $markdown, json_data = $json, openapi_spec = $openapi, embedding = $embedding, embedding_model = $embeddingModel, vector = NULL, canonical_url = $canonical, content_hash = $contentHash, simhash = $simhash, simhash_b0 = $b0, simhash_b1 = $b1, simhash_b2 = $b2, simhash_b3 = $b3, etag = $etag, last_modified = $lastModified, fetched_at = $fetchedAt, timestamp = CURRENT_TIMESTAMP WHERE id = $id `); this.touchStmt = this.db.prepare( "UPDATE scrapes SET fetched_at = ?, status = ?, etag = coalesce(?, etag), last_modified = coalesce(?, last_modified) WHERE id = ?", ); this.insertChunkStmt = this.db.prepare(` INSERT INTO chunks (scrape_id, url, canonical_url, chunk_index, heading_path, text, char_start, char_end, simhash, content_hash, fetched_at, profile, embedding, embedding_model) VALUES ($scrapeId, $url, $canonical, $index, $heading, $text, $start, $end, $simhash, $contentHash, $fetchedAt, $profile, $embedding, $embeddingModel) `); } private insertStmt: ReturnType; private checkUrlStmt: ReturnType; private updateStmt: ReturnType; private touchStmt: ReturnType; private insertChunkStmt: ReturnType; private addColumn(table: string, definition: string): void { try { this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${definition};`); } catch { // Column already exists. } } private initSchema() { this.db.exec(` CREATE TABLE IF NOT EXISTS scrapes ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, profile TEXT NOT NULL, status INTEGER, content TEXT, metadata TEXT, markdown TEXT, json_data TEXT, openapi_spec TEXT, vector TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS cookie_jars ( id TEXT PRIMARY KEY, data TEXT NOT NULL, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX IF NOT EXISTS idx_scrapes_url ON scrapes(url); CREATE INDEX IF NOT EXISTS idx_scrapes_timestamp ON scrapes(timestamp); `); for (const column of ["markdown TEXT", "json_data TEXT", "openapi_spec TEXT", "vector TEXT"]) { this.addColumn("scrapes", column); } for (const column of [ "embedding BLOB", "embedding_model TEXT", "canonical_url TEXT", "content_hash TEXT", "simhash TEXT", "simhash_b0 INTEGER", "simhash_b1 INTEGER", "simhash_b2 INTEGER", "simhash_b3 INTEGER", "etag TEXT", "last_modified TEXT", "fetched_at INTEGER", ]) { this.addColumn("scrapes", column); } this.db.exec(` CREATE INDEX IF NOT EXISTS idx_scrapes_canonical ON scrapes(canonical_url); CREATE INDEX IF NOT EXISTS idx_scrapes_content_hash ON scrapes(content_hash); CREATE INDEX IF NOT EXISTS idx_scrapes_simhash_b0 ON scrapes(simhash_b0); CREATE INDEX IF NOT EXISTS idx_scrapes_simhash_b1 ON scrapes(simhash_b1); CREATE INDEX IF NOT EXISTS idx_scrapes_simhash_b2 ON scrapes(simhash_b2); CREATE INDEX IF NOT EXISTS idx_scrapes_simhash_b3 ON scrapes(simhash_b3); CREATE TABLE IF NOT EXISTS chunks ( id INTEGER PRIMARY KEY AUTOINCREMENT, scrape_id INTEGER NOT NULL REFERENCES scrapes(id) ON DELETE CASCADE, url TEXT NOT NULL, canonical_url TEXT, chunk_index INTEGER NOT NULL, heading_path TEXT, text TEXT NOT NULL, char_start INTEGER, char_end INTEGER, simhash TEXT, content_hash TEXT, fetched_at INTEGER, profile TEXT, embedding BLOB, embedding_model TEXT ); CREATE INDEX IF NOT EXISTS idx_chunks_scrape ON chunks(scrape_id, chunk_index); `); try { this.db.exec(` CREATE VIRTUAL TABLE IF NOT EXISTS scrapes_fts USING fts5( url, title, markdown, tokenize = 'porter unicode61 remove_diacritics 2' ); CREATE TRIGGER IF NOT EXISTS after_scrapes_insert AFTER INSERT ON scrapes BEGIN INSERT INTO scrapes_fts(rowid, url, title, markdown) VALUES (new.id, new.url, coalesce(json_extract(new.metadata, '$.title'), ''), coalesce(new.markdown, '')); END; CREATE TRIGGER IF NOT EXISTS after_scrapes_delete AFTER DELETE ON scrapes BEGIN DELETE FROM scrapes_fts WHERE rowid = old.id; END; DROP TRIGGER IF EXISTS after_scrapes_update; CREATE TRIGGER after_scrapes_update AFTER UPDATE OF url, metadata, markdown ON scrapes BEGIN DELETE FROM scrapes_fts WHERE rowid = old.id; INSERT INTO scrapes_fts(rowid, url, title, markdown) VALUES (new.id, new.url, coalesce(json_extract(new.metadata, '$.title'), ''), coalesce(new.markdown, '')); END; CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( heading, text, content = 'chunks', content_rowid = 'id', tokenize = 'porter unicode61 remove_diacritics 2' ); CREATE TRIGGER IF NOT EXISTS after_chunks_insert AFTER INSERT ON chunks BEGIN INSERT INTO chunks_fts(rowid, heading, text) VALUES (new.id, coalesce(new.heading_path, ''), new.text); END; CREATE TRIGGER IF NOT EXISTS after_chunks_delete AFTER DELETE ON chunks BEGIN INSERT INTO chunks_fts(chunks_fts, rowid, heading, text) VALUES ('delete', old.id, coalesce(old.heading_path, ''), old.text); END; `); // Title-boosted ranking, persisted in the FTS config so every `rank` // ORDER BY uses it. this.db.exec(`INSERT INTO scrapes_fts(scrapes_fts, rank) VALUES('rank', '${DOCUMENT_BM25}');`); this.db.exec(`INSERT INTO chunks_fts(chunks_fts, rank) VALUES('rank', '${CHUNK_BM25}');`); const count = this.db.query("SELECT COUNT(*) as cnt FROM scrapes_fts").get() as { cnt: number }; if (count.cnt === 0) { this.db.exec(` INSERT INTO scrapes_fts(rowid, url, title, markdown) SELECT id, url, coalesce(json_extract(metadata, '$.title'), ''), coalesce(markdown, '') FROM scrapes; `); } } catch (err) { console.error("[db-fts] Failed to initialize FTS5 index and triggers:", err); } this.migrateLegacyVectors(); } /** Convert JSON `vector` text into float32 BLOBs (one-time, batched). */ private migrateLegacyVectors(): void { const rows = this.db .query("SELECT id, vector FROM scrapes WHERE vector IS NOT NULL AND embedding IS NULL LIMIT 5000") .all() as Array<{ id: number; vector: string }>; if (rows.length === 0) return; const update = this.db.prepare( "UPDATE scrapes SET embedding = ?, embedding_model = coalesce(embedding_model, 'legacy-json'), vector = NULL WHERE id = ?", ); this.db.transaction(() => { for (const row of rows) { const parsed = parseJson(row.vector, null); if (Array.isArray(parsed) && parsed.length > 0) update.run(toBlob(parsed), row.id); } })(); } // ------------------------------------------------------------------------- // Writes // ------------------------------------------------------------------------- #bindings(doc: DocumentInput) { const provenance = doc.provenance ?? {}; const bands = provenance.simhash ? simhashBands(provenance.simhash) : null; return { $url: doc.url, $profile: doc.profile, $status: doc.status, $content: doc.content, $metadata: JSON.stringify(doc.metadata ?? {}), $markdown: doc.markdown ?? null, $json: doc.jsonData ? JSON.stringify(doc.jsonData) : null, $openapi: doc.openapiSpec ? JSON.stringify(doc.openapiSpec) : null, $embedding: toBlob(doc.vector), $embeddingModel: doc.vector ? (doc.embeddingModel ?? "unknown") : null, $canonical: provenance.canonicalUrl ?? null, $contentHash: provenance.contentHash ?? null, $simhash: provenance.simhash ?? null, $b0: bands?.[0] ?? null, $b1: bands?.[1] ?? null, $b2: bands?.[2] ?? null, $b3: bands?.[3] ?? null, $etag: provenance.etag ?? null, $lastModified: provenance.lastModified ?? null, $fetchedAt: provenance.fetchedAt ?? Date.now(), }; } #writeChunks(scrapeId: number, doc: DocumentInput): void { if (this.#vectorIndex) { // Keep the ANN index consistent with the chunks being replaced. const stale = this.db.query("SELECT id FROM chunks WHERE scrape_id = ? AND embedding IS NOT NULL").all(scrapeId) as Array<{ id: number; }>; for (const { id } of stale) this.#vectorIndex.remove(id); } this.db.prepare("DELETE FROM chunks WHERE scrape_id = ?").run(scrapeId); const provenance = doc.provenance ?? {}; (doc.chunks ?? []).forEach((chunk, index) => { const result = this.insertChunkStmt.run({ $scrapeId: scrapeId, $url: doc.url, $canonical: provenance.canonicalUrl ?? null, $index: index, $heading: chunk.headingPath?.length ? chunk.headingPath.join(" > ") : null, $text: chunk.text, $start: chunk.charStart ?? null, $end: chunk.charEnd ?? null, $simhash: provenance.simhash ?? null, $contentHash: provenance.contentHash ?? null, $fetchedAt: provenance.fetchedAt ?? Date.now(), $profile: doc.profile, $embedding: toBlob(chunk.embedding), $embeddingModel: chunk.embedding ? (doc.chunkEmbeddingModel ?? "unknown") : null, }); if (chunk.embedding && this.#vectorIndex) { this.#vectorIndex.add(Number(result.lastInsertRowid), toFloat32(chunk.embedding)); } }); } /** Append a new row (history-preserving). */ public saveScrape( url: string, profile: string, status: number, content: string, metadata: unknown, markdown?: string, jsonData?: unknown, openapiSpec?: unknown, vector?: number[] | Float32Array, ) { return this.insertStmt.run( this.#bindings({ url, profile, status, content, metadata, markdown, jsonData, openapiSpec, vector }), ); } public saveScrapesBatch(scrapes: ScrapeRecordInput[]): number { if (scrapes.length === 0) return 0; this.db.transaction((items: ScrapeRecordInput[]) => { for (const s of items) { this.saveScrape( s.url, s.profile, s.status, s.content, s.metadata, s.markdown, s.jsonData, s.openapiSpec, s.vector, ); } })(scrapes); return scrapes.length; } public upsertScrape( url: string, profile: string, status: number, content: string, metadata: unknown, markdown?: string, jsonData?: unknown, openapiSpec?: unknown, vector?: number[] | Float32Array, ) { return this.upsertDocument({ url, profile, status, content, metadata, markdown, jsonData, openapiSpec, vector }); } /** * Idempotent document write keyed on URL. When the stored row already has * the same `contentHash`, only freshness fields are touched and chunks are * left untouched (exactly-once persistence under re-crawls and retries). */ public upsertDocument(doc: DocumentInput): UpsertResult { return this.db.transaction((input: DocumentInput): UpsertResult => { const existing = this.checkUrlStmt.get(input.url) as | { id: number; content_hash: string | null } | null; const hash = input.provenance?.contentHash ?? null; if (existing && hash && existing.content_hash === hash) { this.touchStmt.run( input.provenance?.fetchedAt ?? Date.now(), input.status, input.provenance?.etag ?? null, input.provenance?.lastModified ?? null, existing.id, ); return { id: existing.id, changed: false, inserted: false }; } if (existing) { this.updateStmt.run({ ...this.#bindings(input), $id: existing.id }); if (input.chunks) this.#writeChunks(existing.id, input); return { id: existing.id, changed: true, inserted: false }; } const inserted = this.insertStmt.run(this.#bindings(input)); const id = Number(inserted.lastInsertRowid); if (input.chunks) this.#writeChunks(id, input); return { id, changed: true, inserted: true }; })(doc); } /** Batch of {@link upsertDocument} in one transaction. */ public upsertDocuments(docs: DocumentInput[]): UpsertResult[] { return this.db.transaction((items: DocumentInput[]) => items.map((d) => this.upsertDocument(d)))(docs); } public checkpoint(mode: "PASSIVE" | "FULL" | "RESTART" | "TRUNCATE" = "PASSIVE") { return this.db.exec(`PRAGMA wal_checkpoint(${mode});`); } public vacuum() { return this.db.exec("VACUUM;"); } // ------------------------------------------------------------------------- // Reads // ------------------------------------------------------------------------- public getRecentScrapes(limit = 10) { return this.db.query("SELECT * FROM scrapes ORDER BY timestamp DESC LIMIT ?").all(limit); } public getScrapeByUrl(url: string) { return this.db .query("SELECT * FROM scrapes WHERE url = ? OR canonical_url = ? ORDER BY timestamp DESC, id DESC LIMIT 1") .get(url, url) as any; } public findByContentHash(contentHash: string): { id: number; url: string } | null { return this.db .query("SELECT id, url FROM scrapes WHERE content_hash = ? ORDER BY id LIMIT 1") .get(contentHash) as { id: number; url: string } | null; } /** * Documents whose SimHash is within `maxBits` of `simhash` (≤ 3 is exact * thanks to band pigeonholing; larger values may miss candidates). */ public findNearDuplicates(simhash: string, maxBits = 3, excludeUrl?: string): NearDuplicate[] { const bands = simhashBands(simhash); if (!bands) return []; const rows = this.db .query( `SELECT id, url, simhash FROM scrapes WHERE simhash_b0 = ? OR simhash_b1 = ? OR simhash_b2 = ? OR simhash_b3 = ?`, ) .all(...bands) as Array<{ id: number; url: string; simhash: string }>; return rows .filter((row) => row.url !== excludeUrl) .map((row) => ({ ...row, distance: simhashDistance(simhash, row.simhash) })) .filter((row) => row.distance <= maxBits) .sort((a, b) => a.distance - b.distance); } /** Rows that carry an embedding, decoded as float32 views. */ public getAllScrapesWithVectors(): Array<{ id: number; url: string; metadata: string; markdown: string; embedding: Float32Array; }> { const rows = this.db .query("SELECT id, url, metadata, markdown, embedding FROM scrapes WHERE embedding IS NOT NULL") .all() as Array<{ id: number; url: string; metadata: string; markdown: string; embedding: Uint8Array }>; return rows.flatMap((row) => { const embedding = blobToFloat32(row.embedding); return embedding ? [{ ...row, embedding }] : []; }); } /** Title-boosted BM25 over documents. Falls back from AND to OR for recall. */ public searchFullText(queryStr: string, limit = 10) { const run = (mode: "AND" | "OR") => { const match = ftsQuery(queryStr, mode); if (!match) return []; return this.db .query( `SELECT s.id, s.url, s.profile, s.status, s.metadata, s.markdown, s.timestamp, s.canonical_url, s.fetched_at, fts.rank FROM scrapes_fts fts JOIN scrapes s ON s.id = fts.rowid WHERE scrapes_fts MATCH ? ORDER BY fts.rank LIMIT ?`, ) .all(match, limit) as any[]; }; try { const strict = run("AND"); if (strict.length >= limit) return strict; const seen = new Set(strict.map((row) => row.id)); return [...strict, ...run("OR").filter((row) => !seen.has(row.id))].slice(0, limit); } catch (err) { console.error("[db-fts] FTS query failed, falling back to LIKE:", err); return this.db .query( `SELECT id, url, profile, status, metadata, markdown, timestamp, 0.0 as rank FROM scrapes WHERE url LIKE ? OR markdown LIKE ? ORDER BY timestamp DESC LIMIT ?`, ) .all(`%${queryStr}%`, `%${queryStr}%`, limit) as any[]; } } /** BM25 over chunks, with provenance and offsets for citations. */ public searchChunks(queryStr: string, limit = 10): ChunkHit[] { const run = (mode: "AND" | "OR") => { const match = ftsQuery(queryStr, mode); if (!match) return []; return this.db .query( `SELECT c.id, c.url, c.canonical_url, c.heading_path, c.text, c.char_start, c.char_end, c.fetched_at, c.profile, c.content_hash, s.metadata, fts.rank FROM chunks_fts fts JOIN chunks c ON c.id = fts.rowid JOIN scrapes s ON s.id = c.scrape_id WHERE chunks_fts MATCH ? ORDER BY fts.rank LIMIT ?`, ) .all(match, limit) as any[]; }; let rows = run("AND"); if (rows.length < limit) { const seen = new Set(rows.map((row) => row.id)); rows = [...rows, ...run("OR").filter((row) => !seen.has(row.id))].slice(0, limit); } return rows.map((row) => this.#chunkHit(row, -row.rank)); } #chunkHit(row: any, score: number): ChunkHit { return { chunkId: row.id, url: row.url, canonicalUrl: row.canonical_url ?? null, title: parseJson<{ title?: string }>(row.metadata, {}).title ?? "Untitled", headingPath: row.heading_path ? String(row.heading_path).split(" > ") : [], text: row.text, charStart: row.char_start ?? null, charEnd: row.char_end ?? null, fetchedAt: row.fetched_at ?? null, profile: row.profile ?? null, contentHash: row.content_hash ?? null, score, }; } /** * Open (or rebuild) the persisted native HNSW index for chunk embeddings of * `model` next to this database (`..hnsw`) and attach it. Falls * back to the exact scan when the native bridge is unavailable. Returns the * attached index, or `null`. */ public async openVectorIndex(model: string, dim: number): Promise { if (this.#path === ":memory:") return null; const { isBridgeAvailable, NativeVectorIndex } = await import("../rust/bridge.ts"); if (!isBridgeAvailable()) return null; const slug = model.replace(/[^a-zA-Z0-9._-]+/g, "_"); const native = NativeVectorIndex.open(`${this.#path}.${slug}.hnsw`, dim); const expected = ( this.db .query("SELECT COUNT(*) AS n FROM chunks WHERE embedding IS NOT NULL AND embedding_model = ?") .get(model) as { n: number } ).n; if (native.rebuiltFromCorruptFile || native.size !== expected) { // Source of truth is SQLite: rebuild when the file is missing, stale or corrupt. const rebuilt = NativeVectorIndex.open(`${this.#path}.${slug}.hnsw.rebuild`, dim); let keys: number[] = []; let vectors: Float32Array[] = []; for (const { id, embedding } of this.iterateChunkEmbeddings(model)) { if (embedding.length !== dim) continue; keys.push(id); vectors.push(embedding); if (keys.length === 4096) { rebuilt.addBatch(keys, vectors); keys = []; vectors = []; } } rebuilt.addBatch(keys, vectors); rebuilt.save(); rebuilt.close(); native.close(); const { renameSync } = await import("node:fs"); renameSync(`${this.#path}.${slug}.hnsw.rebuild`, `${this.#path}.${slug}.hnsw`); const reopened = NativeVectorIndex.open(`${this.#path}.${slug}.hnsw`, dim); this.attachVectorIndex(reopened); return reopened; } this.attachVectorIndex(native); return native; } /** Persist the attached vector index, if any. */ public saveVectorIndex(): void { this.#vectorIndex?.save(); } /** Attach an ANN index over chunk embeddings (keys are chunk ids). */ public attachVectorIndex(index: VectorIndex | null): void { this.#vectorIndex = index; } /** Chunk embeddings in id order, for (re)building a vector index. */ public *iterateChunkEmbeddings(model?: string): Generator<{ id: number; embedding: Float32Array }> { const stmt = model ? this.db.query("SELECT id, embedding FROM chunks WHERE embedding IS NOT NULL AND embedding_model = ? ORDER BY id") : this.db.query("SELECT id, embedding FROM chunks WHERE embedding IS NOT NULL ORDER BY id"); for (const row of (model ? stmt.iterate(model) : stmt.iterate()) as Iterable<{ id: number; embedding: Uint8Array }>) { const embedding = blobToFloat32(row.embedding); if (embedding) yield { id: row.id, embedding }; } } /** * Dense retrieval over chunks: ANN index when attached, otherwise an exact * scan over BLOB embeddings (no JSON parsing). */ public searchChunksSemantic(queryVector: Float32Array | number[], limit = 10, model?: string): ChunkHit[] { const query = toFloat32(queryVector); let scored: Array<{ id: number; score: number }>; if (this.#vectorIndex && this.#vectorIndex.size > 0 && this.#vectorIndex.dim === query.length) { scored = this.#vectorIndex.search(query, limit).map((hit) => ({ id: hit.key, score: hit.score })); } else { const queryNorm = norm(query) || 1; scored = []; for (const { id, embedding } of this.iterateChunkEmbeddings(model)) { if (embedding.length !== query.length) continue; const denom = queryNorm * (norm(embedding) || 1); scored.push({ id, score: dot(query, embedding) / denom }); } scored.sort((a, b) => b.score - a.score); scored = scored.slice(0, limit); } if (scored.length === 0) return []; const byId = new Map(scored.map((s) => [s.id, s.score])); const rows = this.db .query( `SELECT c.id, c.url, c.canonical_url, c.heading_path, c.text, c.char_start, c.char_end, c.fetched_at, c.profile, c.content_hash, s.metadata FROM chunks c JOIN scrapes s ON s.id = c.scrape_id WHERE c.id IN (${scored.map(() => "?").join(",")})`, ) .all(...scored.map((s) => s.id)) as any[]; return rows .map((row) => this.#chunkHit(row, byId.get(row.id) ?? 0)) .sort((a, b) => b.score - a.score); } /** Document-level dense retrieval over `scrapes.embedding`. */ public searchSemantic( queryVector: number[] | Float32Array, limit = 10, minSimilarity = 0.1, ): SemanticHit[] { const query = toFloat32(queryVector); const queryNorm = norm(query) || 1; const results: SemanticHit[] = []; const stmt = this.db.query( "SELECT url, metadata, markdown, embedding FROM scrapes WHERE embedding IS NOT NULL", ); for (const row of stmt.iterate() as Iterable<{ url: string; metadata: string; markdown: string; embedding: Uint8Array; }>) { const embedding = blobToFloat32(row.embedding); if (!embedding || embedding.length !== query.length) continue; const similarity = dot(query, embedding) / (queryNorm * (norm(embedding) || 1)); if (similarity < minSimilarity) continue; results.push({ url: row.url, title: parseJson<{ title?: string }>(row.metadata, {}).title || "Untitled", markdown: row.markdown || "", similarity, }); } results.sort((a, b) => b.similarity - a.similarity); return results.slice(0, limit); } /** * Hybrid retrieval: BM25 (title-boosted) ⊕ dense, fused with Reciprocal * Rank Fusion (k = 60) over the top `candidates` of each side. */ public searchHybrid( queryStr: string, queryVector?: number[] | Float32Array, limit = 10, options: { candidates?: number; k?: number } = {}, ): HybridHit[] { const candidates = Math.max(limit, options.candidates ?? 200); const k = options.k ?? 60; const fused = new Map(); const add = (url: string, title: string, markdown: string, rank: number) => { const contribution = 1 / (k + rank + 1); const existing = fused.get(url); if (existing) existing.score += contribution; else fused.set(url, { url, title, markdown, score: contribution }); }; this.searchFullText(queryStr, candidates).forEach((row: any, rank: number) => { const title = parseJson<{ title?: string }>(row.metadata, {}).title || "Untitled"; add(row.url, title, row.markdown || "", rank); }); if (queryVector) { this.searchSemantic(queryVector, candidates, Number.NEGATIVE_INFINITY).forEach((hit, rank) => add(hit.url, hit.title, hit.markdown, rank), ); } return [...fused.values()].sort((a, b) => b.score - a.score).slice(0, limit); } /** * Hybrid retrieval over chunks (BM25 ⊕ dense, RRF) returning citable hits. */ public searchChunksHybrid( queryStr: string, queryVector?: number[] | Float32Array, limit = 10, options: { candidates?: number; k?: number; model?: string } = {}, ): ChunkHit[] { const candidates = Math.max(limit, options.candidates ?? 200); const k = options.k ?? 60; const fused = new Map(); const add = (hit: ChunkHit, rank: number) => { const contribution = 1 / (k + rank + 1); const existing = fused.get(hit.chunkId); if (existing) existing.score += contribution; else fused.set(hit.chunkId, { ...hit, score: contribution }); }; this.searchChunks(queryStr, candidates).forEach(add); if (queryVector) this.searchChunksSemantic(queryVector, candidates, options.model).forEach(add); return [...fused.values()].sort((a, b) => b.score - a.score).slice(0, limit); } public getChunks(scrapeId: number): ChunkHit[] { return ( this.db .query( `SELECT c.*, s.metadata FROM chunks c JOIN scrapes s ON s.id = c.scrape_id WHERE c.scrape_id = ? ORDER BY c.chunk_index`, ) .all(scrapeId) as any[] ).map((row) => this.#chunkHit(row, 0)); } /** Documents whose validators allow a conditional re-fetch. */ public getRevalidationCandidates(olderThanMs: number, limit = 100) { return this.db .query( `SELECT id, url, etag, last_modified, content_hash, fetched_at FROM scrapes WHERE fetched_at IS NULL OR fetched_at < ? ORDER BY coalesce(fetched_at, 0) ASC LIMIT ?`, ) .all(Date.now() - olderThanMs, limit) as Array<{ id: number; url: string; etag: string | null; last_modified: string | null; content_hash: string | null; fetched_at: number | null; }>; } /** Record a `304 Not Modified` (or unchanged content) revalidation. */ public markRevalidated(id: number, status = 304, validators: { etag?: string | null; lastModified?: string | null } = {}) { this.touchStmt.run(Date.now(), status, validators.etag ?? null, validators.lastModified ?? null, id); } public getScrapesCount(): number { const row = this.db.query("SELECT count(*) as cnt FROM scrapes").get() as { cnt: number } | null; return row?.cnt ?? 0; } public getChunksCount(): number { const row = this.db.query("SELECT count(*) as cnt FROM chunks").get() as { cnt: number } | null; return row?.cnt ?? 0; } public getScrapesByDomain(domain: string, limit = 50, offset = 0) { return this.db .query( "SELECT id, url, profile, status, metadata, markdown, json_data, openapi_spec, timestamp FROM scrapes WHERE url LIKE ? ORDER BY timestamp DESC LIMIT ? OFFSET ?", ) .all(`%${domain}%`, limit, offset) as any[]; } public close() { if (this.#vectorIndex) { try { this.#vectorIndex.save(); } catch (err) { console.error("[bxc-db] failed to persist the vector index:", err); } this.#vectorIndex.close(); this.#vectorIndex = null; } this.db.close(); } } /** @deprecated Kept for callers that still compare plain arrays. */ export { cosineSimilarity };