/** Content-source kind. Mirrors ChunkKind in src/fts5.ts. */ export type EmbedChunkKind = "md" | "pdf"; /** v2.17.0 — vector storage encoding. */ export type EmbedQuantization = "f32" | "int8"; /** * A single hit from {@link EmbedDb.search}. Mirrors the {@link FtsSearchHit} * shape so the RRF fusion layer can blend them by id (rel_path + chunk_index). */ export interface EmbedSearchHit { /** Vault-relative path of the source note / PDF. */ rel_path: string; /** 0-based chunk position within the source. */ chunk_index: number; /** 1-based starting line in the source. */ line_start: number; /** 1-based ending line in the source (inclusive). */ line_end: number; /** Raw chunk text — caller can render snippets. */ text_preview: string; /** Cosine similarity (since vectors are L2-normalized at insert time). */ score: number; /** v2.8.0 — content-source kind. Defaults to "md" for backward compat. */ kind: EmbedChunkKind; } /** Counter summary returned by the embed-sync routine in `server.ts`. */ export interface EmbedSyncReport { /** Files newly embedded (no prior source_state row). */ added: number; /** Files re-embedded due to mtime change. */ updated: number; /** Files dropped because the source vanished from the vault. */ deleted: number; /** Files whose mtime matched the stored row — no work needed. */ unchanged: number; /** Total chunks in the index after the sync. */ total_chunks: number; } interface SourceStateRow { rel_path: string; mtime_ms: number; } export interface EmbedDbOptions { /** Absolute path to the .embed.db file. */ file: string; /** Vault root for cross-vault contamination guard. */ vaultRoot: string; /** Model alias the user built this index with (e.g. "multilingual"). */ modelAlias: string; /** Vector dimensionality (must match the model). */ dim: number; /** * v2.17.0 — vector storage encoding. * - `"f32"` (default) — Float32 BLOB, 4 bytes per dim. * - `"int8"` — int8 BLOB + per-vector Float32 min + Float32 scale, * ~1 byte per dim + 8 bytes overhead. ~4× storage reduction at * ~1-2% recall@10 cost. * * Mode is per-database; switching modes triggers a full rebuild * via the schema-mismatch path in `bootstrapSchema`. */ quantization?: EmbedQuantization; } /** * v2.17.0 — encode a Float32 vector for storage as int8 + (vMin, scale). * Asymmetric scalar quantization: the smallest Float32 component maps * to int8 0; the largest maps to int8 255; intermediate values are * linearly interpolated. Dequantization: `f[i] ≈ q[i] * scale + vMin`. * * BLOB layout (dim × 1 + 8 bytes): * bytes [0 .. dim) int8 quantized values * bytes [dim .. dim+4) Float32 vMin (little-endian) * bytes [dim+4 .. dim+8) Float32 scale (little-endian) * * For a 384-dim vector this is 392 bytes vs 1536 for Float32 — a * 3.92× reduction at the storage layer. */ export declare function encodeInt8Vector(vec: Float32Array): Buffer; /** * v2.17.0 — decode an int8-quantized vector buffer back to Float32. * Inverse of `encodeInt8Vector`. Caller passes `dim` so we know how * many bytes are int8 vs the trailing min/scale tuple. */ export declare function decodeInt8Vector(buf: Buffer, dim: number): Float32Array; /** * Persistent embedding index backed by SQLite (one row per chunk + meta * table for cross-vault contamination guards). Vectors are stored as * Float32 BLOBs (default) or int8-quantized BLOBs (`quantization: "int8"`, * ~4× storage reduction at ~1-2% recall@10 cost). Brute-force cosine * top-K via {@link EmbedDb.search} or wrap with HNSW (see `src/hnsw.ts`) * for sub-10ms queries at million-chunk scale. * * Schema is bootstrapped on `open()` and auto-rebuilt on any meta * mismatch (vault root, model alias, dim, quantization, schema version). * * @example * ```ts * const db = new EmbedDb({ file, vaultRoot, modelAlias: "multilingual", dim: 384 }); * await db.open(); * db.upsertNote(relPath, mtimeMs, chunks); * const hits = db.search(queryVec, 10); * db.close(); * ``` */ export declare class EmbedDb { private db; private readonly file; private readonly vaultRoot; private readonly modelAlias; private readonly dim; /** v2.17.0 — vector storage encoding. */ private readonly quantization; /** Bytes per encoded vector — pre-computed once for hot-path checks. */ private readonly encodedBytes; constructor(opts: EmbedDbOptions); /** * Open the SQLite database, bootstrap the schema, and tighten file perms * to 0o600 on the db + WAL/SHM sidecars (note bodies live here — same * privacy posture as `vault.ts`'s persistent parse cache). Idempotent — * a second call after an open is a no-op. * * @throws {Error} If `better-sqlite3` (an optional dependency) fails to * load or its native binding can't be loaded. */ open(): Promise; /** * Remove the embed db + WAL/SHM sidecars AND the HNSW persistence sidecars * (`.hnsw.bin` + `.hnsw.meta.json`, where `` is the embed * file with its `.embed.db` suffix stripped — mirrors the persist path in * server.ts). Idempotent. * * v3.9.0-rc.34 (deep-audit P-2) — the HNSW sidecars were previously NOT * removed by `clear-embeddings`, so a `--use-hnsw` user's vault content * persisted on disk after "clearing" — and the `.hnsw.meta.json` carries * `text_preview` (raw chunk text), so this was a right-to-erasure / data- * cleanup gap, not just stale-index hygiene. Now the single file-deletion * authority for an embed-db also erases its HNSW companions. */ clearOnDisk(): Promise; /** Close the underlying SQLite handle. Idempotent — calling close * twice is safe. Call before process exit to flush WAL. */ close(): void; private bootstrapSchema; private readMeta; private writeMeta; private requireDb; /** * Replace all embeddings for a single note. Caller computes vectors. * v2.8.0: optional `kind` parameter ("md" | "pdf"); defaults to "md" so * existing callers (markdown indexing path) need no changes. */ /** * @returns v3.9.0-rc.2 — `{ oldIds, newIds }`. `oldIds` is the set of * `embeddings.id` values that were deleted (the file's previous * chunks, before this upsert); `newIds` is the set of fresh ids * assigned by AUTOINCREMENT, in the same order as the input `chunks` * array. Callers maintaining a parallel in-memory index (HNSW) use * these to `markDelete(oldIds)` + `addPoint(vectors, newIds)` so the * index stays in sync with the embed-db without rebuilding. Pre-3.9.0 * the method returned `void`; existing callers that ignore the * return value continue working unchanged. */ upsertNote(relPath: string, mtimeMs: number, chunks: ReadonlyArray<{ chunkIndex: number; lineStart: number; lineEnd: number; textPreview: string; vector: Float32Array; }>, kind?: EmbedChunkKind): { oldIds: number[]; newIds: number[]; }; /** Drop a note's embeddings entirely (used on file deletion). * * v3.7.11 (round-13 audit, sibling of v3.7.10 #10) — wrapped DELETE * embeddings + DELETE source_state in a single transaction. Pre-fix * a crash between the two statements left an orphaned source_state * row pointing at no chunks. Less critical than upsertNote (both * statements are idempotent DELETEs) but for consistency with * upsertNote (already transactional) + reindexFile (v3.7.10) + * reindexPdfFile (v3.7.10), this completes the atomicity class fix. */ /** * @returns v3.9.0-rc.2 — the set of `embeddings.id` values that were * deleted (empty if the file had no embed-db rows). Callers use this * to `markDelete(deletedIds)` on a parallel HNSW index. Pre-3.9.0 * the method returned `void`; existing callers that ignore the * return value continue working unchanged. */ deleteNote(relPath: string): number[]; /** * Read the source-state table — caller compares mtimes to decide what to * re-embed. v2.8.0: optional `kind` filter — when set, only rows of that * kind are returned. Lets the markdown-sync and PDF-sync paths run * independently without one's "missing files" being deleted by the other. */ getSourceStates(kind?: EmbedChunkKind): SourceStateRow[]; /** Brute-force cosine top-K. Vectors are L2-normalized at insert time so * cosine == dot product. Acceptable up to ~50K chunks; v2.1 will swap to * HNSW if real vaults hit that ceiling. */ search(queryVec: Float32Array, k: number, opts?: { folder?: string; minScore?: number; }): EmbedSearchHit[]; /** Total embedded chunks — used by stats / UI. */ totalChunks(): number; /** * v2.16.0 — compute a tractable signature of the embedding index for * HNSW staleness detection. Format: `dim=;rows=;maxId=;model=`. * * Why this composite (vs full content hash)? * • Full hash would require reading every BLOB on every serve start — * wastes the I/O savings the persisted HNSW is supposed to give us. * • Rowcount + max-id catches every common change pattern: insert * (max-id moves up), delete (rowcount drops), update (max-id moves * up because we DELETE+INSERT). Edge case: updating in-place * without changing max-id (rare in our codebase — upsertNote always * deletes+reinserts so max-id always advances). * • dim + model alias guard against a model swap that re-embeds with * a different vector space. */ computeSignature(): string; /** * v2.13.0 — return every (vector, row) pair for HNSW build. Caller * is responsible for assigning sequential integer labels (we use * `embeddings.id` since it's already a stable AUTOINCREMENT PK). * * Memory footprint: ~1.5 KB per row (384-dim Float32 + path string + * preview). For 50K chunks: ~75 MB peak during build. Caller should * release the array after building HNSW (we intentionally don't * stream — HNSW build is 30s on 50K chunks anyway, the 75 MB is * insignificant compared to the ONNX runtime + FTS5 working set). */ getAllVectors(): Array<{ label: number; vector: Float32Array; rel_path: string; chunk_index: number; line_start: number; line_end: number; text_preview: string; kind: EmbedChunkKind; }>; } /** Default location for the embed db, alongside the FTS5 db + parse cache. */ export declare function defaultEmbedDbFile(vaultHashPrefix: string): string; /** * v3.10.0-rc.20 (audit M7) — derive the HNSW persistence base for an embed-db * file. `/.embed.db` → `/.hnsw`; the index writes `.bin` * and the metadata writes `.meta.json` (see {@link import("./hnsw.js")}). * * SINGLE SOURCE OF TRUTH for the base so the WRITER (server.ts `persistFile`, * passed to `saveTo`/`loadHnswFromDisk`) and the ERASER ({@link EmbedDb.clearOnDisk}) * can NEVER drift. If they computed the base independently and one changed (the * strip regex or the `.hnsw` suffix), `clear-embeddings` would leave the HNSW * sidecars on disk — and `.hnsw.meta.json` carries raw `text_preview`, so that's * a right-to-erasure (GDPR) gap (the rc.34 P-2 class). The erasure-completeness * invariant asserts both call sites route through this helper. */ export declare function hnswPersistBase(embedDbFile: string): string; /** * v3.6.1 CRIT-1 — non-destructive peek at an existing embed-db's meta row. * * Reads `model_alias`, `dim`, `quantization`, `vault_root`, `schema_version` * from a SQLite file WITHOUT opening it via `EmbedDb` (which would trigger * `bootstrapSchema()` and DROP TABLE on any mismatch with the caller's * declared model). This lets a caller like `prepareServerDeps()` * pre-discover what model the embed-db was built with, then open it with * the matching model — avoiding the data-destruction class of bug the * external (anonymous) v3.6.0 audit caught. * * **Class-closure timeline (retroactive correction batch — see also * v3.7.2 audit response for the 4th drift instance: this TSDoc itself * previously mis-attributed the closure to v3.6.3):** * - v3.6.1 fixed 1 callsite (`server.ts` HNSW path) and claimed "CRIT-1 * closed" — overclaim; 9 callsites stayed vulnerable. * - v3.6.2 fixed `server.ts:254` (serve), `src/tools/search.ts:917` * (hot path) plus the K-1b sibling for FtsIndex; CHANGELOG claimed * "all 10 callsites" — still an overclaim; cli.ts had 5 residual. * - v3.6.3 was deferred to a marketing-only patch ("memory for AI * agents" positioning); K-1 work was pushed to v3.6.4. * - v3.6.4 fixed the cli.ts residual: `cli.ts:398` (build-embeddings), * `cli.ts:554` (setup step 3), `cli.ts:311` (index), `cli.ts:638` * (eval). `clear-*` paths marked `// SAFE BY DESIGN`. Added * `tests/k1-class-invariant.test.ts` (grep gate). * - v3.7.0 added `tests/k1-ast-invariant.test.ts` (TypeScript compiler * API def-use trace) catching the "peek called but result discarded" * bypass that grep would miss. Plus `peekEmbedDbMetaCached` for * ~20× speedup on the search hot path. * * Enforced by `tests/k1-class-invariant.test.ts` (grep, 40-line window) * and `tests/k1-ast-invariant.test.ts` (AST def-use trace). * * Returns null if the file doesn't exist OR doesn't have a `meta` table * yet (fresh db). v3.11.0-rc.9 (audit re-verify) — TSDoc corrected: this NEVER * throws (rc.34 wrapped `new Database()` + the meta queries in a catch that maps * ANY failure — corrupt / unreadable / not-a-DB / directory / missing dep — to * null), since it runs unguarded on the search hot path + in CLI subcommands. * * The opened SQLite handle is read-only and closed before return — no * lock contention with a subsequent `EmbedDb.open()`. * * @param file - Absolute path to a `.embed.db` file. * @returns Meta dict if the file is a populated embed-db, null otherwise. * @example * ```ts * const meta = await peekEmbedDbMeta(embedFile); * if (meta?.model_alias) { * const model = resolveModel(meta.model_alias); // honor what was built * } * ``` */ export declare function peekEmbedDbMeta(file: string): Promise<{ schema_version?: string; vault_root?: string; model_alias?: string; dim?: string; quantization?: string; } | null>; type PeekEmbedDbMetaResult = Awaited>; /** * v3.9.0-rc.28 (external-audit M-6) — cap on `peekCache`. A long-running `serve` * over a vault with many distinct `.embed.db` paths would otherwise grow the * cache without bound (one entry per file path forever). 512 covers any * realistic single-vault session with comfortable headroom. */ export declare const MAX_PEEK_CACHE_ENTRIES = 512; /** * Insert `key→value` into an insertion-ordered `Map` used as an LRU cache, then * evict the oldest entries until `size <= max`. Pure + exported so the eviction * is unit-testable directly (the `peekEmbedDbMetaCached` path needs real files). * Mirrors the `boundedSetAdd` helper (bases.ts, rc.15). On a re-set of an * existing key the caller should `delete` first so recency is refreshed. * @internal exported for unit tests. */ export declare function lruMapSet(map: Map, key: K, value: V, max: number): void; export declare function peekEmbedDbMetaCached(file: string): Promise; /** * v3.7.0 L-1 — test-only. Clear the module-level peek cache. Used in * unit tests to isolate per-test state; in production the cache lives * as long as the process. */ export declare function clearPeekCache(): void; export {}; //# sourceMappingURL=embed-db.d.ts.map