/** * Memory-health score (FEAT-444) — read-only per-store health metrics shared * by three surfaces: the `doctor` CLI row, `GET /health`'s `memory_health` * detail block, and the `astramem-local memory health` CLI report. One * `MemoryHealthReport` shape, built here, consumed by all three — mirrors * how `SessionDigest` (this same directory, provenance.ts) is the one shape * shared between the HTTP digest route and the MCP `session_digest` tool. * * BINDING split from the 2026-07-08 design review (design-review artifact, * FEAT-444 section): `GET /health` regressed to an accidental O(N) full * scan once already this week (migration 019 fixed `usefulnessRate()`'s * unindexed `memory_events` scan) — this module must not repeat that * mistake on the same endpoint in the same week. So there are two tiers: * * - `buildMemoryHealthCheap()` — O(1)/index-backed ONLY. Every query here * rides an existing index (idx_memories_archival_candidates, * idx_memory_events_usefulness_served/used from migration 019, * idx_memory_events_correction_type from migration 020, idx_jobs_state * from 001-init) — no new migration needed, no per-request full table * scan, no similarity computation. This is the ONLY tier `/health` may * use (AC-2). * - `buildMemoryHealthFull()` — adds byType/byScope breakdowns and the * staleness distribution, which have no covering index and are * genuinely O(N) group-bys. Fine for `doctor` (AC-1) and the CLI report * (AC-3) — both are operator-invoked, off the hot path, read-only. * * Deep metrics (near-duplicate estimate, junk heuristic, optional * LLM-judged sample) are CLI-only and live in memory-health-deep.ts — never * wired into `/health` or `doctor`'s default (non---deep) pass. * * Every function here is read-only: no INSERT/UPDATE/DELETE against * memories, memory_events, jobs, or consolidation_proposals (AC-1/AC-3). */ import type { DB } from '../../storage/db.js'; export interface UsefulnessCoverage { /** Distinct active atoms that have ever been served (recall_served event). */ served: number; /** Distinct active atoms that have ever been explicitly used (recall_used event). */ used: number; /** served / activeCount — fraction of active atoms ever surfaced by a * recall/search surface. null when activeCount === 0 (avoids a * misleading 0%, same convention as usefulnessRate()). */ coverageRate: number | null; } export interface CorrectionStats { /** Distinct atoms with an invalidate or supersede event, ever. */ corrected: number; /** corrected / (activeCount + corrected) — approximates "share of * ever-known atoms that got corrected". null when the denominator is 0. */ rate: number | null; } export interface StalenessBucket { /** Human label, e.g. "0-7d". */ label: string; /** Inclusive upper bound in days; null for the open-ended last bucket. */ maxDays: number | null; count: number; } /** One row per (repo ?? '', type) group — mirrors consolidate.ts's own * grouping key so the deep near-duplicate scan (memory-health-deep.ts) * samples the exact same population consolidation would compare. */ export interface MemoryHealthCounts { active: number; archived: number; byType: Record; byScope: Record; } export interface MemoryHealthReport { generatedAt: number; /** Always present — index-backed (idx_memories_archival_candidates). */ activeCount: number; archivedCount: number; /** null on the /health cheap subset; populated by buildMemoryHealthFull() * for doctor/CLI (no covering index for a type/scope group-by — a * genuine O(N) scan, acceptable off the /health hot path only). */ counts: MemoryHealthCounts | null; staleness: StalenessBucket[] | null; /** Always present — rides migration 019's partial indexes. */ usefulness: UsefulnessCoverage; /** Always present — rides migration 020's partial index. */ corrections: CorrectionStats; /** Distinct sessions with at least one permanently-failed ('poison') * distill job — index-backed via idx_jobs_state (state='poison' is the * equality prefix; scoped further to kind='distill' in-query). Always * present. */ poisonDistillSessions: number; } /** * Rolling window (days) `distillSessionStats()` counts terminal/poison * distill sessions over (2026-08-02 poison-metric-window fix). Deliberately * NOT the same denominator as `poisonDistillSessionCount()`/ * `MemoryHealthReport.poisonDistillSessions` above, which stay a lifetime * count for informational display — a lifetime poison RATE can only ever * heal once the retention sweep eventually purges the offending rows * (POISON_JOB_RETENTION_DAYS, job-repo.ts — 90 days), leaving the * POISON_RATE_ALARM doctor/`/health` alarm stuck red for weeks after the * underlying cause has already cleared (e.g. a one-off metered-provider * quota burst). Windowing to the last 7 days makes the alarm answer "is * extraction healthy RIGHT NOW", which is what an operator actually wants * to know when this goes red. 7 days (not, say, 1) still gives * MEANINGFUL_USAGE_THRESHOLD (20 terminal sessions) a realistic chance to * accumulate on a normal-traffic install before the alarm can fire at all. */ export declare const DISTILL_POISON_RATE_WINDOW_DAYS = 7; export interface DistillSessionStats { /** The rolling window (days) `terminal`/`poison`/`poisonRate` below were * computed over — see DISTILL_POISON_RATE_WINDOW_DAYS. Echoed back so a * consumer (doctor message, /health wire field) can state it without * re-importing the constant. */ windowDays: number; /** Distinct session_id values among distill jobs that reached a terminal * state (completed or poison) within the last `windowDays` days (by * `updated_at`, i.e. when the job actually transitioned, not when it was * enqueued). Pending/running/retrying('failed') jobs are excluded — they * have not concluded yet, so counting them would move the denominator * under a still-running backlog rather than reflecting outcomes. */ terminal: number; /** Distinct session_id values among distill jobs that transitioned to the * 'poison' state (permanently failed after exhausting retries, * JobRepo.markPoison) within the same `windowDays`-day window. */ poison: number; /** poison / terminal. null when terminal === 0 (nothing concluded yet in * the window to judge a rate from — mirrors the null convention * usefulnessRate() and correctionStats() above already use for an empty * denominator). */ poisonRate: number | null; } /** * The ADR-015 rule 6 "state the denominator" counter checkMemoryHealth was * missing — its only return path was `{ok: true}`; a 100% poison rate still * reported "memory health: OK" (see checks.ts's doc comment on * checkMemoryHealth). Both queries below ride idx_jobs_distill_terminal_window * (migration 060, partial `WHERE kind = 'distill'` indexed on (state, * updated_at)) — see that migration's comment for why neither pre-existing * jobs index (idx_jobs_state, idx_jobs_distill_session) covers this shape. * Degrades to a null rate rather than throwing on a bare/pre-migration test * DB (e.g. no `jobs` table at all). */ export declare function distillSessionStats(db: DB, opts?: { windowDays?: number; }): DistillSessionStats; /** * The ONLY builder `GET /health` (src/server/routes/health.ts) may call — * every query above is index-backed; none scans the full memories or * memory_events table. `counts`/`staleness` are null here by design (see * file header) — populate them via buildMemoryHealthFull() for doctor/CLI. */ export declare function buildMemoryHealthCheap(db: DB): MemoryHealthReport; /** * Full report: the cheap tier plus byType/byScope + staleness. Used by * `doctor` (AC-1) and `astramem-local memory health` (AC-3) — both * operator-invoked and off the /health hot path, so the extra O(N) * group-bys are acceptable here per the design review's recommendation. */ export declare function buildMemoryHealthFull(db: DB): MemoryHealthReport;