import type { EmbedSearchHit } from "./embed-db.js"; /** A single labeled vector — used to populate the index. */ export interface LabeledVector { /** Stable identifier — lets the search code recover the source row from the EmbedDb. */ label: number; /** L2-normalized vector. Caller is responsible for the normalization. */ vector: Float32Array; } /** * v2.16.0 — sidecar metadata persisted alongside the .hnsw.bin index. Used * for staleness detection on boot: if `signature` matches the current * embed-db's signature (computed by `EmbedDb.computeSignature()`), the * pre-built HNSW is loaded; otherwise it's rebuilt from scratch. * * Stored as JSON next to the binary index (`.meta.json`). Keep this * format stable — bumping `formatVersion` invalidates all on-disk * indexes for users on the new version (they'll rebuild on next boot, * which is harmless but visible). */ export interface HnswPersistedMeta { formatVersion: 1; /** Embedder dim — must match the corpus the index will be queried with. */ dim: number; /** Vector count at write time. */ size: number; /** * Embed-db signature at write time — when this differs from the current * embed-db's signature, the persisted index is stale and should be * rebuilt. We use rowcount + max-id + dim as a tractable signature * (full content-hash would require reading every vector). */ signature: string; /** Row label → source row map needed to reconstruct hits. JSON-friendly. */ rowsByLabel: Record; /** ISO timestamp of the write — informational. */ writtenAt: string; } /** Build-time HNSW parameters. Defaults tuned for 384-dim cosine on PKM data. */ export interface HnswBuildOptions { /** Embedding dimensionality (must match the corpus). */ dim: number; /** Maximum elements (caller's count of vectors); enables index pre-sizing. */ maxElements: number; /** * Number of bidirectional links per node. Higher M = better recall but * more memory + slower build. Default 16 (Malkov & Yashunin, 2018, §4.1). */ m?: number; /** * Beam width during build. Higher efConstruction = better recall, * slower build, no query-time cost. Default 200. */ efConstruction?: number; /** Seed for build-time randomization (reproducibility in tests). */ seed?: number; } /** Per-query parameters. */ export interface HnswQueryOptions { /** * Beam width during search. Higher = more accurate, slower. Default 100. * Must be ≥ k. Common range: 50-500. */ ef?: number; } /** * In-memory HNSW index over L2-normalized cosine vectors. Built once on * serve start from `EmbedDb.getAllVectors()`; queried per * `obsidian_search` / `obsidian_embeddings_search` invocation. */ export interface HnswIndex { /** Vector dimensionality. */ readonly dim: number; /** Number of points currently in the index. */ readonly size: number; /** * k-NN search. Returns labels + distances (cosine distance, smaller = * more similar). Caller maps labels back to source rows via the same * `LabeledVector.label` they used at build time. */ searchKnn(queryVec: Float32Array, k: number, opts?: HnswQueryOptions): { labels: number[]; distances: number[]; }; /** * v2.16.0 — persist the index to disk for fast reload on next serve * start. Writes the binary index to `.bin` and a JSON meta * sidecar to `.meta.json` containing the embed-db signature, * dim, size, and label→row map. Returns true on successful write. * * Caller is responsible for choosing `file` (typically alongside the * embed-db with `.hnsw` suffix). We separate binary + meta files so * a partial write (e.g. crash mid-flush) leaves the meta missing, * which the loader treats as "no usable index" → rebuild from scratch. */ saveTo(file: string, rowsByLabel: ReadonlyMap, signature: string): Promise; /** * v3.9.0-rc.2 — apply a live-update diff to the in-memory index. The * watcher calls this after `embedDb.upsertNote()` returns its * `{ oldIds, newIds }` so search reflects the change immediately * (pre-3.9.0, search was stale until the next serve restart rebuilt * the index from the freshly upserted embed-db). * * Semantics: * 1. Each id in `removeLabels` is `markDelete`'d. Missing labels * (e.g. a stale watcher tracking a label that was already evicted) * are silently skipped. * 2. Each entry in `addPoints` is `addPoint`'d with `replaceDeleted` * = true so deleted-but-allocated slots are reused before the * index grows. Throws (wrapped) if capacity is exhausted AND the * caller didn't pre-grow via {@link resize}. * * Atomicity: the SDK's underlying mutations are synchronous, but * `applyDiff` does not wrap them in a transaction. A throw mid-loop * leaves the index in a partial-update state (some labels removed, * some new points added, others not). Callers MUST treat throws as * "rebuild required" — there's no rollback path in hnswlib. * * @returns the number of labels removed + the number of points added * (for logging / instrumentation). Sum should equal * `removeLabels.length + addPoints.length` on success. */ applyDiff(removeLabels: ReadonlyArray, addPoints: ReadonlyArray<{ label: number; vector: Float32Array; }>): { removed: number; added: number; }; /** * v3.9.0-rc.2 — grow the index to at least `newMaxElements`. No-op if * already large enough. Used by the watcher before `applyDiff` when * the live-update would push us past current capacity. Native call * is synchronous (in-place re-allocation). */ resize(newMaxElements: number): void; /** * v3.9.0-rc.2 — capacity introspection. `currentCount` is the number * of live points (deleted points still count toward this); `maxElements` * is the pre-allocated cap. Caller uses these to decide whether * {@link resize} is needed before {@link applyDiff}. */ capacity(): { currentCount: number; maxElements: number; }; } /** * Build a fresh in-memory HNSW from labeled vectors. * * `vectors` must be L2-normalized — the cosine distance space treats * inputs as already-unit-length, so unnormalized inputs produce wrong * distances. The `EmbedDb` already L2-normalizes at insert time, so the * usual call path (loadAllVectors → buildHnsw) is safe by construction. * * Throws if `dim` doesn't match any vector's length, if `maxElements` * is less than the input count, or if `hnswlib-node` failed to load. */ export declare function buildHnsw(vectors: ReadonlyArray, opts: HnswBuildOptions): Promise; /** * v2.16.0 — load a previously-persisted HNSW index from disk. Returns * `null` (with a stderr warning) if: * • Either the .bin or .meta.json file is missing * • The meta's `signature` doesn't match the caller's current signature * • The meta's `formatVersion` doesn't match * • The meta's `dim` is not a positive integer (v3.8.0-rc.10 P3-27) * • The meta's `size` is not a non-negative integer (v3.8.0-rc.10 P3-27) * • The meta's `rowsByLabel` is not a plain object (v3.8.0-rc.10 P3-27) * • The native lib fails to load the .bin (corrupt / dim mismatch) * * On success returns `{ index, rowsByLabel }` so the caller can wire * both into `searchHybrid`'s `hnsw` context without rebuilding from * scratch. Typical boot-time win: ~25s rebuild → ~50ms load on a * 50K-chunk vault. */ export declare function loadHnswFromDisk(file: string, expectedSignature: string): Promise<{ index: HnswIndex; rowsByLabel: Map; } | null>; /** * Convert HNSW search results to EmbedSearchHit using a label → source-row * lookup. The label was assigned by the caller at build time (typically * `EmbedDb.getAllVectors()` returns rows with sequential integer labels); * we just reverse the mapping. Distance → cosine similarity: cosine * distance is `1 - cosine_similarity`, so we flip back here so callers * can compare HNSW + brute-force scores apples-to-apples. */ export declare function hnswResultsToHits(result: { labels: number[]; distances: number[]; }, rowByLabel: ReadonlyMap): EmbedSearchHit[]; //# sourceMappingURL=hnsw.d.ts.map