/** * Consolidation — formation pipeline stage 9 (ADR-004, Wave 4b). * * Periodic offline pass over accumulated atoms, per (repo, type) group: * * - similarity >= mergeThreshold → auto merge-as-supersede. Non-destructive * by construction (architecture-review W4): the loser is superseded by the * winner via the event log, and the winner's derived_from gains the * loser's id — bitemporal history keeps the original readable forever. * - proposeThreshold <= similarity < mergeThreshold → propose-only row in * consolidation_proposals; the user confirms via REST. Nothing changes * until they do (strategy Pass 6 A4) — UNLESS `autoAcceptThreshold` * (FEAT-442, `consolidation.autoAcceptThreshold` config, default null = * OFF) is set and similarity clears that bar too, in which case the * proposal is created then immediately accepted via the same code path a * human accept uses, with an `auto_accepted` provenance marker on the * resulting supersede event. Reversible via * `MemoryEventRepo.unsupersede()` / `POST /memory/:id/unsupersede` — see * that method's doc comment for exact semantics (un-hides the loser; the * winner is untouched). * * v1 is deterministic: similarity is cosine over the stored embeddings, no * LLM call for merge/propose decisions. The second-order abstraction pass * (ADR-004 stage 9b) is still v1.x. Contradiction detection (stage 9c) is * FEAT-456 SLICE-1: an opt-in (default off) judge call inserted ahead of * the propose-tier guard below — see the "FEAT-456" comments in this file * and `src/consolidate/contradiction-judge.ts`. Propose-only like the rest * of this module: a confident 'contradicts' verdict writes a * `kind='contradiction'` proposal row, never an auto-action. * * Winner selection: higher usefulness score wins (ADR-010), then higher * importance, then the newer atom. (Contradiction proposals use a * different rule — newer atom always wins — see `runConsolidation`'s * FEAT-456 branch.) */ import type { DB } from '../storage/db.js'; import type { Config } from '../config/config.js'; import type { LLMProvider } from '../contracts/llm.js'; import type { VectorStore } from '../contracts/index.js'; import { type SupersedeProvenance, type CorrectionSource } from '../storage/memory-events.js'; import { type JudgeVerdict } from './contradiction-judge.js'; import { type DupVerdictLabel } from './dup-judge.js'; import { COMMAND_GUARD_REASON } from './command-guard.js'; export interface ConsolidateOpts { /** Cosine similarity at/above which a pair auto-merges. */ mergeThreshold?: number; /** Cosine similarity at/above which a pair becomes a proposal. */ proposeThreshold?: number; /** Groups larger than this are skipped (O(n²) guard) and reported. */ maxGroupSize?: number; /** * Auto-merge pairs whose normalized text is equal or a strict subset of * the other's, instead of queueing a manual proposal ("Port 7777 is the * default" vs "port 7777 is the default."). The containing (superset) * text always wins so no active information is lost — the shorter * variant survives in bitemporal history like any supersede. Also * auto-accepts EXISTING pending proposals whose loser text is contained * in the winner's. Default true. */ autoMergeContained?: boolean; /** * FEAT-442 autonomous consolidation: cosine similarity at/above which a * propose-tier pair (proposeThreshold <= similarity < mergeThreshold) is * accepted immediately — via the exact same path a human accept uses * (ProposalRepo.accept, i.e. proposal row created THEN resolved, so the * audit trail is identical to a manual accept plus a provenance marker) * — instead of sitting in the manual queue. Reversible via * `MemoryEventRepo.unsupersede()`. * * Must satisfy `proposeThreshold <= autoAcceptThreshold <= 1`; an * out-of-range value disables auto-accept for THIS run only (logged via * `log`, never fatal — matches this config layer's "never block a run on * a bad value" pattern, e.g. `applyFusionGovernance`). * * Default `null`/`undefined` = OFF. With no value set, behavior is * byte-identical to pre-FEAT-442 propose/accept: every propose-tier pair * becomes (and stays) a pending `consolidation_proposals` row until a * human resolves it. */ autoAcceptThreshold?: number | null; /** * FEAT-456 SLICE-1: contradiction-detection config for this run. Mirrors * `Config['consolidation']['contradictionDetection']` exactly (the job * handler and REST route forward the running config's value verbatim). * Omitted, or `mode: 'off'` (the default), is BYTE-IDENTICAL to * pre-FEAT-456 output — the judge is never called. */ contradictionDetection?: Config['consolidation']['contradictionDetection']; /** * LLMProvider for the contradiction judge — reuses * `ProviderSet.llm.extraction` (design §1.3, no new provider role). * Required only when `contradictionDetection.mode !== 'off'`; a missing * provider with mode on disables judging for THIS run only (logged, * non-fatal — matches this file's "never block a run on a bad/missing * capability" governance pattern, see `resolveAutoAcceptThreshold`). */ judgeProvider?: LLMProvider; /** * FEAT-549: batched dup-judge sweep config for this run. Mirrors * `Config['consolidation']['dupJudge']` exactly (the job handler forwards * the running config's value verbatim, same as `contradictionDetection`). * Omitted, or `mode: 'off'` (the default), is BYTE-IDENTICAL to * pre-FEAT-549 output — the sweep is never run and pending `kind='merge'` * proposals are left exactly as the pairwise scan created them. */ dupJudge?: Config['consolidation']['dupJudge']; /** * LLMProvider for the dup-judge sweep — reuses `ProviderSet.llm.extraction` * by default (no new provider role), same identity-default shape * `judgeProvider` uses. Required only when `dupJudge.mode !== 'off'`; a * missing provider with mode on disables the sweep for THIS run only * (logged, non-fatal — matches `resolveContradictionDetection`'s posture). */ dupJudgeProvider?: LLMProvider; /** Injectable logger seam for tests; defaults to `console.warn`. */ log?: (message: string) => void; /** * ADR-019 Tier 1 (issue #347): the pairwise scan below (`for`/`for` over * each (repo, type) group) yields to the event loop every N pairs via * `await new Promise(r => setImmediate(r))` — a real cooperative yield, * not a timer-family no-op. Without this, a large group (up to * `maxGroupSize`, default 500 → C(500,2) = 124,750 pairs) runs as one * uninterrupted synchronous JS stack across every group, starving the * HTTP/MCP event loop for the whole scan and hanging `/recall` and * `/memory/:id/used` — the confirmed mechanism behind issue #347 (see * ADR-019). Default 200 pairs; tune down if a single group's per-pair * cost (embedding compare + SQLite writes) is unusually heavy, up if * `setImmediate` overhead becomes measurable at very small groups. */ yieldEveryNPairs?: number; /** * Test-only observability hook: called once per cooperative yield (see * `yieldEveryNPairs`). Lets tests assert the yield actually fires without * timing the event loop. Never set in production. */ onYield?: () => void; /** * P2.1 stabilization: candidate-pair selection strategy — mirrors * `Config['consolidation']['candidateSelection']` exactly (see that * field's doc comment for the full mechanism/rationale). Default * `'full'` is BYTE-IDENTICAL to pre-P2.1 behavior. An invalid value * falls back to `'full'` for THIS run only (logged, never fatal — same * pattern as `resolveAutoAcceptThreshold`). */ candidateSelection?: 'full' | 'knn'; /** Neighbors queried per atom in `'knn'` mode. Default 30. Ignored in * `'full'` mode. An invalid value falls back to the default for THIS * run only (logged, never fatal). */ knnK?: number; /** * Ceiling on total candidate pairs processed THIS run, with a persisted * resumable cursor — mirrors * `Config['consolidation']['maxCandidatePairsPerRun']` exactly (see that * field's doc comment). Default `null` = off (unbounded, byte-identical * to pre-P2.1 behavior). An invalid value falls back to `null` for THIS * run only (logged, never fatal). */ maxCandidatePairsPerRun?: number | null; /** * Injectable `VectorStore` for the `'knn'` path — defaults to a fresh * `SqliteVecStore(db)` when omitted. Callers with an already-wired * instance (e.g. `ExtendedHandlerCtx.vecStore`) should pass it through * rather than let this call allocate a second one against the same * connection. Ignored in `'full'` mode. `SqliteVecStore.search()` * doesn't validate its own constructor `dim` against the query vector * (only `upsert()` does), so no embedding dimension needs threading * here. */ vectorStore?: VectorStore; /** * issue #387: wall-clock ceiling on the SETUP phase (load atoms + build * per-group embedding maps) — the part of a run that used to execute as * one uninterrupted synchronous stretch BEFORE the pairwise scan's own * cooperative yields (`yieldEveryNPairs`, ADR-019 Tier 1) ever got a * chance to fire. On a large corpus this alone froze the event loop long * enough that `/health` looked dead, and — combined with the * boot-recovery bug this issue also fixed (`JobRepo.recoverOrphans`) — * reproduced on every restart. When the budget is exceeded mid-load, the * loader stops fetching MORE atoms and the run proceeds with whatever was * already loaded (`summary.setupBudgetExceeded = true`, logged loudly) — * degraded coverage this pass, not a hang. Default 60s. */ setupBudgetMs?: number; /** * issue #387: how many atoms the SETUP phase (atoms load + per-group * embedding-map build) processes between cooperative yields — same * `setImmediate`-based real yield `yieldEveryNPairs` uses for the scan * itself, applied to the phase that used to have none at all. Default 500. */ setupYieldEveryNAtoms?: number; /** * FEAT-482 (worker-starvation wave, item 2/3 — the one item the fold * didn't close, see `queue-liveness-starvation.test.ts`'s doc comment): * checked at the SAME cadence as the existing cooperative yield points * (setup atoms-load pages, setup per-group embedding-map build, pair * scan) — never on its own timer, so it adds no overhead beyond what * those checkpoints already pay. When it returns true, the run stops at * the current safe checkpoint (never mid-transaction — same invariant * `yieldEveryNPairs`'s doc comment already relies on) instead of running * to completion, exactly like a `setupBudgetMs` timeout: partial * progress is kept (already-committed merges/proposals are real), the * run is logged loudly (`summary.preemptedForHigherPriority = true`), * and the remainder is picked up on the next scheduled pass (consolidate * re-enqueues itself every 6h — see serve.ts) rather than starving a * newly-arrived higher-priority job. * * This closes the residual gap priority tiers alone couldn't: * `JobRepo.claimPending()`'s tier ordering only helps a job that is * still PENDING at claim time — once a `consolidate` job is already * `running`, nothing today lets a burst of P1 work interrupt it. The * production wiring (`consolidateHandler`) passes * `() => jobRepo.hasPendingAbovePriority(JOB_PRIORITY.consolidate)`; * omitted (every caller without queue visibility — one-shot CLI runs, * most existing tests) is byte-identical to pre-FEAT-482 behavior — * never preempts. */ preemptIfHigherPriorityPending?: () => boolean; } export interface ConsolidateSummary { groupsScanned: number; groupsSkipped: Array<{ repo: string | null; type: string; size: number; }>; merged: Array<{ winner: string; loser: string; similarity: number; reason?: 'similarity' | 'contained'; }>; proposed: Array<{ winner: string; loser: string; similarity: number; }>; /** Pending proposal ids auto-accepted by the containment sweep. */ autoAcceptedProposals: string[]; /** Pending proposal ids auto-rejected as stale (an atom no longer valid). */ staleRejectedProposals: string[]; /** * FEAT-442: propose-tier pairs accepted immediately this run because * their similarity met `autoAcceptThreshold` — distinct from `merged` * (mergeThreshold/containment auto-merges, which never create a proposal * row at all) and from `proposed` (still pending). Each entry's * `proposalId` is the now-`accepted` `consolidation_proposals` row — * findable via `GET /consolidation/proposals?status=accepted` — and * reversible via `POST /memory/:id/unsupersede` on `loser`. */ autoAccepted: Array<{ winner: string; loser: string; similarity: number; proposalId: string; }>; /** * FEAT-456 `mode: 'dry-run'`: judge-eligible pairs the judge labeled * 'contradicts' at >= `minConfidence`, previewed but NOT written — the * safe-rollout mode. Always `[]` when `mode !== 'dry-run'`. */ contradictionsPreviewed: Array<{ winner: string; loser: string; similarity: number; verdict: JudgeVerdict; }>; /** * FEAT-456 `mode: 'enabled'`: `kind='contradiction'` proposals actually * inserted this run. `winner` = the newer atom (`created_at` max), * `loser` = the older atom — directional, opposite of the merge tier's * usefulness-based pick (§2.2: the new atom is the presumptive * correction). Always `[]` when `mode !== 'enabled'`. */ contradictionsProposed: Array<{ winner: string; loser: string; similarity: number; proposalId: string; }>; /** * True when `maxPerRun` judge calls were exhausted before the scan * finished — lets a report distinguish "no contradictions found" from * "ran out of budget before finishing" (§1.5). Remaining judge-eligible * pairs fall through to the existing merge-tier classification unchanged. */ contradictionCapReached: boolean; /** * issue #387: true when `setupBudgetMs` elapsed before the SETUP phase * (atoms load + per-group embedding-map build) finished — the run * proceeded with only what was loaded/built by then. See * `ConsolidateOpts.setupBudgetMs`'s doc comment. */ setupBudgetExceeded: boolean; /** * FEAT-482 (worker-starvation wave, item 2/3): true when * `preemptIfHigherPriorityPending` returned true at some checkpoint * before the scan finished — the run stopped early so the worker lane * could claim the now-pending higher-priority job. See * `ConsolidateOpts.preemptIfHigherPriorityPending`'s doc comment. * Independent of `setupBudgetExceeded` — a run can hit either, both (in * sequence), or neither. Always `false` when the option was omitted. */ preemptedForHigherPriority: boolean; /** * FEAT-482 review fix (PR #463): true when this run persisted a resume * cursor because it stopped early (ceiling hit, setup budget exceeded, * or preemption) — regardless of whether `maxCandidatePairsPerRun` was * configured. Lets a caller/test distinguish "stopped early, but the * next pass resumes further into the corpus" from "stopped early at the * identical spot every time" (previously unobservable — see PR #463 * review finding 1). `false` on a run that either completed in full or * never stopped early at all. */ resumeCursorUpdated: boolean; /** * FEAT-482: true when `contradictionDetection.maxWallClockMs` elapsed * before the scan finished — a SEPARATE guard from `contradictionCapReached` * because a slow/rate-limited judge provider can blow the wall-clock * budget long before `maxPerRun` calls are made (maxPerRun bounds call * COUNT, not duration). Same fall-through as the count cap: remaining * judge-eligible pairs fall through to the existing merge-tier * classification unchanged. */ contradictionWallClockCapReached: boolean; /** * FEAT-482: total judge calls actually dispatched this run — 0 whenever * contradiction detection was off/disabled for the run. Since dollars * cannot bound this judge (see contradiction-judge.ts's doc comment — * every shipped provider reports `usage.usd: 0`), call count and wall- * clock time are the only real cost signals; this field plus * `judgeSweepElapsedMs` are what `recordConsolidationJudgeRun` * (src/storage/consolidation-judge-log.ts) persists for `doctor` to * surface, and what tells an operator who later points extraction at a * genuinely metered provider what actually happened. */ judgeCallsExecuted: number; /** * FEAT-482: wall-clock milliseconds spent in the judge sweep this run * (0 when contradiction detection was off/disabled). Measured from the * same `judgeSweepStartedAt` the `maxWallClockMs` cap checks against. */ judgeSweepElapsedMs: number; /** * FEAT-499 stage 1: of `judgeCallsExecuted` REAL judge dispatches this * run, how many had a pair cosine similarity in * [NEAR_MERGE_THRESHOLD_MIN, mergeThreshold) — see that constant's doc * comment. Always 0 when contradiction detection was off/disabled. Purely * observational (no behavior change); this is the evidence a future * stage-2 short-circuit would be gated on. */ judgeCallsNearThreshold: number; /** * FEAT-549 `dupJudge.mode: 'dry-run'`: verdicts produced by the batched * dup-judge sweep over pending `kind='merge'` proposals, previewed but * NOT resolved — always `[]` when `dupJudge.mode !== 'dry-run'`. */ dupJudgeVerdictsPreviewed: Array<{ proposalId: string; similarity: number; verdict: DupVerdictLabel; confidence: number; }>; /** * FEAT-549 `dupJudge.mode: 'enabled'`: pending `kind='merge'` proposals * actually auto-resolved this sweep, either direction — `action: 'merged'` * for a confident `same-fact-merge` (via `ProposalRepo.accept`), * `action: 'kept-separate'` for a confident `distinct-keep-separate` (via * `ProposalRepo.reject`). Always `[]` when `dupJudge.mode !== 'enabled'`. */ dupJudgeResolved: Array<{ proposalId: string; verdict: DupVerdictLabel; confidence: number; action: 'merged' | 'kept-separate'; }>; /** FEAT-549: total dup-judge LLM calls (batches, not proposals) actually * dispatched this sweep — 0 whenever `dupJudge` was off/disabled. */ dupJudgeCallsExecuted: number; /** FEAT-549: true when `dupJudge.maxPerRun` calls were exhausted before * every pending eligible proposal was judged this sweep. */ dupJudgeCapReached: boolean; /** FEAT-549: true when `dupJudge.maxWallClockMs` elapsed before the sweep * finished — a SEPARATE guard from `dupJudgeCapReached`, same rationale * as `contradictionWallClockCapReached` (FEAT-482 lesson). */ dupJudgeWallClockCapReached: boolean; /** * FEAT-552 sub-scope C (AC-C1): pairs that cleared `mergeThreshold` but * were BLOCKED from auto-merging by the command-token guard (either atom * `type: 'command'` with differing tokenized command surfaces) — * downgraded to a pending `kind='merge'` proposal instead (see * `insertGuardedMergeProposal`). Always `[]` when no command-type atom is * involved in any candidate pair this run (AC-C1: non-command pairs are * unaffected). */ commandGuardBlocked: Array<{ winner: string; loser: string; similarity: number; reason: typeof COMMAND_GUARD_REASON; }>; /** * FEAT-552 sub-scope C (AC-C1): count of pending `kind='merge'` proposals * the dup-judge sweep refused to auto-resolve (accept OR reject) this run * because the command-token guard tripped — left pending with a guard * marker in `metadata_json` instead (see `annotateCommandGuardBlocked`). * Always 0 when dup-judge is off/disabled or no guarded pair was pending. */ dupJudgeCommandGuardBlocked: number; } export interface AtomRow { id: string; rowid: number; repo: string | null; type: string; text: string; importance: number; created_at: number; derived_from: string | null; } /** * All C(n,2) pairs in a group, in the exact i; /** * P2.1: per-atom top-`k` nearest-neighbor query via the existing * `VectorStore.search()` abstraction — same infra `/recall` uses, no new * dependency. `Config['consolidation']['candidateSelection']`'s doc * comment explains why this is a JS post-filter rather than a same-query * metadata filter: sqlite-vec's adapter throws on a non-empty `VecFilter` * today (`src/vector/sqlite-vec.ts`'s `search()` — "VecFilter not yet * implemented"), so hits are filtered down to the current (repo,type) * group's own atom ids here instead. Symmetric pairs are deduplicated via * a canonical min/max-id key (same pair-identity convention * `insertContradictionProposal`'s `MIN(winner_id,loser_id)`/ * `MAX(winner_id,loser_id)` SQL guard already uses — just an in-memory Set * instead of a DB `WHERE NOT EXISTS`). O(n^2) -> O(n*k). * * Cooperative-yields during the search phase too (ADR-019 Tier 1, * `yieldEveryNPairs` reused as the cadence) — each `vectorStore.search()` * call runs a synchronous better-sqlite3 MATCH query under the hood, so * without a periodic `setImmediate` yield here a large group's * CANDIDATE-GENERATION phase (not just its later pair-processing phase) * could itself become one long uninterrupted stretch. */ export declare function buildKnnCandidatePairs(group: readonly AtomRow[], vecs: ReadonlyMap, vectorStore: VectorStore, k: number, opts?: { yieldEveryNPairs?: number; onYield?: () => void; }): Promise>; /** * Normalization for the containment rule: lowercase, strip backticks/quotes * and punctuation, collapse whitespace. Deliberately aggressive — it only * gates WHICH near-duplicates skip the manual queue, never what merging does. */ export declare function normalizeForContainment(text: string): string; /** * 'a-contains-b' | 'b-contains-a' | 'equal' | null. Guards trivially short * texts (a 3-char normalized string is contained in almost anything). */ export declare function containment(aText: string, bText: string): 'a-contains-b' | 'b-contains-a' | 'equal' | null; /** Exported for reuse by the memory-health CLI's near-duplicate estimate * (FEAT-444, deep/CLI-only metric) — same cosine-over-stored-embeddings * math this module already uses for merge/propose decisions, no second * implementation. */ export declare function cosine(a: Float32Array, b: Float32Array): number; /** * Merge-as-supersede: loser superseded by winner (event log + valid_to + * memory_corrected usefulness signal, all via MemoryEventRepo.supersede), * plus lineage — winner.derived_from gains the loser id. One transaction. * * `provenance` (FEAT-442) is forwarded to `MemoryEventRepo.supersede()` * untouched — see that method and {@link SupersedeProvenance}. Omitted by * every pre-existing caller (containment auto-merge, human * `ProposalRepo.accept`), so their payload shape is unchanged. * * `correctionSource` (issue #190) is REQUIRED, deliberately with no default — * every call site in this module is either fully automatic (containment tier, * mergeThreshold tier: always `'consolidation_auto'`) or routes through * `ProposalRepo.accept`, which itself decides `'consolidation_auto'` vs * `'external'` based on whether a human resolved the proposal (see * `proposals.ts`). Forcing every caller to say which, rather than defaulting, * is exactly what a silently-wrong default would have re-created here. */ export declare function mergeAsSupersede(db: DB, winnerId: string, loserId: string, provenance: SupersedeProvenance | undefined, correctionSource: CorrectionSource): void; /** * FEAT-499 stage 1 (instrument-first, competitive-teardown steal #2, Mnemon * internal/search/diff.go, Apache-2.0). The judge is already gated to pairs * in [minSimilarity, mergeThreshold) — see `resolveContradictionDetection` * above. Mnemon's insight is that cosine similarity ABOVE this band's own * 0.90 boundary is almost always the same fact restated, not a genuine * contradiction candidate, and could in principle skip the judge entirely * via a cheap deterministic short-circuit. This constant marks that * boundary for INSTRUMENTATION only — counting how many real judge calls * fall in [NEAR_MERGE_THRESHOLD_MIN, mergeThreshold) — so a stage-2 filter * (only added later, gated on this measurement showing >= 20% of calls in * that band) has real evidence instead of a guess. No skip/filter exists * yet; this never changes which pairs get judged. */ export declare const NEAR_MERGE_THRESHOLD_MIN = 0.9; export declare function runConsolidation(db: DB, opts?: ConsolidateOpts): Promise;