/** * Stage 8 — Embed + Index (provider call + DB writes) * * For each normalized memory: * 1. Insert into memories table via MemoryRepo.insert (hash dedup built in) * 2. Embed the normalizedText via EmbedProvider * 3. Upsert vec row via SqliteVecStore.upsert * 4. Update embedding_provider/model/dim on the memories row */ import type { EmbedProvider, LLMProvider } from '../../contracts/index.js'; import type { NormalizedMemory } from './07-memory-normalize.js'; import type { AtomLinkCandidate } from '../link-atoms.js'; import type { DB } from '../../storage/db.js'; import type { Config } from '../../config/config.js'; import { type DurabilityGateMode } from '../durability-gate.js'; export interface IndexResult { memoryId: string; created: boolean; } export interface EmbedIndexContext { db: DB; embed: EmbedProvider; sessionId: string | null; repo: string | null; project: string | null; branch: string | null; agent: string | null; sourceHash: string | null; /** * Canonical envelope's `captured_at` (epoch ms), when the ingest route * received one (v1.0 envelope only — legacy v0.0 has no such field). * Becomes each new memory's `valid_from` so bitemporal `as_of` queries key * off when the content was true, not when this distill job happened to * run. `null`/omitted falls back to MemoryRepo's insert-time wall-clock * default — the pre-existing behavior for legacy envelopes and any * pre-fix rows (no migration backfills those; see distill.ts/distill-events.ts). */ capturedAtMs?: number | null; /** * FEAT-455 / ADR-012 decision 4, widened 2026-07-12: provenance tag * carried on the transcripts row this distill run's atoms were extracted * from — `'auto_capture'` when captured by the hook-tap auto-capture * trigger, `'hook_close'` when captured by the ordinary close-capture * hook, `null`/omitted for every other producer (byte-identical default). * Passed straight through to `MemoryRepo.insertWithCreateEvent`'s * `capture_source` so every atom formed from a captured transcript is * itself scoped for the doctor "Auto-capture" canary's count query and the * disable -> purge query. Widened again FEAT-458 S3 (ADR-013): `'proxy'` * when captured by the LLM proxy relay's capture fork — scoped for its own * "LLM proxy" doctor canary and its own disable -> purge query, isolated * from the auto-capture ones above. Widened again FEAT-489 (Slice A): * `'audio_transcribe'` when captured by the on-device audio-file * transcription pipeline — its own "Audio add-on" doctor row. */ captureSource?: 'auto_capture' | 'hook_close' | 'proxy' | 'audio_transcribe' | 'meeting_captions' | null; /** FEAT-491: the flattened transcript text (flatten-turns.ts output) this * batch's atoms were extracted from — used to recover per-atom speaker * attribution via `attributeSpeaker` below. `undefined` for any caller * that doesn't have it (e.g. distill-events.ts's atom-to-memory path, * which has no source transcript at all) — every atom then gets * `speaker_label: null`, byte-identical to pre-FEAT-491 behavior. */ sourceText?: string; /** * FEAT-489/FEAT-491 (ADR-017 decision 6): whether the operator * disclosure/opt-in required for capturing a non-user speaker was * satisfied at capture time, carried on the transcripts row this distill * run's atoms were extracted from. Passed straight through to * `MemoryRepo.insertWithCreateEvent`'s `consent_disclosed` so a memory * produced from a third-party recording can self-identify as such even if * its source transcript is later pruned by retention (FEAT-493) * independently. `null`/omitted for every producer without a * third-party-speaker capture source. */ consentDisclosed?: boolean | null; /** * FEAT-441: durability quality gate mode. Undefined/omitted behaves as * 'off' — every pre-FEAT-441 caller (and the existing test suite) that * never sets this field is byte-identical (AC-2): `gateDurability` short * circuits to `null` for 'off' without even running the classifier. */ durabilityGateMode?: DurabilityGateMode; /** * Config used to redact a gated atom's text before it reaches the log * sink (AC-7 — same Stage-0 `redactIfEnabled` choke point `/remember` * and ingest use). Only consulted when a gate actually fires (mode !== * 'off' and a candidate matches); falls back to `defaultConfig()` * (redaction ON by default) if omitted so a caller that turns the gate on * without also threading its config still redacts rather than silently * skipping redaction. */ redactConfig?: Config; /** * FEAT-441 AC-4 observability out-param: when provided, `.count` is * incremented once per atom gated out during this call. Mutated in place * (rather than folded into the return value) so the `IndexResult[]` * return contract every existing caller already depends on stays * unchanged — callers read `.count` back after the call resolves. */ gatedOutCounter?: { count: number; }; /** * FEAT-533: LLM atom-triage tier mode. Undefined/omitted behaves as * 'off' — every pre-FEAT-533 caller (and the existing test suite) that * never sets this field is byte-identical: the triage batch loop below * is skipped entirely whenever this resolves to 'off'. */ atomTriageMode?: 'off' | 'dry-run' | 'enabled' | 'repair-only'; /** * Provider for the triage batch call — only consulted when * `atomTriageMode !== 'off'`. Real callers (distill/pipeline.ts) always * set this from `ProviderSet.llm.atomTriage`, which `getProviders` * itself always populates (identity default to `llm.extraction`) — see * that field's doc comment. A caller that sets a non-'off' mode without * also supplying this is a no-op (no triage call is ever made) rather * than a throw, same tolerant-default posture `durabilityGateMode`'s * omission gets. */ llmAtomTriage?: LLMProvider; /** Fixed atom-count batch size for the triage sweep — see * `Config['distill']['atomTriage'].batchSize`'s doc comment for why * this batches the whole job's flat post-reduce/post-normalize atom * stream rather than per chunk. Falls back to 20 when omitted. */ atomTriageBatchSize?: number; /** Call-count cap on the triage sweep for this job — falls back to 200 * when omitted. See `AtomTriageRunTracker`. */ atomTriageMaxPerRun?: number; /** Wall-clock cap (ms) on the triage sweep for this job — falls back to * 300000 (5 min) when omitted. See `AtomTriageRunTracker`. */ atomTriageMaxWallClockMs?: number; /** * FEAT-551: evidence-gated sweeper. Undefined/omitted behaves as `false` * — every pre-FEAT-551 caller (and the existing test suite) that never * sets this field is byte-identical (AC-2): the gate check below is * skipped entirely, so a `NormalizedMemory` tagged * `extractionSource: 'passB'` is admitted exactly like any other atom. * Real callers (distill/pipeline.ts's `runPipeline`) resolve this from * `config.distill.extractionPassB.evidenceGate`, defaulting to `true` * exactly when passB's resolved provider differs from pass A's (the * mixed-provider case FEAT-551's own measurement targeted) — see * `runPipeline`'s `evidenceGateEnabled` local for the exact precedence. * When `true`, every atom with `extractionSource === 'passB'` must carry * an `evidence` quote that mechanically verifies (whitespace-normalized) * against `sourceText`, or it is dropped pre-index (never embedded, never * indexed) — see `checkEvidenceGate` (../evidence-gate.js). Pass-A atoms * (or any atom with no `extractionSource` tag, e.g. a single-pass run) * are NEVER gated regardless of this setting. */ evidenceGateEnabled?: boolean; /** * Cooperative-yield interval (2026-07-19 event-loop-stall fix) for this * stage's Phase A and Phase C atom loops — see * `DEFAULT_EMBED_INDEX_YIELD_EVERY_N_ATOMS`'s doc comment. Omitted uses * that default; test-only tuning knob, mirrors * `ConsolidateOpts.yieldEveryNPairs` (src/consolidate/consolidate.ts). */ yieldEveryNAtoms?: number; /** * Test-only observability hook, fired once per cooperative yield in either * Phase A or Phase C — lets tests assert the yield actually fires without * timing the event loop. Mirrors `ConsolidateOpts.onYield`. Never set in * production. */ onYield?: () => void; /** * Retrieval-overhaul Phase 6 (P6b) — deterministic cross-atom link * candidates computed by `linkAtoms` (src/distill/link-atoms.ts) right * after stage 6's reduce(), threaded through pipeline.ts unchanged * (memory-normalize/ground-dates never drop or reorder atoms, only * annotate them, so the `contentHash` values these candidates reference * stay valid all the way to this stage). Resolved to real memory ids and * persisted via `MemoryLinkRepo` AFTER the main atom-insert loop below, * once every atom in this batch has a memory id (or was deduped to an * existing one) — see the resolution block after Phase C. `undefined`/ * empty (every caller that doesn't pass it, e.g. distill-events.ts's * atom-to-memory path, which has no `linkAtoms` pass) is a pure no-op — * byte-identical to pre-P6b behavior. */ atomLinks?: AtomLinkCandidate[]; } /** * Embed and index all normalized memories. * Returns one IndexResult per input atom (some may be deduped by hash). */ export declare function embedAndIndex(memories: NormalizedMemory[], ctx: EmbedIndexContext): Promise; export type ValidityDropReason = 'invalid_at_implausible' | 'invalid_at_before_valid_at'; /** * Decide whether an extracted `invalid_at` may be persisted as `valid_to`. * * Why this guard exists — the stakes are asymmetric and that asymmetry decides * every judgment call here: * * * accepting a slightly-wrong bound leaves one atom with a slightly wrong * validity window. Recoverable, low blast radius. * * accepting a GARBAGE bound (a past date, or year 9999 wrapping to a past * epoch, or an interval that ends before it starts) sets `valid_to` to a * value that makes the atom fail `validityFilterClause`'s default * `(valid_to IS NULL OR valid_to > now)` predicate — i.e. the memory is * PERMANENTLY INVISIBLE to every normal recall. The row is on disk, the * write returned success, nothing errored, no canary went red. It is * silent, irreversible data loss caused by one bad token from a 7B model. * * So: when a bound is implausible, we KEEP THE ATOM and DROP THE BOUND. Never * the atom. An unbounded atom is merely imprecise; a wrongly-bounded atom is * gone. * * Returns the ms value to persist (or `null` for "unbounded"), plus the reason * it was refused, so the caller can COUNT the refusal. A guard that discards * silently is just a quieter version of the bug it is fixing (ADR-015: measure * the RATE of the failure, not the existence of a success). */ export declare function guardValidTo(invalidAtMs: number | null, validFromMs: number | null, anchorMs: number): { validTo: number | null; dropped: ValidityDropReason | null; };