enquire-mcp API reference - v4.0.0-rc.7
    Preparing search index...

    Class EmbedDb

    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 is available via EmbedDb.search; wrap with HNSW (see src/hnsw.ts) for approximate nearest-neighbor retrieval.

    open() admits only a truly schema-empty file or a structurally recognized embedding index for the exact vault root. A recognized same-root index is upgraded in place when the vector table already matches the current v2 shape and only schema metadata is behind; rebuilt for v1 table-shape or model/dim/quantization mismatches; foreign, malformed, and future-schema databases are refused without Enquire-issued persistent PRAGMA, DDL, DML, chmod, or HNSW actions.

    const db = new EmbedDb({ file, vaultRoot, modelAlias: "multilingual", dim: 384 });
    await db.open();
    db.upsertNote(relPath, mtimeMs, chunks);
    const hits = db.search(queryVec, 10);
    await db.closeAndRelease();
    Index
    • Create a lazy embedding-index handle after validating all runtime options.

      Parameters

      • opts: EmbedDbOptions

        Database path plus exact vault/model/vector authority tuple.

      Returns EmbedDb

      If a string or quantization option is invalid, including a file without the exact .embed.db suffix.

      If dim is not a positive safe integer.

    • Acquire an additional shared semantic-family lifetime in the already pinned scopes. A prepared in-memory HNSW context owns this after its short-lived SQLite snapshot handle closes.

      Returns Promise<PersistenceFamilyLeaseHandle>

      Caller-owned shared family lifetime.

      If the EmbedDb is not open or its pinned scopes changed.

    • Audit one content kind without mutating the index.

      A declared file is complete only when its actual rows have the declared count and occupy the contiguous chunk-index range 0..n_chunks - 1. Embedding-only paths and quarantine markers are also mismatches. Both sides are filtered by kind, so independent markdown and PDF syncs cannot contaminate one another's result.

      Parameters

      Returns EmbedKindAudit

      Aggregate counts and the number of unique mismatched paths.

      const audit = db.auditKind("md");
      if (audit.mismatched_files > 0) throw new Error("embedding index is incomplete");
    • Validate numerical health of every stored vector for one content kind.

      Evidence-grade embeddings must be finite, non-zero, and approximately L2-normalized. The wider tolerance accounts for optional int8 storage quantization while still rejecting zero/NaN/Infinity and arbitrary-scale payloads that would invalidate cosine-as-dot-product search.

      Parameters

      Returns EmbedVectorAudit

      Count of invalid physical vector rows.

    • Capture the cheap physical-generation identity from one SQLite snapshot.

      Unlike a full HNSW receipt this reads only the immutable instance UUID and mutation epoch, so request-time callers can verify graph authority before and after awaited filesystem validation without hashing every vector.

      Returns EmbedDbGenerationIdentity

      Exact database instance UUID and durable mutation epoch.

      If either identity cell is malformed.

      const before = db.captureGenerationIdentity();
      // ... perform bounded read work ...
      const after = db.captureGenerationIdentity();
    • Capture the complete trusted authority needed to load a native HNSW graph. Row metadata and DB-canonical decoded vectors come from the same synchronous SQLite snapshot as the persistence receipt.

      Returns HnswLoadSnapshot

      Exact receipt plus detached row and vector maps keyed by label.

      const snapshot = db.captureHnswLoadSnapshot();
      
    • Capture one transactionally consistent, fully admitted HNSW receipt.

      Every configuration cell, quarantine marker, source receipt, row field, and raw vector BLOB is read inside one synchronous better-sqlite3 transaction. A malformed non-quarantined row refuses the complete HNSW snapshot instead of silently creating a partial-recall graph.

      Returns HnswReceiptSnapshot

      Exact database-generation receipt plus current label metadata.

    • Remove the embed db + WAL/SHM/rollback-journal sidecars, HNSW persistence sidecars, and the process-restart watcher interlock (<embed-db>.watcher-activation.guard). The guard contains no vault content, but clear-embeddings is the explicit recovery operation after a failed startup and therefore owns its removal. 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 historical format-2 .hnsw.meta.json carried text_preview (raw chunk text), so this was a right-to-erasure / data-cleanup gap, not just stale-index hygiene. Current compact pointers omit previews, but native vector generations remain sensitive and the same erasure authority still owns the whole family.

      Returns Promise<boolean>

    • Close the SQLite handle synchronously and begin releasing its shared persistence lifetime. Release failures are retained for an awaited retry through closeAndRelease; no rejection escapes unobserved.

      Returns void

    • Close SQLite and await exact shared-lifetime release. A failed release remains retryable: a later invocation reuses the same core handle rather than silently acquiring or forgetting a second marker.

      Returns Promise<void>

      After both the native handle and shared lease are released.

    • Validate multiple source receipts atomically in one synchronous SQLite read snapshot. Output indices correspond exactly to input indices.

      Parameters

      Returns boolean[]

      A current/stale mask captured from one database snapshot.

      If more than 512 receipts are supplied.

      const current = db.currentSourceReceiptMask(db.searchWithReceipts(queryVector, 10));
      
    • Parameters

      • relPath: string

      Returns number[]

      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.

    • Hash the exact kind-scoped source declarations and embedding payload.

      Rows, quarantine markers, and durable source revisions are streamed in deterministic order so strict before/after evidence detects same-shape in-place mutations without loading the vector corpus into memory.

      Parameters

      Returns string

      Lowercase SHA-256 digest of all ordered physical fields.

    • 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). Rows are source-state-bound and non-quarantined, but this legacy bootstrap shape carries no receipt; public HNSW egress must hydrate labels through getSearchRowsByIds.

      Returns {
          chunk_index: number;
          kind: EmbedChunkKind;
          label: number;
          line_end: number;
          line_start: number;
          rel_path: string;
          text_preview: string;
          vector: Float32Array;
      }[]

    • Return the exact pinned semantic-family scopes while this database is open. HNSW publishers must use these scopes instead of re-resolving a pathname.

      Returns PersistenceFamilyScopes

      Pinned namespace and primary EmbedDb family scopes.

      If this EmbedDb does not hold an open shared lifetime.

    • Return quarantined source paths in deterministic order.

      Parameters

      • Optionalkind: EmbedChunkKind

        Optional content-kind filter.

      • Optionallimit: number

        Optional positive safe SQLite row cap. Callers that need an overflow receipt should request their policy limit plus one.

      Returns string[]

      Vault-relative paths that must be retried and withheld.

      const markdownPaths = db.getQuarantinedPaths("md");
      
    • Hydrate HNSW labels from current, receipt-bound database rows. Missing, orphaned, kind-mismatched, and quarantined labels are omitted. Scores are deliberately absent because callers obtain them from the HNSW query that produced the labels.

      Parameters

      • ids: number[]

        Embedding row ids returned by HNSW.

      Returns Map<number, Omit<EmbedReceiptSearchHit, "score">>

      Current rows keyed by their embedding id.

      const currentRows = db.getSearchRowsByIds([17, 42]);
      
    • 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.

      Parameters

      • Optionalkind: EmbedChunkKind

        Optional source kind.

      • Optionallimit: number

        Optional positive safe row cap applied by SQLite before JS materialization. Callers that need an overflow receipt should request their policy limit plus one.

      Returns SourceStateRow[]

      Source-state rows in deterministic path order.

    • Confirm that a persisted hit still names the exact current source generation. This check is synchronous so callers can run it immediately after their final awaited live-vault stat, leaving no await-sized race.

      Parameters

      • relPath: string

        Vault-relative source path from the persisted hit.

      • kind: EmbedChunkKind

        Content-source kind from the persisted hit.

      • indexedMtimeMs: number

        Source mtime selected with the persisted bytes.

      • indexedRevision: number

        Source authority revision selected with the bytes.

      Returns boolean

      True only for the exact current state and ledger revision when no quarantine marker exists.

      if (!db.isCurrentSourceReceipt(hit.rel_path, hit.kind, hit.indexed_mtime_ms, hit.indexed_revision)) {
      return [];
      }
    • Open the SQLite database, verify ownership on the live handle, bootstrap only an admitted schema, then enable WAL and best-effort tighten file permissions. Refusal preserves logical schema and cell/BLOB values. SQLite itself may still take locks, recover/checkpoint an existing journal, or touch physical container/sidecar bytes while opening and closing; this API does not claim byte-identical DB/WAL/SHM or directory state. Before dependency loading and again immediately before native open, the main, WAL, SHM, and rollback- journal leaves must be wholly absent or every present leaf must be a singly linked regular file; orphan sidecars refuse. Idempotent after success.

      Parameters

      • OptionalexpectedDiscovery: EmbedDbConfigDiscovery

        Optional readonly preflight result to bind this mutating open to. No argument preserves the low-level intentional-rebuild contract; a supplied stale result is refused before bootstrap.

      Returns Promise<void>

      If better-sqlite3 (an optional dependency) fails to load, its native binding is unavailable, or a populated database cannot prove same-vault EmbedDb ownership under a supported non-future schema.

    • Persistently quarantine one source after an uncertain embedding attempt. Physical rows remain available for a later successful replacement, but every retrieval API excludes them immediately.

      Parameters

      • relPath: string

        Vault-relative source path.

      • kind: EmbedChunkKind

        Content-source kind.

      Returns void

      Nothing.

      db.quarantineSource("Private/rotated.md", "md");
      
    • Quarantine one source only while a derived HNSW graph still owns the expected physical generation.

      The comparison and the marker insert run under one BEGIN IMMEDIATE transaction. A drift result performs no DML, allowing the watcher to process-quarantine its stale graph before writing the marker DB-only.

      Parameters

      Returns EmbedConditionalMutationResult<void>

      A committed post-trigger generation, or a drift receipt proving no marker write ran.

    • Brute-force cosine top-K over current, non-quarantined database rows. Vectors are L2-normalized at insert time so cosine equals dot product. This legacy-compatible surface intentionally omits internal source receipts; persisted-content egress callers use searchWithReceipts. Acceptable up to roughly 50K chunks; larger corpora use HNSW.

      Parameters

      • queryVec: Float32Array

        L2-normalized query vector with the database dimension.

      • k: number

        Maximum number of ranked hits to return.

      • opts: { folder?: string; minScore?: number } = {}

        Optional folder prefix and minimum cosine score.

      Returns EmbedSearchHit[]

      Current, non-quarantined hits in descending cosine order.

    • Brute-force cosine top-K with the exact persisted source receipt selected alongside every preview. Callers must validate the receipt after their final awaited live-source check before exposing persisted bytes.

      Parameters

      • queryVec: Float32Array

        L2-normalized query vector with the database dimension.

      • k: number

        Maximum number of ranked hits to return.

      • opts: { folder?: string; minScore?: number } = {}

        Optional folder prefix and minimum cosine score.

      Returns EmbedReceiptSearchHit[]

      Current, non-quarantined receipt-bearing hits in cosine order.

      const hits = db.searchWithReceipts(queryVector, 10);
      const current = db.currentSourceReceiptMask(hits);
    • Total embedded chunks — used by stats / UI.

      Returns number

    • 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.

      Parameters

      • relPath: string
      • mtimeMs: number
      • chunks: readonly {
            chunkIndex: number;
            lineEnd: number;
            lineStart: number;
            textPreview: string;
            vector: Float32Array;
        }[]
      • kind: EmbedChunkKind = "md"

      Returns { newIds: number[]; oldIds: number[] }

      The legacy semver-bound { oldIds, newIds } result. Internal HNSW maintainers that also need DB-canonical decoded vectors use upsertNoteWithCanonicalVectors; keeping that additive sibling avoids changing the public method's exact return shape.

    • Replace one source generation and return the exact decoded vectors stored by the same SQLite transaction.

      Parameters

      • relPath: string
      • mtimeMs: number
      • chunks: readonly {
            chunkIndex: number;
            lineEnd: number;
            lineStart: number;
            textPreview: string;
            vector: Float32Array;
        }[]
      • kind: EmbedChunkKind = "md"

      Returns EmbedUpsertResult

      { oldIds, newIds, newVectors }, where newVectors are decoded from the committed BLOBs in newIds order. Watcher HNSW updates must use this sibling so int8 live search and restart rebuilds consume identical numeric input.

    • Replace one source only if an in-memory HNSW graph still names the exact current database generation.

      The comparison and every mutation run under one BEGIN IMMEDIATE transaction. A drift result performs no DML, allowing the watcher to quarantine its stale graph before retrying through the authoritative database-only path.

      Parameters

      • expected: EmbedDbGenerationIdentity

        UUID/epoch currently owned by the in-memory graph.

      • relPath: string

        Exact vault-relative source path.

      • mtimeMs: number

        Revalidated source modification time.

      • chunks: readonly {
            chunkIndex: number;
            lineEnd: number;
            lineStart: number;
            textPreview: string;
            vector: Float32Array;
        }[]

        Fully prepared, normalized embedding chunks.

      • kind: EmbedChunkKind = "md"

        Markdown or PDF source kind.

      Returns EmbedConditionalMutationResult<EmbedUpsertResult>

      Either the committed row diff plus its new generation, or a no-write drift receipt.