import type { EmbedDb } from "./embed-db.js"; import type { loadEmbedder } from "./embeddings.js"; import { type FtsIndex } from "./fts5.js"; import type { HnswIndex } from "./hnsw.js"; import type { Vault } from "./vault.js"; /** * v3.9.0-rc.2 — shape of the row-metadata entries the HNSW index keeps * alongside each label. Mirrors `HnswPersistedMeta["rowsByLabel"][k]` * but defined here so the watcher's TypeScript surface stays * self-contained (no circular imports between watcher.ts and hnsw.ts's * persistence types). */ export interface HnswRowMeta { rel_path: string; chunk_index: number; line_start: number; line_end: number; text_preview: string; kind: "md" | "pdf"; } export interface WatcherOptions { /** Vault to watch — must already be ensureExists()'d. */ vault: Vault; /** Optional FTS5 index to keep in sync on each event. */ ftsIndex?: FtsIndex | null; /** Suppress the "watcher: ..." stderr lines (used by tests). */ silent?: boolean; /** * v3.7.16 P1-5 — when true, the watcher also handles `.pdf` lifecycle * events (add / change / unlink), keeping the FTS5 PDF chunks in sync. * Mirrors the `--include-pdfs` serve flag. Pre-3.7.16 the watcher * ignored everything but `.md`, so PDFs added/deleted/moved during a * serve session left stale rows in FTS5 until restart. * * NOTE: PDF re-indexing on `change` requires re-extracting text from * the new bytes via `extractPdfText` (~50-200ms per page). For large * PDFs this can spike CPU — same cost as the initial-index pass but * triggered by a single file. Off by default; opt in alongside * `--include-pdfs` for full PDF coverage at runtime. */ includePdfs?: boolean; /** * v3.8.0-rc.2 R-7 — optional embed-db handle. When provided alongside * `embedder`, the watcher re-embeds + upserts on `.md` add/change events * and `deleteNote()`s on unlink. Pre-3.8.0 the embed-db drifted on every * vault edit until a manual `enquire-mcp build-embeddings` rebuild — * search-quality slowly degraded across the session for users on * `--use-hnsw` or `--persistent-index` with embeddings. * * Cost per `.md` change: 1 read + chunkContent + embedder.embed (~50-200ms * per chunk on M1 CPU, batched 8x) + db.upsertNote. For a typical * 5-paragraph note (~5 chunks), watcher overhead is ~250-500ms — usually * invisible against Obsidian's autosave-debounce window. For very long * notes the per-edit cost can spike to seconds. */ embedDb?: EmbedDb | null; /** * v3.8.0-rc.2 R-7 — embedder handle. Same instance used at bulk-sync * time so model/dim/late-chunking config stays consistent. Required * if `embedDb` is provided. */ embedder?: Awaited> | null; /** * v3.8.0-rc.2 R-7 — propagate `--late-chunk-context ` to per-file * re-embeds. Without this, runtime updates would use 0-context while * the bulk-built index used n-context — embeddings would diverge in * vector space and search recall would drift over the session. */ lateChunkContext?: number; /** * v3.9.0-rc.1 — when true, the watcher runs Tesseract OCR on * image-only / scanned PDFs that pdfjs can't extract text from, then * pipes the OCR-derived text through the standard embed pipeline so * the embed-db keeps OCR'd PDFs in sync with edits during a long * serve session. Off by default (OCR is slow: ~1-2s per page on M1 * CPU; a 100-page paper takes minutes and blocks the event loop). * * Requires `tesseract.js` + `@napi-rs/canvas` optional dependencies * + the requested language trained-data files pre-installed via * `enquire-mcp install-ocr-lang ` (see v3.7.16 P1-1 offline * enforcement). If those aren't available, OCR fails-soft — the * watcher still updates FTS5 + clears any stale embed-db rows. * * Recommended pairing: `--ocr-pdfs` + `--watch` + `--include-pdfs` * for users with scanned-document vaults that change during sessions. */ ocrPdfs?: boolean; /** * v3.9.0-rc.1 — language pack(s) passed to `extractPdfWithOcr`. * Default `'eng'`. Multi-lang via `'+'`, e.g. `'eng+rus'`. See * `src/ocr.ts` for the full language model. */ ocrLangs?: string; /** * v3.9.0-rc.1 — page cap for OCR runs. Mirrors `DEFAULT_OCR_MAX_PAGES` * (200) — image-only PDFs that exceed this won't be embed-sync'd * (the watcher logs the skip + still updates FTS5). Operators can * lift the cap when they trust their PDF set. */ ocrMaxPages?: number; } /** Row shape shared by `embedSingleNote` / `embedSinglePdf` results. */ interface EmbedRowLike { vector: Float32Array; chunkIndex: number; lineStart: number; lineEnd: number; textPreview: string; } /** * v3.9.0-rc.11 (audit) — zip embed-db rows with their freshly-assigned row ids * for an HNSW add-diff. `EmbedDb.upsertNote` returns exactly one id per row in * the same order, so a length mismatch is a bug. The pre-rc.11 code used * `newIds[i] ?? -1`, which silently inserted a vector under SENTINEL label * `-1` on any mismatch — corrupting the in-memory index, the shared * `rowsByLabel` map, AND the persisted `.hnsw.bin` sidecar (a later * `markDelete(-1)` or a real row colliding on `-1` then scrambles results). * This throws (fail-closed) instead: the watcher's per-event try/catch logs it * and skips the HNSW update for that file, and the signature guard rebuilds a * correct index on the next serve. A corrupt sentinel label is never inserted. * * @param rows - The embed rows (vector + chunk metadata), in insertion order. * @param newIds - The row ids `upsertNote` assigned, parallel to `rows`. * @returns Add-points for `syncHnswForFile`, each id guaranteed defined. * @throws {Error} If `newIds.length !== rows.length`. */ export declare function zipHnswAddPoints(rows: ReadonlyArray, newIds: ReadonlyArray): Array; export declare class VaultWatcher { private watcher; private readonly vault; private readonly ftsIndex; private readonly silent; private readonly includePdfs; private embedDb; private embedder; private lateChunkContext; private ocrPdfs; private ocrLangs; private ocrMaxPages; private hnsw; private hnswRowsByLabel; private hnswPersistFile; private hnswDirty; private closed; private readonly fileQueues; constructor(opts: WatcherOptions); /** * v3.9.0-rc.1 — enable / configure OCR-on-watch after construction. * Called by server.ts after attachEmbed() runs (since OCR fallback * only makes sense once embed-db is wired). Fails loud if includePdfs * is off — without it, PDF events are filtered before the OCR * codepath runs. * * @param enabled - When true, image-only PDFs that pdfjs can't read * trigger a Tesseract OCR pass; the OCR-derived text feeds the * normal embed pipeline via embedSinglePdf's preExtractedPages path. * @param langs - Tesseract language pack (default "eng"). Multi-lang * via `+`, e.g. "eng+rus". * @param maxPages - Page cap for OCR runs. Default 200 (DEFAULT_OCR_MAX_PAGES). */ setOcrPdfs(enabled: boolean, langs?: string, maxPages?: number): void; /** * v3.8.0-rc.2 R-7 — attach an embed-db handle + embedder after the * watcher has started. Used by `prepareServerDeps` when HNSW context * init completes after the watcher's initial `start()` call (HNSW * build can take 25s+; watcher needs to be running before that to * capture file edits during the boot window). * * Calling this is idempotent — if you pass the same handle twice, * the watcher uses the most recent one. Pass `null` for both to * detach (the FTS5-only sync continues). */ attachEmbed(embedDb: EmbedDb | null, embedder: Awaited> | null, lateChunkContext?: number): void; /** * v3.9.0-rc.2 — wire an in-memory HNSW index for live updates. After * this call, every md/pdf event that mutates embed-db ALSO updates * the HNSW graph via `hnsw.applyDiff(oldIds, newPoints)` so search * results reflect the change immediately. Pre-3.9.0, the HNSW index * was rebuilt from embed-db only at serve startup; vault edits during * the session left the HNSW stale until restart, and `--use-hnsw` * users saw new content omitted from semantic-search results. * * Must be called AFTER `attachEmbed` (the HNSW + embed-db handles * share a lifecycle — server.ts opens both during HNSW init). * * @param hnsw - the in-memory HNSW index built by server.ts. * @param rowsByLabel - the mutable label→row map shared with * `searchHybrid` (the live update writes into it so subsequent * searches see the new chunks). * @param persistFile - v3.9.0-rc.6: optional sidecar base path * (`.hnsw`). When provided AND HNSW live * updates occurred, the watcher re-persists the index at close time * so the next serve loads the up-to-date sidecar instead of * rebuilding. Omit (or pass when `--no-hnsw-persist`) to skip * persistence — correctness is unaffected (signature guard). */ attachHnsw(hnsw: HnswIndex, rowsByLabel: Map, persistFile?: string): void; /** * v3.9.0-rc.6 — flush the live-updated HNSW index to its disk sidecar. * No-op unless ALL of: the index is dirty (had ≥1 applyDiff since the * last flush), an index + rowsByLabel + persistFile + embedDb are all * wired. Recomputes the embed-db signature so the persisted * `.meta.json` matches what `loadHnswFromDisk` will expect on the next * serve (any external embed-db change since then → signature mismatch * → safe rebuild). Fail-soft: a save error is logged + swallowed (the * signature guard means a stale/missing sidecar just triggers rebuild). * * @returns true if a flush was performed, false if it was a no-op. */ flushHnswToDisk(): Promise; /** * v3.9.0-rc.2 — internal helper. Apply an embed-db {oldIds, newIds} * diff to the wired HNSW index + rowsByLabel map. Called by both the * md and pdf event handlers after upsertNote / deleteNote returns. * Fail-soft: on any error, logs to stderr and returns — the embed-db * is already updated, so the next serve restart will rebuild HNSW * from the correct state. (Same posture as the watcher's existing * embed-db fail-soft.) * * CONCURRENCY CONTRACT (v3.11.0-rc.9, external audit T-MED-1 re-verify): this * method and the `HnswIndex.applyDiff` it calls are FULLY SYNCHRONOUS — there is * NO `await` between `markDelete` and `addPoint`, nor around the shared * `hnswRowsByLabel` delete/set. On Node's single-threaded event loop that makes * the entire shared-state mutation an atomic critical section: two DIFFERENT-file * `handle()` chains can only context-switch at their `await`ed embed steps (which * don't touch the shared index), so they CANNOT interleave a partial apply. The * synchronicity IS the cross-file serialization — an explicit mutation queue would * be redundant. **A future edit MUST NOT introduce an `await` into this method or * applyDiff** (it would open a real cross-file interleave window); the per-file * `fileQueues` (rc.11 H1) serialize only SAME-file events, whose chains span the * diff-compute awaits. (Enforced by `tests/hnsw-sync-critical-section.test.ts`.) */ private syncHnswForFile; /** Start watching. Resolves once the watcher has reported `ready`. */ start(): Promise; private handle; close(): Promise; } export {}; //# sourceMappingURL=watcher.d.ts.map